🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Add error tracking feature and update documentation (#418)
Bill Yang38e0c0fba9c2
diff --git a/.claude/settings.local.json b/.claude/settings.local.jsonindex ce8e3d913..57edeb70a 100644--- a/.claude/settings.local.json+++ b/.claude/settings.local.json@@ -15,7 +15,8 @@"Bash(npm run build:*)","Bash(npm run:*)","Bash(mv:*)",- "Bash(chmod:*)"+ "Bash(chmod:*)",+ "Bash(rg:*)"]},"enableAllProjectMcpServers": falsediff --git a/client/package-lock.json b/client/package-lock.jsonindex 211018cb8..75755d66b 100644--- a/client/package-lock.json+++ b/client/package-lock.json@@ -1,12 +1,12 @@{"name": "client",- "version": "1.1.0",+ "version": "1.3.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "client",- "version": "1.1.0",+ "version": "1.3.0","dependencies": {"@hookform/resolvers": "5.0.1","@nivo/bar": "0.96.0",diff --git a/client/src/api/analytics/errors/useGetErrorBucketed.ts b/client/src/api/analytics/errors/useGetErrorBucketed.tsnew file mode 100644index 000000000..f5a2185f1--- /dev/null+++ b/client/src/api/analytics/errors/useGetErrorBucketed.ts@@ -0,0 +1,41 @@+import { useStore } from "@/lib/store";+import { useQuery, UseQueryResult } from "@tanstack/react-query";+import { authedFetch, getQueryParams } from "../../utils";++// This should match GetErrorBucketedResponse from the backend+export type GetErrorBucketedResponse = {+ time: string;+ error_count: number;+}[];++type UseGetErrorBucketedOptions = {+ errorMessage: string;+ enabled?: boolean;+};++export function useGetErrorBucketed({+ errorMessage,+ enabled = true,+}: UseGetErrorBucketedOptions): UseQueryResult<GetErrorBucketedResponse> {+ const { time, site, filters, bucket } = useStore();++ const queryParams = {+ ...getQueryParams(time),+ bucket,+ errorMessage,+ filters,+ };++ return useQuery({+ queryKey: ["error-bucketed", time, site, filters, bucket, errorMessage],+ queryFn: () => {+ return authedFetch<any>(`/error-bucketed/${site}`, queryParams).then(+ (res) => {+ return res.data;+ }+ );+ },+ enabled: enabled && !!errorMessage && !!site,+ staleTime: Infinity,+ });+}diff --git a/client/src/api/analytics/errors/useGetErrorEvents.ts b/client/src/api/analytics/errors/useGetErrorEvents.tsnew file mode 100644index 000000000..c51a72956--- /dev/null+++ b/client/src/api/analytics/errors/useGetErrorEvents.ts@@ -0,0 +1,87 @@+import { useStore } from "@/lib/store";+import { useInfiniteQuery } from "@tanstack/react-query";+import { APIResponse } from "../../types";+import { authedFetch, getQueryParams } from "../../utils";++// This should match ErrorEvent from the backend+export type ErrorEvent = {+ timestamp: string;+ session_id: string;+ user_id: string | null;+ pathname: string | null;+ hostname: string | null;+ page_title: string | null;+ referrer: string | null;+ browser: string | null;+ browser_version: string | null;+ operating_system: string | null;+ operating_system_version: string | null;+ device_type: string | null;+ country: string | null;+ city: string | null;+ region: string | null;+ // Parsed error properties (now from backend)+ message: string;+ stack: string | null;+ fileName: string | null;+ lineNumber: number | null;+ columnNumber: number | null;+};++// This should match the paginated response structure from getErrorEvents.ts+export type ErrorEventsPaginatedResponse = {+ data: ErrorEvent[];+ totalCount: number;+};++// This is for non-paginated use+export type ErrorEventsStandardResponse = ErrorEvent[];++type UseGetErrorEventsOptions = {+ errorMessage: string;+ limit?: number;+ page?: number;+ useFilters?: boolean;+ enabled?: boolean;+};++// Hook for infinite scrolling+export function useGetErrorEventsInfinite(+ errorMessage: string,+ enabled: boolean = true+) {+ const { time, site, filters } = useStore();++ return useInfiniteQuery({+ queryKey: ["error-events-infinite", time, site, filters, errorMessage],+ queryFn: async ({ pageParam = 1 }) => {+ const queryParams = {+ ...getQueryParams(time),+ errorMessage,+ limit: 20,+ page: pageParam,+ filters,+ };++ return authedFetch<APIResponse<ErrorEventsPaginatedResponse>>(+ `/error-events/${site}`,+ queryParams+ );+ },+ initialPageParam: 1,+ getNextPageParam: (+ lastPage: APIResponse<ErrorEventsPaginatedResponse>,+ allPages+ ) => {+ const currentPage = allPages.length;+ const totalItems = lastPage.data?.totalCount || 0;+ const itemsPerPage = 20;+ const totalPages = Math.ceil(totalItems / itemsPerPage);++ return currentPage < totalPages ? currentPage + 1 : undefined;+ },+ enabled: enabled && !!errorMessage && !!site,+ staleTime: Infinity,+ });+}+diff --git a/client/src/api/analytics/errors/useGetErrorNames.ts b/client/src/api/analytics/errors/useGetErrorNames.tsnew file mode 100644index 000000000..7ae0e8643--- /dev/null+++ b/client/src/api/analytics/errors/useGetErrorNames.ts@@ -0,0 +1,84 @@+import { useStore } from "@/lib/store";+import { useQuery, UseQueryResult } from "@tanstack/react-query";+import { APIResponse } from "../../types";+import { authedFetch, getQueryParams } from "../../utils";++// This should match ErrorNameItem from the backend+export type ErrorNameItem = {+ value: string; // Error message+ errorName: string; // Error type (TypeError, ReferenceError, etc.)+ count: number; // Total occurrences+ sessionCount: number; // Unique sessions affected+ percentage: number;+};++// This should match the paginated response structure from getErrorNames.ts+export type ErrorNamesPaginatedResponse = {+ data: ErrorNameItem[];+ totalCount: number;+};++// This is for non-paginated use by StandardSection (or similar)+export type ErrorNamesStandardResponse = ErrorNameItem[];++type UseGetErrorNamesOptions = {+ limit?: number;+ page?: number;+ useFilters?: boolean;+};++// Hook for paginated fetching (e.g., for a dedicated "All Errors" screen)+export function useGetErrorNamesPaginated({+ limit = 10,+ page = 1,+ useFilters = true,+}: UseGetErrorNamesOptions): UseQueryResult<+ APIResponse<ErrorNamesPaginatedResponse>+> {+ const { time, site, filters } = useStore();++ const queryParams = {+ ...getQueryParams(time),+ limit,+ page,+ filters: useFilters ? filters : undefined,+ };++ return useQuery({+ queryKey: ["error-names", time, site, filters, limit, page],+ queryFn: () => {+ return authedFetch<APIResponse<ErrorNamesPaginatedResponse>>(+ `/error-names/${site}`,+ queryParams+ );+ },+ staleTime: Infinity,+ });+}++// Hook for standard (non-paginated) fetching+export function useGetErrorNames({+ limit = 10,+ useFilters = true,+}: Omit<UseGetErrorNamesOptions, "page">): UseQueryResult<+ APIResponse<ErrorNamesStandardResponse>+> {+ const { time, site, filters } = useStore();++ const queryParams = {+ ...getQueryParams(time),+ limit,+ filters: useFilters ? filters : undefined,+ };++ return useQuery({+ queryKey: ["error-names", time, site, filters, limit],+ queryFn: () => {+ return authedFetch<APIResponse<ErrorNamesStandardResponse>>(+ `/error-names/${site}`,+ queryParams+ );+ },+ staleTime: Infinity,+ });+}diff --git a/client/src/app/[site]/components/Sidebar/Sidebar.tsx b/client/src/app/[site]/components/Sidebar/Sidebar.tsxindex 3ed630c76..03a4475c5 100644--- a/client/src/app/[site]/components/Sidebar/Sidebar.tsx+++ b/client/src/app/[site]/components/Sidebar/Sidebar.tsx@@ -1,6 +1,7 @@"use client";import { Funnel, Target } from "@phosphor-icons/react/dist/ssr";import {+ AlertTriangle,Earth,Gauge,LayoutDashboard,@@ -46,7 +47,7 @@ export function Sidebar() {<div className="p-3 border-b border-neutral-800 flex flex-col gap-2"><SiteSelector /></div>- <div className="flex flex-col space-y-1 p-3 ">+ <div className="flex flex-col p-3 "><LiveUserCount /><SidebarLinklabel="Main"@@ -124,6 +125,12 @@ export function Sidebar() {href={getTabPath("events")}icon={<MousePointerClick className="w-4 h-4" />}/>+ <SidebarLink+ label="Errors"+ active={isActiveTab("errors")}+ href={getTabPath("errors")}+ icon={<AlertTriangle className="w-4 h-4" />}+ />{/* <SidebarLinklabel="Reports"active={isActiveTab("reports")}diff --git a/client/src/app/[site]/errors/components/EnableErrorTracking.tsx b/client/src/app/[site]/errors/components/EnableErrorTracking.tsxnew file mode 100644index 000000000..622c0d2a6--- /dev/null+++ b/client/src/app/[site]/errors/components/EnableErrorTracking.tsx@@ -0,0 +1,66 @@+"use client";++import { AlertTriangle, ArrowRight } from "lucide-react";+import Link from "next/link";+import {+ Alert,+ AlertDescription,+ AlertTitle,+} from "../../../../components/ui/alert";+import { Button } from "../../../../components/ui/button";+import { useGetErrorNames } from "../../../../api/analytics/errors/useGetErrorNames";++export function EnableErrorTracking() {+ const {+ data: errorData,+ isLoading,+ isError,+ } = useGetErrorNames({ limit: 1 });++ // Don't show banner while loading or if there's an error+ if (isLoading || isError) return null;++ const errors = errorData?.data ?? [];++ // Only show banner if there are no errors tracked+ if (errors.length > 0) return null;++ return (+ <Alert className="p-4 bg-amber-50/50 border-amber-200/50 dark:bg-amber-900/10 dark:border-amber-800/50">+ <div className="flex items-start space-x-3">+ <AlertTriangle className="h-5 w-5 mt-0.5 text-amber-500/80" />+ <div className="flex-1">+ <AlertTitle className="text-base font-semibold mb-1 text-amber-700/90 dark:text-amber-400/90">+ Enable Error Tracking+ </AlertTitle>+ <AlertDescription className="text-sm text-amber-700/80 dark:text-amber-400/80 mb-3">+ Add{" "}+ <code className="bg-amber-100/70 dark:bg-amber-800/50 px-1 py-0.5 rounded text-xs">+ data-tracking-errors="true"+ </code>{" "}+ to your script tag. <strong>Note:</strong> Enabling error tracking+ will increase your event usage.+ </AlertDescription>++ <div className="space-y-2">+ <div className="flex flex-col space-y-2 sm:flex-row sm:space-y-0 sm:space-x-2 items-start sm:items-center">+ <Button+ asChild+ variant="outline"+ size="sm"+ className="border-amber-300/70 text-amber-700/90 hover:bg-amber-100/70 dark:border-amber-600/70 dark:text-amber-400/90 dark:hover:bg-amber-800/50"+ >+ <Link+ href="https://rybbit.io/docs/script#error-tracking"+ target="_blank"+ >+ View Documentation <ArrowRight className="ml-1 h-3 w-3" />+ </Link>+ </Button>+ </div>+ </div>+ </div>+ </div>+ </Alert>+ );+}diff --git a/client/src/app/[site]/errors/components/ErrorDetails.tsx b/client/src/app/[site]/errors/components/ErrorDetails.tsxnew file mode 100644index 000000000..3d6eda9dd--- /dev/null+++ b/client/src/app/[site]/errors/components/ErrorDetails.tsx@@ -0,0 +1,382 @@+"use client";++import {+ ErrorEvent,+ useGetErrorEventsInfinite,+} from "@/api/analytics/errors/useGetErrorEvents";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { userLocale } from "@/lib/dateTimeUtils";+import { useGetRegionName } from "@/lib/geo";+import { getCountryName } from "@/lib/utils";+import {+ AlertTriangle,+ Code,+ Hash,+ Laptop,+ Loader2,+ Smartphone,+ TriangleAlert,+ User,+} from "lucide-react";+import { DateTime } from "luxon";+import Link from "next/link";+import { memo, useMemo } from "react";+import { Browser } from "../../components/shared/icons/Browser";+import { CountryFlag } from "../../components/shared/icons/CountryFlag";+import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";++interface ErrorDetailsProps {+ errorMessage: string;+}++// DeviceIcon component for displaying mobile/desktop icons+function DeviceIcon({ deviceType }: { deviceType: string | null }) {+ if (!deviceType) return <Laptop className="w-4 h-4" />;++ const type = deviceType.toLowerCase();+ if (type.includes("mobile") || type.includes("tablet")) {+ return <Smartphone className="w-4 h-4" />;+ }+ return <Laptop className="w-4 h-4" />;+}++// Function to truncate text for display+function truncateText(text: string | null, maxLength: number = 50) {+ if (!text) return "-";+ if (text.length <= maxLength) return text;+ return `${text.substring(0, maxLength)}...`;+}++// Component to display individual error event+function ErrorEventItem({ errorEvent }: { errorEvent: ErrorEvent }) {+ const { getRegionName } = useGetRegionName();++ const getFullLocation = (event: ErrorEvent) => {+ let location = "";+ if (event.city) {+ location += `${event.city}, `;+ }+ if (event.region && getRegionName(event.region)) {+ location += `${getRegionName(event.region)}, `;+ }+ if (event.country) {+ location += getCountryName(event.country);+ }+ return location || "Unknown location";+ };++ const formatTimestamp = (timestamp: string) => {+ return DateTime.fromSQL(timestamp, { zone: "utc" })+ .setLocale(userLocale)+ .toRelative();+ };++ return (+ <div className="border border-neutral-800 rounded-lg p-4 bg-neutral-900/50">+ {/* Header with timestamp and basic info */}+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-4">+ <span className="text-sm text-neutral-200">+ {formatTimestamp(errorEvent.timestamp)}+ </span>+ <div className="flex items-center gap-2">+ {errorEvent.country && (+ <Tooltip>+ <TooltipTrigger>+ <CountryFlag country={errorEvent.country} />+ </TooltipTrigger>+ <TooltipContent>+ <p>{getFullLocation(errorEvent)}</p>+ </TooltipContent>+ </Tooltip>+ )}+ {errorEvent.browser && (+ <Tooltip>+ <TooltipTrigger>+ <Browser browser={errorEvent.browser} />+ </TooltipTrigger>+ <TooltipContent>+ <p>+ {errorEvent.browser}+ {errorEvent.browser_version &&+ ` ${errorEvent.browser_version}`}+ </p>+ </TooltipContent>+ </Tooltip>+ )}+ {errorEvent.operating_system && (+ <Tooltip>+ <TooltipTrigger>+ <OperatingSystem os={errorEvent.operating_system} />+ </TooltipTrigger>+ <TooltipContent>+ <p>+ {errorEvent.operating_system}+ {errorEvent.operating_system_version &&+ ` ${errorEvent.operating_system_version}`}+ </p>+ </TooltipContent>+ </Tooltip>+ )}+ <Tooltip>+ <TooltipTrigger>+ <DeviceIcon deviceType={errorEvent.device_type} />+ </TooltipTrigger>+ <TooltipContent>+ <p>{errorEvent.device_type || "Unknown device"}</p>+ </TooltipContent>+ </Tooltip>+ </div>+ <Link+ href={`https://${errorEvent.hostname}${errorEvent.pathname}`}+ target="_blank"+ rel="noopener noreferrer"+ className="text-sm text-neutral-300 break-words hover:underline"+ >+ {errorEvent.hostname && errorEvent.pathname+ ? `${errorEvent.hostname}${errorEvent.pathname}`+ : errorEvent.pathname || errorEvent.hostname || "Unknown page"}+ </Link>+ </div>+ <div className="flex items-center gap-2">+ {/* Session ID */}+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="outline" className="text-xs">+ <Hash className="w-3 h-3 mr-1" />+ {errorEvent.session_id.substring(0, 8)}+ </Badge>+ </TooltipTrigger>+ <TooltipContent>Session ID: {errorEvent.session_id}</TooltipContent>+ </Tooltip>++ {/* User ID if available */}+ {errorEvent.user_id && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="outline" className="text-xs">+ <User className="w-3 h-3 mr-1" />+ {errorEvent.user_id.substring(0, 8)}+ </Badge>+ </TooltipTrigger>+ <TooltipContent>User ID: {errorEvent.user_id}</TooltipContent>+ </Tooltip>+ )}+ </div>+ </div>++ {/* Error message */}+ <div className="mb-3">+ <div className="flex items-start gap-2 text-red-400">+ <TriangleAlert className="w-4 h-4 mt-0.5 flex-shrink-0" />+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium mb-1">Error</p>+ <p className="text-sm text-neutral-300 break-words">+ {errorEvent.message || "No message available"}+ </p>+ </div>+ </div>+ </div>++ {/* Stack trace if available */}+ {errorEvent.stack && (+ <div className="mt-3 pt-3 border-t border-neutral-700">+ <div className="flex items-start gap-2">+ <Code className="w-4 h-4 text-neutral-100 mt-0.5 flex-shrink-0" />+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium text-neutral-100 mb-1">+ Stack Trace:+ </p>+ {/* File and line info */}+ {(errorEvent.fileName || errorEvent.lineNumber) && (+ <div className="mb-2">+ <div className="flex-1 min-w-0">+ <Link+ href={`${errorEvent.fileName}`}+ className="text-sm text-neutral-300 break-words hover:underline"+ target="_blank"+ rel="noopener noreferrer"+ >+ {errorEvent.fileName && (+ <span>{truncateText(errorEvent.fileName, 100)}</span>+ )}+ {errorEvent.lineNumber && (+ <span className="text-neutral-100">+ :{errorEvent.lineNumber}+ {errorEvent.columnNumber &&+ `:${errorEvent.columnNumber}`}+ </span>+ )}+ </Link>+ </div>+ </div>+ )}+ <pre className="text-xs text-neutral-100 bg-neutral-800 p-2 rounded overflow-x-auto whitespace-pre-wrap break-words">+ {errorEvent.stack}+ </pre>+ </div>+ </div>+ </div>+ )}+ </div>+ );+}++export function ErrorDetails({ errorMessage }: ErrorDetailsProps) {+ const {+ data: errorEventsData,+ isLoading,+ isError,+ error,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ } = useGetErrorEventsInfinite(errorMessage, !!errorMessage);++ // Flatten all error events into a single array+ const allErrorEvents = useMemo(() => {+ if (!errorEventsData?.pages) return [];+ return errorEventsData.pages.flatMap((page) => page.data?.data || []);+ }, [errorEventsData?.pages]);++ // Get total count from the first page+ const totalCount = errorEventsData?.pages?.[0]?.data?.totalCount || 0;++ if (isLoading) {+ return (+ <div className="p-4 bg-neutral-900 border-t border-neutral-800">+ <div className="space-y-3">+ {Array.from({ length: 3 }).map((_, index) => (+ <div+ key={index}+ className="border border-neutral-800 rounded-lg p-4 bg-neutral-900/50"+ >+ {/* Header with timestamp and icons */}+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-4">+ <Skeleton className="h-4 w-20" /> {/* Timestamp */}+ <div className="flex items-center gap-2">+ <Skeleton className="h-4 w-4 rounded" />{" "}+ {/* Country flag */}+ <Skeleton className="h-4 w-4 rounded" />{" "}+ {/* Browser icon */}+ <Skeleton className="h-4 w-4 rounded" /> {/* OS icon */}+ <Skeleton className="h-4 w-4 rounded" /> {/* Device icon */}+ </div>+ <Skeleton className="h-4 w-48" /> {/* URL */}+ </div>+ <div className="flex items-center gap-2">+ <Skeleton className="h-5 w-16 rounded-full" />{" "}+ {/* Session badge */}+ <Skeleton className="h-5 w-16 rounded-full" />{" "}+ {/* User badge */}+ </div>+ </div>++ {/* Error message section */}+ <div className="mb-3">+ <div className="flex items-start gap-2">+ <Skeleton className="h-4 w-4 mt-0.5" /> {/* Error icon */}+ <div className="flex-1 min-w-0">+ <Skeleton className="h-4 w-12 mb-1" /> {/* "Error" label */}+ <Skeleton className="h-4 w-full mb-1" />{" "}+ {/* Error message line 1 */}+ <Skeleton className="h-4 w-3/4" />{" "}+ {/* Error message line 2 */}+ </div>+ </div>+ </div>++ {/* Stack trace section (randomly show/hide) */}+ {Math.random() > 0.5 && (+ <div className="mt-3 pt-3 border-t border-neutral-700">+ <div className="flex items-start gap-2">+ <Skeleton className="h-4 w-4 mt-0.5" /> {/* Code icon */}+ <div className="flex-1 min-w-0">+ <Skeleton className="h-4 w-20 mb-1" />{" "}+ {/* "Stack Trace:" label */}+ <Skeleton className="h-4 w-64 mb-2" />{" "}+ {/* File name and line */}+ <Skeleton className="h-16 w-full rounded" />{" "}+ {/* Stack trace code block */}+ </div>+ </div>+ </div>+ )}+ </div>+ ))}+ </div>+ </div>+ );+ }++ if (isError) {+ return (+ <div className="p-4 bg-neutral-900 border-t border-neutral-800">+ <div className="text-center text-red-400">+ <AlertTriangle className="w-6 h-6 mx-auto mb-2" />+ <p>Error loading error details</p>+ <p className="text-sm text-neutral-400">{error?.toString()}</p>+ </div>+ </div>+ );+ }++ if (!allErrorEvents || allErrorEvents.length === 0) {+ return (+ <div className="p-4 bg-neutral-900 border-t border-neutral-800">+ <div className="text-center text-neutral-400">+ <AlertTriangle className="w-6 h-6 mx-auto mb-2" />+ <p>No error events found</p>+ <p className="text-sm">+ This error may have occurred outside the current time range.+ </p>+ </div>+ </div>+ );+ }++ return (+ <div className="p-4 bg-neutral-900 border-t border-neutral-800 space-y-3 max-h-[70vh] overflow-y-auto">+ {allErrorEvents.map((errorEvent, index) => (+ <ErrorEventItem+ key={`${errorEvent.session_id}-${errorEvent.timestamp}-${index}`}+ errorEvent={errorEvent}+ />+ ))}++ {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>+ )}++ {totalCount > 0 && (+ <div className="text-center text-xs text-gray-500 mt-2">+ Showing {allErrorEvents.length} of {totalCount} error events+ </div>+ )}+ </div>+ );+}diff --git a/client/src/app/[site]/errors/components/ErrorListItem.tsx b/client/src/app/[site]/errors/components/ErrorListItem.tsxnew file mode 100644index 000000000..d31747f05--- /dev/null+++ b/client/src/app/[site]/errors/components/ErrorListItem.tsx@@ -0,0 +1,114 @@+"use client";++import { truncateString } from "@/lib/utils";+import { ChevronDown, ChevronRight } from "lucide-react";+import { useState } from "react";+import { ErrorDetails } from "./ErrorDetails";+import { ErrorSparklineChart } from "./ErrorSparklineChart";+import { useGetErrorBucketed } from "@/api/analytics/errors/useGetErrorBucketed";+import { ErrorNameItem } from "../../../../api/analytics/errors/useGetErrorNames";++// Maximum length for error messages+const MAX_ERROR_MESSAGE_LENGTH = 150;++type ErrorListItemProps = {+ errorData: ErrorNameItem;+};++export function ErrorListItem({ errorData }: ErrorListItemProps) {+ const [expanded, setExpanded] = useState(false);+ const [isHovering, setIsHovering] = useState(false);++ const handleCardClick = () => {+ setExpanded(!expanded);+ };++ // Get error bucketed data for sparkline+ const { data: errorBucketedData, isLoading: isLoadingBucketed } =+ useGetErrorBucketed({+ errorMessage: errorData.value,+ enabled: true,+ });++ return (+ <div+ className="mb-3 rounded-lg bg-neutral-900 border border-neutral-800"+ onMouseEnter={() => setIsHovering(true)}+ onMouseLeave={() => setIsHovering(false)}+ >+ <div className="p-3 cursor-pointer" onClick={handleCardClick}>+ <div className="flex flex-col md:flex-row justify-between items-start md:items-center w-full gap-4">+ {/* Left side: Error message with icon */}+ <div className="flex-1 min-w-0 space-y-1">+ <h3 className="text-sm font-medium truncate">+ {errorData.errorName || "JavaScript Error"}+ </h3>+ <p className="text-xs text-muted-foreground">+ {truncateString(errorData.value, MAX_ERROR_MESSAGE_LENGTH)}+ </p>+ </div>++ {/* Right side: Sparkline chart and error statistics */}+ <div className="flex items-center gap-2 w-full md:w-auto">+ {/* Sparkline chart */}+ <div className="h-12 w-56 relative overflow-visible">+ <ErrorSparklineChart+ data={errorBucketedData}+ isHovering={isHovering}+ errorMessage={errorData.value}+ isLoading={isLoadingBucketed}+ />+ </div>++ {/* Error statistics */}+ <div className="flex items-center ">+ {/* Occurrences */}+ <div className="text-center min-w-[80px]">+ <div>+ <span className="text-base font-semibold">+ {errorData.count.toLocaleString()}+ </span>+ </div>+ <div>+ <span className="text-xs text-foreground/70">+ occurrences+ </span>+ </div>+ </div>++ {/* Sessions affected */}+ <div className="text-center min-w-[80px]">+ <div>+ <span className="text-base font-semibold">+ {errorData.sessionCount.toLocaleString()}+ </span>+ </div>+ <div>+ <span className="text-xs text-foreground/70">sessions</span>+ </div>+ </div>++ {/* Expand/Collapse icon */}+ <div className="ml-2 flex-shrink-0 flex">+ {expanded ? (+ <ChevronDown+ className="w-4 h-4 text-gray-400"+ strokeWidth={3}+ />+ ) : (+ <ChevronRight+ className="w-4 h-4 text-gray-400"+ strokeWidth={3}+ />+ )}+ </div>+ </div>+ </div>+ </div>+ </div>++ {/* Expanded content using ErrorDetails component */}+ {expanded && <ErrorDetails errorMessage={errorData.value} />}+ </div>+ );+}diff --git a/client/src/app/[site]/errors/components/ErrorListSkeleton.tsx b/client/src/app/[site]/errors/components/ErrorListSkeleton.tsxnew file mode 100644index 000000000..d6e392a53--- /dev/null+++ b/client/src/app/[site]/errors/components/ErrorListSkeleton.tsx@@ -0,0 +1,66 @@+"use client";++import { Skeleton } from "@/components/ui/skeleton";++type ErrorListSkeletonProps = {+ count?: number;+};++export function ErrorListSkeleton({ count = 5 }: ErrorListSkeletonProps) {+ return (+ <>+ {Array.from({ length: count }).map((_, index) => (+ <div+ key={index}+ className="mb-3 rounded-lg bg-neutral-900 border border-neutral-800"+ >+ <div className="p-3">+ <div className="flex flex-col md:flex-row justify-between items-start md:items-center w-full gap-4">+ {/* Left side: Error name and message */}+ <div className="flex-1 min-w-0 space-y-1">+ <Skeleton className="h-4 w-32" /> {/* Error name (e.g., "TypeError") */}+ <Skeleton className="h-3 w-full max-w-[500px]" /> {/* Error message */}+ </div>++ {/* Right side: Sparkline chart and error statistics */}+ <div className="flex items-center gap-2 w-full md:w-auto">+ {/* Sparkline chart */}+ <div className="h-12 w-56">+ <Skeleton className="h-full w-full rounded" />+ </div>++ {/* Error statistics */}+ <div className="flex items-center">+ {/* Occurrences */}+ <div className="text-center min-w-[80px]">+ <div className="mb-1">+ <Skeleton className="h-5 w-10 mx-auto" /> {/* Count number */}+ </div>+ <div>+ <Skeleton className="h-3 w-16 mx-auto" /> {/* "occurrences" text */}+ </div>+ </div>++ {/* Sessions affected */}+ <div className="text-center min-w-[80px]">+ <div className="mb-1">+ <Skeleton className="h-5 w-8 mx-auto" /> {/* Session count */}+ </div>+ <div>+ <Skeleton className="h-3 w-12 mx-auto" /> {/* "sessions" text */}+ </div>+ </div>++ {/* Expand/Collapse icon */}+ <div className="ml-2 flex-shrink-0">+ <Skeleton className="h-4 w-4" /> {/* Chevron icon */}+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ ))}+ </>+ );+}diff --git a/client/src/app/[site]/errors/components/ErrorSparklineChart.tsx b/client/src/app/[site]/errors/components/ErrorSparklineChart.tsxnew file mode 100644index 000000000..9c20038c1--- /dev/null+++ b/client/src/app/[site]/errors/components/ErrorSparklineChart.tsx@@ -0,0 +1,123 @@+"use client";++import { GetErrorBucketedResponse } from "@/api/analytics/errors/useGetErrorBucketed";+import { hour12, userLocale } from "@/lib/dateTimeUtils";+import { nivoTheme } from "@/lib/nivo";+import { ResponsiveBar } from "@nivo/bar";+import { DateTime } from "luxon";+import { useMemo } from "react";++interface ErrorSparklineChartProps {+ data: GetErrorBucketedResponse | undefined;+ isHovering: boolean;+ errorMessage: string;+ isLoading: boolean;+}++export function ErrorSparklineChart({+ data,+ isHovering,+ errorMessage,+ isLoading,+}: ErrorSparklineChartProps) {+ const chartData = useMemo(() => {+ if (!data || data.length === 0) {+ return [];+ }++ return data+ .filter((e) => {+ // Filter out dates from the future+ return DateTime.fromSQL(e.time).toUTC() <= DateTime.now();+ })+ .map((e) => ({+ time: DateTime.fromSQL(e.time).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),+ errors: e.error_count || 0,+ }));+ }, [data]);++ if (isLoading) {+ return (+ <div className="h-full w-full flex items-center justify-center animate-pulse">+ <div className="h-[1px] w-full bg-border opacity-50"></div>+ </div>+ );+ }++ if (!chartData || chartData.length === 0) {+ return (+ <div className="h-full w-full flex items-center justify-center">+ <div className="h-[1px] w-full bg-border opacity-50"></div>+ </div>+ );+ }++ return (+ <ResponsiveBar+ data={chartData}+ keys={["errors"]}+ indexBy="time"+ margin={{ top: 0, right: 0, bottom: 0, left: 0 }}+ padding={0.3}+ valueScale={{ type: "linear" }}+ indexScale={{ type: "band", round: true }}+ colors={[isHovering ? "hsl(var(--dataviz-2))" : "hsl(var(--dataviz))"]}+ theme={nivoTheme}+ axisTop={null}+ axisRight={null}+ axisBottom={null}+ axisLeft={null}+ enableLabel={false}+ enableGridX={false}+ enableGridY={false}+ tooltip={({+ id,+ value,+ data,+ }: {+ id: string | number;+ value: number;+ data: { time: string; errors: number };+ }) => {+ const currentTime = DateTime.fromFormat(+ data.time,+ "yyyy-MM-dd HH:mm:ss",+ { zone: "utc" }+ ).toLocal();+ const currentY = Number(value);++ return (+ <div+ className="bg-neutral-850 p-2 rounded-md text-xs border border-neutral-750 shadow-lg"+ style={{ zIndex: 9999, position: "relative" }}+ >+ <div className="font-semibold mb-1 text-neutral-200">+ {formatDateTime(currentTime)}+ </div>+ <div className="flex justify-between items-center">+ <span className="font-medium text-red-400">+ {currentY.toLocaleString()}{" "}+ {currentY === 1 ? "error" : "errors"}+ </span>+ </div>+ </div>+ );+ }}+ animate={true}+ motionConfig="gentle"+ borderRadius={1}+ />+ );+}++const formatDateTime = (dt: DateTime) => {+ const options: Intl.DateTimeFormatOptions = {+ month: "short",+ day: "numeric",+ hour: "numeric",+ minute: "numeric",+ hour12: hour12,+ };++ return new Intl.DateTimeFormat(userLocale, options).format(dt.toJSDate());+};diff --git a/client/src/app/[site]/errors/page.tsx b/client/src/app/[site]/errors/page.tsxnew file mode 100644index 000000000..9924ff71e--- /dev/null+++ b/client/src/app/[site]/errors/page.tsx@@ -0,0 +1,158 @@+"use client";++import {+ ErrorNameItem,+ useGetErrorNamesPaginated,+} from "@/api/analytics/errors/useGetErrorNames";+import { Pagination } from "@/components/pagination";+import { useSetPageTitle } from "@/hooks/useSetPageTitle";+import { useStore } from "@/lib/store";+import { useEffect, useState } from "react";+import { DisabledOverlay } from "../../../components/DisabledOverlay";+import { SubHeader } from "../components/SubHeader/SubHeader";+import { ErrorListItem } from "./components/ErrorListItem";+import { ErrorListSkeleton } from "./components/ErrorListSkeleton";+import { EnableErrorTracking } from "./components/EnableErrorTracking";+import { NothingFound } from "../../../components/NothingFound";++// Number of items per page+const PAGE_SIZE = 10;++export default function Errors() {+ const { site } = useStore();++ const [pagination, setPagination] = useState({+ pageIndex: 0,+ pageSize: PAGE_SIZE,+ });+ const [totalPages, setTotalPages] = useState(0);++ useSetPageTitle("Rybbit · Errors");++ // Get page number (1-based) from pageIndex (0-based)+ const pageNumber = pagination.pageIndex + 1;++ const {+ data: apiResponse,+ isLoading: isLoadingErrors,+ isError: isErrorErrors,+ error: errorsError,+ isPlaceholderData,+ isFetching,+ } = useGetErrorNamesPaginated({+ limit: pagination.pageSize,+ page: pageNumber,+ });++ const errorsDataArray: ErrorNameItem[] | undefined = apiResponse?.data?.data;+ const totalCount: number | undefined = apiResponse?.data?.totalCount;++ const isLoading = isLoadingErrors || isFetching;++ // Create a minimal table object with the required pagination methods+ const table = {+ getState: () => ({+ pagination: {+ pageIndex: pagination.pageIndex,+ pageSize: pagination.pageSize,+ },+ }),+ getCanPreviousPage: () => pagination.pageIndex > 0,+ getCanNextPage: () => {+ if (totalCount === undefined) return true;+ return (pagination.pageIndex + 1) * pagination.pageSize < totalCount;+ },+ getPageCount: () => totalPages,+ setPageIndex: (index: number) =>+ setPagination({ ...pagination, pageIndex: index }),+ previousPage: () =>+ setPagination({ ...pagination, pageIndex: pagination.pageIndex - 1 }),+ nextPage: () =>+ setPagination({ ...pagination, pageIndex: pagination.pageIndex + 1 }),+ };++ useEffect(() => {+ if (!isLoadingErrors && !isPlaceholderData && !isFetching) {+ if (totalCount !== undefined) {+ setTotalPages(Math.ceil(totalCount / pagination.pageSize));+ } else if (+ errorsDataArray &&+ errorsDataArray.length === 0 &&+ pagination.pageIndex === 0+ ) {+ // Fallback if totalCount is somehow undefined but we have an empty array on page 1+ setTotalPages(0);+ } else if (+ errorsDataArray &&+ errorsDataArray.length < pagination.pageSize+ ) {+ // Fallback: if less than a full page is returned, assume it's the last+ setTotalPages(pagination.pageIndex + 1);+ }+ } else if (+ pagination.pageIndex === 0 &&+ isLoadingErrors &&+ !errorsDataArray+ ) {+ // Initial load, no data yet+ setTotalPages(0);+ }+ }, [+ apiResponse,+ totalCount,+ errorsDataArray,+ isLoadingErrors,+ isPlaceholderData,+ isFetching,+ pagination.pageIndex,+ pagination.pageSize,+ ]);++ if (!site) {+ return null;+ }++ return (+ <DisabledOverlay message="errors">+ <div className="p-2 md:p-4 max-w-[1100px] mx-auto space-y-3">+ <SubHeader />+ <EnableErrorTracking />++ {isLoading ? (+ <ErrorListSkeleton count={pagination.pageSize} />+ ) : isErrorErrors ? (+ <div className="text-center p-8 text-destructive">+ <p>Error loading errors data</p>+ <p className="text-sm">{errorsError?.toString()}</p>+ </div>+ ) : errorsDataArray && errorsDataArray.length > 0 ? (+ <>+ {errorsDataArray.map((errorItem: ErrorNameItem, index: number) => (+ <ErrorListItem+ key={`${errorItem.value}-${index}-${pagination.pageIndex}`}+ errorData={errorItem}+ />+ ))}+ {totalPages > 0 && (+ <Pagination+ table={table}+ data={{ items: errorsDataArray || [], total: totalCount || 0 }}+ pagination={pagination}+ setPagination={setPagination}+ isLoading={isLoading}+ itemName="errors"+ />+ )}+ </>+ ) : !isLoadingErrors && !isFetching ? (+ <NothingFound+ title={"No error events found"}+ description={+ "Errors will appear here once error tracking is enabled and errors occur on your site."+ }+ />+ ) : null}+ </div>+ </DisabledOverlay>+ );+}diff --git a/client/src/app/[site]/performance/components/EnableWebVitals.tsx b/client/src/app/[site]/performance/components/EnableWebVitals.tsxindex c192ee3d9..532105e90 100644--- a/client/src/app/[site]/performance/components/EnableWebVitals.tsx+++ b/client/src/app/[site]/performance/components/EnableWebVitals.tsx@@ -45,16 +45,16 @@ export function EnableWebVitals() {if (!hasNoWebVitalsData) return null;return (- <Alert className="p-4 bg-blue-50 border-blue-200 dark:bg-blue-900/20 dark:border-blue-800">+ <Alert className="p-4 bg-amber-50/50 border-amber-200/50 dark:bg-amber-900/10 dark:border-amber-800/50"><div className="flex items-start space-x-3">- <BarChart3 className="h-5 w-5 mt-0.5 text-blue-500" />+ <BarChart3 className="h-5 w-5 mt-0.5 text-amber-500/80" /><div className="flex-1">- <AlertTitle className="text-base font-semibold mb-1 text-blue-700 dark:text-blue-400">+ <AlertTitle className="text-base font-semibold mb-1 text-amber-700/90 dark:text-amber-400/90">Enable Web Vitals Collection</AlertTitle>- <AlertDescription className="text-sm text-blue-700 dark:text-blue-400 mb-3">+ <AlertDescription className="text-sm text-amber-700/80 dark:text-amber-400/80 mb-3">Add{" "}- <code className="bg-blue-100 dark:bg-blue-800 px-1 py-0.5 rounded text-xs">+ <code className="bg-amber-100/70 dark:bg-amber-800/50 px-1 py-0.5 rounded text-xs">data-web-vitals="true"</code>{" "}to your script tag. <strong>Note:</strong> Enabling Web Vitals will@@ -67,7 +67,7 @@ export function EnableWebVitals() {asChildvariant="outline"size="sm"- className="border-blue-300 text-blue-700 hover:bg-blue-100 dark:border-blue-600 dark:text-blue-400 dark:hover:bg-blue-800"+ className="border-amber-300/70 text-amber-700/90 hover:bg-amber-100/70 dark:border-amber-600/70 dark:text-amber-400/90 dark:hover:bg-amber-800/50"><Linkhref="https://rybbit.io/docs/script#web-vitals-performance-metrics"diff --git a/client/src/components/SiteSettings/ScriptBuilder.tsx b/client/src/components/SiteSettings/ScriptBuilder.tsxindex c06ffddbc..e6227021a 100644--- a/client/src/components/SiteSettings/ScriptBuilder.tsx+++ b/client/src/components/SiteSettings/ScriptBuilder.tsx@@ -18,6 +18,7 @@ export function ScriptBuilder({ siteId }: ScriptBuilderProps) {const [autoTrack, setAutoTrack] = useState(true);const [trackQuery, setTrackQuery] = useState(true);const [trackOutbound, setTrackOutbound] = useState(true);+ const [trackErrors, setTrackErrors] = useState(false);const [webVitals, setWebVitals] = useState(false);const [skipPatterns, setSkipPatterns] = useState<string[]>([]);const [skipPatternsText, setSkipPatternsText] = useState("");@@ -110,6 +111,11 @@ export function ScriptBuilder({ siteId }: ScriptBuilderProps) {? `data-track-outbound="false"`: ""+ }${+ trackErrors+ ? `+ data-track-errors="true"`+ : ""}${skipPatterns.length > 0? `@@ -212,6 +218,28 @@ export function ScriptBuilder({ siteId }: ScriptBuilderProps) {</div></div>+ {/* Track Errors Option */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <div>+ <Label+ htmlFor="trackErrors"+ className="text-sm font-medium text-foreground block"+ >+ Track JavaScript errors+ </Label>+ <p className="text-xs text-muted-foreground mt-1">+ Automatically capture and track JavaScript errors on your site+ </p>+ </div>+ <Switch+ id="trackErrors"+ checked={trackErrors}+ onCheckedChange={setTrackErrors}+ />+ </div>+ </div>+{/* Track Outbound Links Option */}{/* <div className="space-y-2"><div className="flex items-center justify-between">diff --git a/docs/src/content/script.mdx b/docs/src/content/script.mdxindex 392543cbe..7f5f4157e 100644--- a/docs/src/content/script.mdx+++ b/docs/src/content/script.mdx@@ -21,6 +21,7 @@ You can customize the script's behavior using `data-*` attributes on the `<scrip| `data-track-spa` | `string` | `"true"`| Set to `"false"` to disable automatic pageview tracking for single page applications (React, Vue, etc). You will need to manually call `window.rybbit.pageview()` or `window.rybbit.track()` for all but the initial pageview. || `data-track-query`| `string` | `"true"`| Set to `"false"` to disable tracking of URL query strings. This enhances privacy by preventing potentially sensitive information in query parameters from being stored in your analytics data. || `data-track-outbound` | `string` | `"true"` | Set to `"false"` to disable automatic tracking of outbound link clicks. |+| `data-track-errors` | `string` | `"false"` | Set to `"true"` to enable automatic tracking of JavaScript errors and unhandled promise rejections. Only tracks errors from the same origin to avoid noise from third-party scripts. || `data-web-vitals` | `string` | `"false"`| Set to `"true"` to enable Web Vitals performance metrics collection (LCP, CLS, INP, FCP, TTFB). Web Vitals are disabled by default to reduce script size and network requests. || `data-skip-patterns` | `string` | `[]` | A JSON string array of URL path patterns to ignore. Pageviews matching these patterns won't be tracked. Supports two types of wildcards: `*` (matches within a segment) and `**` (matches across segments). || `data-mask-patterns` | `string` | `[]` | A JSON string array of URL path patterns to mask for privacy. Pageviews matching these patterns will be tracked, but the actual URL path will be replaced with the pattern itself in analytics data. Supports the same wildcards as `data-skip-patterns`. |@@ -54,6 +55,7 @@ data-mask-patterns='["/users/*/settings", "/accounts/**", "/orders/*/details"]'data-skip-patterns='["/admin/**", "/preview/*"]'data-mask-patterns='["/users/*/profile", "/orders/**"]'data-track-query="false"+ data-track-errors="true"data-web-vitals="true"data-debounce="300"></script>@@ -78,3 +80,31 @@ Web Vitals are disabled by default to keep the script lightweight. When enabled></script>```+## Error Tracking++Error tracking is disabled by default to keep the script lightweight and respect user privacy. When enabled with `data-track-errors="true"`, the script will:++- Automatically capture JavaScript errors and unhandled promise rejections+- Filter out errors from third-party scripts (only tracks errors from your domain)+- Truncate error messages and stack traces to prevent excessive data storage+- Send error data to your analytics dashboard for monitoring++**Enable Error Tracking:**+```html+<script+ src="https://app.rybbit.io/api/script.js"+ async+ data-site-id="YOUR_SITE_ID"+ data-track-errors="true"+></script>+```++Error data includes:+- Error type (TypeError, ReferenceError, etc.)+- Error message (truncated to 500 characters)+- Stack trace (truncated to 2000 characters)+- File location and line/column numbers+- Session information for debugging++**Privacy Note:** Error tracking only captures errors originating from your website's domain to avoid noise from browser extensions, third-party scripts, or other external sources.+diff --git a/memory-bank/error-tracking-plan.md b/memory-bank/error-tracking-plan.mdnew file mode 100644index 000000000..a1b365e7b--- /dev/null+++ b/memory-bank/error-tracking-plan.md@@ -0,0 +1,138 @@+# Frontend Error Tracking Implementation Plan++## Overview++This document outlines the implementation plan for adding frontend error tracking to the Rybbit analytics system. Errors will be tracked as a new event type in the existing ClickHouse infrastructure.++## Key Decisions++1. **Storage**: Use existing `props` JSON column in ClickHouse events table+2. **Filtering**: Track only first-party errors (same domain as the website)+3. **Opt-in**: Error tracking requires explicit enablement via `data-track-errors="true"`+4. **Truncation**: Error messages limited to 500 chars, stack traces to 2000 chars++## Implementation Components++### 1. Error Event Structure++Errors will be stored with `type: 'error'` in the events table:++```typescript+{+ site_id: 123,+ type: 'error',+ event_name: 'TypeError', // The error type/name+ props: {+ message: 'Cannot read property...', // Truncated to 500 chars+ stack: '...', // Truncated to 2000 chars+ fileName: 'app.js',+ lineNumber: 42,+ columnNumber: 15,+ timestamp: '2025-01-20T10:30:00Z'+ },+ // Standard fields auto-populated:+ session_id, pathname, referrer, browser, os, device, country, etc.+}+```++### 2. Backend Changes++#### 2.1 Update `server/src/tracker/trackEvent.ts`++- Add 'error' to valid event types+- Validate error-specific properties+- Apply truncation to message (500) and stack (2000)++#### 2.2 Create `server/src/api/analytics/getErrorNames.ts`++- Similar structure to `getPageTitles.ts`+- Query errors grouped by `event_name`+- Return occurrence count and session count+- Support pagination and time filtering++### 3. Analytics Script Updates++#### 3.1 Add Error Capture++- Check for `data-track-errors="true"` attribute+- Install global error handler when enabled+- Filter errors to first-party only (same origin)+- Format and send error data to `/api/track`++#### 3.2 Error Filtering Logic++```javascript+// Only track errors from the same origin+if (error.fileName && !error.fileName.startsWith(window.location.origin)) {+ return; // Skip third-party errors+}+```++### 4. Frontend UI Components++#### 4.1 Create `client/src/api/analytics/useGetErrorNames.ts`++- React Query hook for fetching error data+- Support pagination parameters+- Return error names with counts++#### 4.2 Implement `client/src/app/[site]/errors/page.tsx`++- List view similar to pages implementation+- Display: Error Name | Occurrences | Sessions Affected | Percentage+- Pagination support+- No sparklines in initial version++### 5. Documentation++Update `docs/src/content/script.mdx`:++- Add `data-track-errors` to configuration options table+- Default value: `"false"`+- Description: "Set to 'true' to enable automatic error tracking. When enabled, captures JavaScript errors from your domain only."++## Implementation Order++1. **Backend trackEvent.ts** - Add error type support (validate and store)+2. **Analytics script** - Add error capture with first-party filtering+3. **Backend getErrorNames.ts** - Create the analytics endpoint+4. **Frontend API hook** - Create useGetErrorNames.ts+5. **Frontend UI** - Implement errors/page.tsx+6. **Documentation** - Update script.mdx++## Technical Considerations++### Performance++- Errors stored in existing props JSON column+- ClickHouse handles JSON queries efficiently+- Consider adding dedicated columns if query performance becomes an issue++### Privacy++- First-party only filtering reduces noise and privacy concerns+- Stack traces may contain sensitive file paths - truncation helps+- No personal data should be in error messages++### Rate Limiting++- Consider implementing rate limiting in future iterations+- Suggested: 10 errors per minute per session+- Not included in initial implementation for simplicity++## Future Enhancements++1. **Error Details View**: Click through to see full error details+2. **Browser/OS Breakdown**: Show which browsers are most affected+3. **Time Series**: Show error trends over time+4. **Source Maps**: Support for production source map resolution+5. **Error Grouping**: Smart grouping of similar errors+6. **Alerting**: Notify when error rates spike++## Success Criteria++1. Errors are successfully captured and stored in ClickHouse+2. Error list page shows aggregated error data+3. Only first-party errors are tracked+4. Documentation clearly explains the feature+5. No performance impact on sites that don't enable error trackingdiff --git a/server/public/script-full.js b/server/public/script-full.jsindex 69a8aa0ae..1225e1529 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -72,7 +72,9 @@}const siteId = scriptTag.getAttribute("data-site-id") || scriptTag.getAttribute("site-id");if (!siteId || isNaN(Number(siteId))) {- console.error("Please provide a valid site ID using the data-site-id attribute");+ console.error(+ "Please provide a valid site ID using the data-site-id attribute"+ );return null;}const debounceDuration = scriptTag.getAttribute("data-debounce") ? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce"))) : 500;@@ -94,6 +96,7 @@trackQuerystring: scriptTag.getAttribute("data-track-query") !== "false",trackOutbound: scriptTag.getAttribute("data-track-outbound") !== "false",enableWebVitals: scriptTag.getAttribute("data-web-vitals") === "true",+ trackErrors: scriptTag.getAttribute("data-track-errors") === "true",skipPatterns,maskPatterns,apiKey@@ -165,7 +168,9 @@}track(eventType, eventName = "", properties = {}) {if (eventType === "custom_event" && (!eventName || typeof eventName !== "string")) {- console.error("Event name is required and must be a string for custom events");+ console.error(+ "Event name is required and must be a string for custom events"+ );return;}const basePayload = this.createBasePayload();@@ -176,7 +181,7 @@...basePayload,type: eventType,event_name: eventName,- properties: eventType === "custom_event" || eventType === "outbound" ? JSON.stringify(properties) : void 0+ properties: eventType === "custom_event" || eventType === "outbound" || eventType === "error" ? JSON.stringify(properties) : void 0};this.sendTrackingData(payload);}@@ -202,6 +207,51 @@};this.sendTrackingData(payload);}+ trackError(error, additionalInfo = {}) {+ const currentOrigin = window.location.origin;+ const filename = additionalInfo.filename || "";+ const errorStack = error.stack || "";+ if (filename) {+ try {+ const fileUrl = new URL(filename);+ if (fileUrl.origin !== currentOrigin) {+ return;+ }+ } catch (e2) {+ }+ } else if (errorStack) {+ if (!errorStack.includes(currentOrigin)) {+ return;+ }+ }+ const errorProperties = {+ message: error.message?.substring(0, 500) || "Unknown error",+ // Truncate to 500 chars+ stack: errorStack.substring(0, 2e3) || ""+ // Truncate to 2000 chars+ };+ if (filename) {+ errorProperties.fileName = filename;+ }+ if (additionalInfo.lineno) {+ const lineNum = typeof additionalInfo.lineno === "string" ? parseInt(additionalInfo.lineno, 10) : additionalInfo.lineno;+ if (lineNum && lineNum !== 0) {+ errorProperties.lineNumber = lineNum;+ }+ }+ if (additionalInfo.colno) {+ const colNum = typeof additionalInfo.colno === "string" ? parseInt(additionalInfo.colno, 10) : additionalInfo.colno;+ if (colNum && colNum !== 0) {+ errorProperties.columnNumber = colNum;+ }+ }+ for (const key in additionalInfo) {+ if (!["lineno", "colno"].includes(key) && additionalInfo[key] !== void 0) {+ errorProperties[key] = additionalInfo[key];+ }+ }+ this.track("error", error.name || "Error", errorProperties);+ }identify(userId) {if (typeof userId !== "string" || userId.trim() === "") {console.error("User ID must be a non-empty string");@@ -547,11 +597,28 @@}const tracker = new Tracker(config);if (config.enableWebVitals) {- const webVitalsCollector = new WebVitalsCollector((vitals) => {- tracker.trackWebVitals(vitals);- });+ const webVitalsCollector = new WebVitalsCollector(+ (vitals) => {+ tracker.trackWebVitals(vitals);+ }+ );webVitalsCollector.initialize();}+ if (config.trackErrors) {+ window.addEventListener("error", (event) => {+ tracker.trackError(event.error || new Error(event.message), {+ filename: event.filename,+ lineno: event.lineno,+ colno: event.colno+ });+ });+ window.addEventListener("unhandledrejection", (event) => {+ const error = event.reason instanceof Error ? event.reason : new Error(String(event.reason));+ tracker.trackError(error, {+ type: "unhandledrejection"+ });+ });+ }const trackPageview = () => tracker.trackPageview();const debouncedTrackPageview = config.debounceDuration > 0 ? debounce(trackPageview, config.debounceDuration) : trackPageview;function setupEventListeners() {@@ -575,7 +642,9 @@target = target.parentElement;}if (config.trackOutbound) {- const link = e2.target.closest("a");+ const link = e2.target.closest(+ "a"+ );if (link?.href && isOutboundLink(link.href)) {tracker.trackOutbound(link.href,diff --git a/server/public/script.js b/server/public/script.jsindex 7662a486e..255ba0f73 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var nt=Object.defineProperty;var at=(r,t,e)=>t in r?nt(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var h=(r,t,e)=>at(r,typeof t!="symbol"?t+"":t,e);function st(r){let t="__DOUBLE_ASTERISK_TOKEN__",e="__SINGLE_ASTERISK_TOKEN__",n=r.replace(/\*\*/g,t).replace(/\*/g,e).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`/${t}/`,"g"),"/(?:.+/)?"),n=n.replace(new RegExp(t,"g"),".*"),n=n.replace(/\//g,"\\/");let c=n.replace(new RegExp(e,"g"),"[^/]+");return new RegExp("^"+c+"$")}function P(r,t){for(let e of t)try{if(st(e).test(r))return e}catch(i){console.error(`Invalid pattern: ${e}`,i)}return null}function N(r,t){let e=null;return(...i)=>{e&&clearTimeout(e),e=setTimeout(()=>r(...i),t)}}function W(r){try{let t=window.location.hostname,e=new URL(r).hostname;return e!==t&&e!==""}catch{return!1}}function S(r,t){if(!r)return t;try{let e=JSON.parse(r);return Array.isArray(t)&&!Array.isArray(e)?t:e}catch(e){return console.error("Error parsing JSON:",e),t}}function B(r){let t=r.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 i=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!i||isNaN(Number(i)))return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let n=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,c=S(r.getAttribute("data-skip-patterns"),[]),o=S(r.getAttribute("data-mask-patterns"),[]),a=r.getAttribute("data-api-key")||void 0;return{analyticsHost:e,siteId:i,debounceDuration:n,autoTrackPageview:r.getAttribute("data-auto-track-pageview")!=="false",autoTrackSpa:r.getAttribute("data-track-spa")!=="false",trackQuerystring:r.getAttribute("data-track-query")!=="false",trackOutbound:r.getAttribute("data-track-outbound")!=="false",enableWebVitals:r.getAttribute("data-web-vitals")==="true",skipPatterns:c,maskPatterns:o,apiKey:a}}var b=class{constructor(t){this.customUserId=null;this.config=t,this.loadUserId()}loadUserId(){try{let t=localStorage.getItem("rybbit-user-id");t&&(this.customUserId=t)}catch{}}createBasePayload(){let t=new URL(window.location.href),e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),P(e,this.config.skipPatterns))return null;let i=P(e,this.config.maskPatterns);i&&(e=i);let n={site_id:this.config.siteId,hostname:t.hostname,pathname:e,querystring:this.config.trackQuerystring?t.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(n.user_id=this.customUserId),this.config.apiKey&&(n.api_key=this.config.apiKey),n}async sendTrackingData(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="",i={}){if(t==="custom_event"&&(!e||typeof e!="string")){console.error("Event name is required and must be a string for custom events");return}let n=this.createBasePayload();if(!n)return;let c={...n,type:t,event_name:e,properties:t==="custom_event"||t==="outbound"?JSON.stringify(i):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(t,e={}){this.track("custom_event",t,e)}trackOutbound(t,e="",i="_self"){this.track("outbound","",{url:t,text:e,target:i})}trackWebVitals(t){let e=this.createBasePayload();if(!e)return;let i={...e,type:"performance",event_name:"web-vitals",...t};this.sendTrackingData(i)}identify(t){if(typeof t!="string"||t.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=t.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}};var G=-1,g=r=>{addEventListener("pageshow",t=>{t.persisted&&(G=t.timeStamp,r(t))},!0)},d=(r,t,e,i)=>{let n,c;return o=>{t.value>=0&&(o||i)&&(c=t.value-(n??0),(c||n===void 0)&&(n=t.value,t.delta=c,t.rating=((a,s)=>a>s[1]?"poor":a>s[0]?"needs-improvement":"good")(t.value,e),r(t)))}},M=r=>{requestAnimationFrame(()=>requestAnimationFrame(()=>r()))},R=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},m=()=>R()?.activationStart??0,u=(r,t=-1)=>{let e=R(),i="navigate";return G>=0?i="back-forward-cache":e&&(document.prerendering||m()>0?i="prerender":document.wasDiscarded?i="restore":e.type&&(i=e.type.replace(/_/g,"-"))),{name:r,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},E=new WeakMap;function O(r,t){return E.get(r)||E.set(r,new t),E.get(r)}var C=class{constructor(){h(this,"t");h(this,"i",0);h(this,"o",[])}h(t){if(t.hadRecentInput)return;let e=this.o[0],i=this.o.at(-1);this.i&&e&&i&&t.startTime-i.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)}},f=(r,t,e={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let i=new PerformanceObserver(n=>{Promise.resolve().then(()=>{t(n.getEntries())})});return i.observe({type:r,buffered:!0,...e}),i}}catch{}},x=r=>{let t=!1;return()=>{t||(r(),t=!0)}},p=-1,H=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,y=r=>{document.visibilityState==="hidden"&&p>-1&&(p=r.type==="visibilitychange"?r.timeStamp:0,ot())},V=()=>{addEventListener("visibilitychange",y,!0),addEventListener("prerenderingchange",y,!0)},ot=()=>{removeEventListener("visibilitychange",y,!0),removeEventListener("prerenderingchange",y,!0)},Q=()=>{if(p<0){let r=m();p=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(e=>e.name==="hidden"&&e.startTime>r)[0]?.startTime)??H(),V(),g(()=>{setTimeout(()=>{p=H(),V()})})}return{get firstHiddenTime(){return p}}},T=r=>{document.prerendering?addEventListener("prerenderingchange",()=>r(),!0):r()},F=[1800,3e3],U=(r,t={})=>{T(()=>{let e=Q(),i,n=u("FCP"),c=f("paint",o=>{for(let a of o)a.name==="first-contentful-paint"&&(c.disconnect(),a.startTime<e.firstHiddenTime&&(n.value=Math.max(a.startTime-m(),0),n.entries.push(a),i(!0)))});c&&(i=d(r,n,F,t.reportAllChanges),g(o=>{n=u("FCP"),i=d(r,n,F,t.reportAllChanges),M(()=>{n.value=performance.now()-o.timeStamp,i(!0)})}))})},K=[.1,.25],Y=(r,t={})=>{U(x(()=>{let e,i=u("CLS",0),n=O(t,C),c=a=>{for(let s of a)n.h(s);n.i>i.value&&(i.value=n.i,i.entries=n.o,e())},o=f("layout-shift",c);o&&(e=d(r,i,K,t.reportAllChanges),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(o.takeRecords()),e(!0))}),g(()=>{n.i=0,i=u("CLS",0),e=d(r,i,K,t.reportAllChanges),M(()=>e())}),setTimeout(e))}))},X=0,I=1/0,v=0,ct=r=>{for(let t of r)t.interactionId&&(I=Math.min(I,t.interactionId),v=Math.max(v,t.interactionId),X=v?(v-I)/7+1:0)},L,$=()=>L?X:performance.interactionCount??0,lt=()=>{"interactionCount"in performance||L||(L=f("event",ct,{type:"event",buffered:!0,durationThreshold:0}))},J=0,_=class{constructor(){h(this,"u",[]);h(this,"l",new Map);h(this,"m");h(this,"v")}p(){J=$(),this.u.length=0,this.l.clear()}P(){let t=Math.min(this.u.length-1,Math.floor(($()-J)/50));return this.u[t]}h(t){if(this.m?.(t),!t.interactionId&&t.entryType!=="first-input")return;let e=this.u.at(-1),i=this.l.get(t.interactionId);if(i||this.u.length<10||t.duration>e.T){if(i?t.duration>i.T?(i.entries=[t],i.T=t.duration):t.duration===i.T&&t.startTime===i.entries[0].startTime&&i.entries.push(t):(i={id:t.interactionId,entries:[t],T:t.duration},this.l.set(i.id,i),this.u.push(i)),this.u.sort((n,c)=>c.T-n.T),this.u.length>10){let n=this.u.splice(10);for(let c of n)this.l.delete(c.id)}this.v?.(i)}}},Z=r=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=x(r),document.addEventListener("visibilitychange",r,{once:!0}),t(()=>{r(),document.removeEventListener("visibilitychange",r)}))},q=[200,500],tt=(r,t={})=>{globalThis.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype&&T(()=>{lt();let e,i=u("INP"),n=O(t,_),c=a=>{Z(()=>{for(let l of a)n.h(l);let s=n.P();s&&s.T!==i.value&&(i.value=s.T,i.entries=s.entries,e())})},o=f("event",c,{durationThreshold:t.durationThreshold??40});e=d(r,i,q,t.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(o.takeRecords()),e(!0))}),g(()=>{n.p(),i=u("INP"),e=d(r,i,q,t.reportAllChanges)}))})},A=class{constructor(){h(this,"m")}h(t){this.m?.(t)}},z=[2500,4e3],et=(r,t={})=>{T(()=>{let e=Q(),i,n=u("LCP"),c=O(t,A),o=s=>{t.reportAllChanges||(s=s.slice(-1));for(let l of s)c.h(l),l.startTime<e.firstHiddenTime&&(n.value=Math.max(l.startTime-m(),0),n.entries=[l],i())},a=f("largest-contentful-paint",o);if(a){i=d(r,n,z,t.reportAllChanges);let s=x(()=>{o(a.takeRecords()),a.disconnect(),i(!0)});for(let l of["keydown","click","visibilitychange"])addEventListener(l,()=>Z(s),{capture:!0,once:!0});g(l=>{n=u("LCP"),i=d(r,n,z,t.reportAllChanges),M(()=>{n.value=performance.now()-l.timeStamp,i(!0)})})}})},j=[800,1800],D=r=>{document.prerendering?T(()=>D(r)):document.readyState!=="complete"?addEventListener("load",()=>D(r),!0):setTimeout(r)},rt=(r,t={})=>{let e=u("TTFB"),i=d(r,e,j,t.reportAllChanges);D(()=>{let n=R();n&&(e.value=Math.max(n.responseStart-m(),0),e.entries=[n],i(!0),g(()=>{e=u("TTFB",0),i=d(r,e,j,t.reportAllChanges),i(!0)}))})};var k=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{et(this.collectMetric.bind(this)),Y(this.collectMetric.bind(this)),tt(this.collectMetric.bind(this)),U(this.collectMetric.bind(this)),rt(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(n=>n!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};(function(){let r=document.currentScript;if(!r){console.error("Could not find current script tag");return}if(window.__RYBBIT_OPTOUT__||localStorage.getItem("disable-rybbit")!==null){window.rybbit={pageview:()=>{},event:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null};return}let t=B(r);if(!t)return;let e=new b(t);t.enableWebVitals&&new k(a=>{e.trackWebVitals(a)}).initialize();let i=()=>e.trackPageview(),n=t.debounceDuration>0?N(i,t.debounceDuration):i;function c(){if(document.addEventListener("click",function(o){let a=o.target;for(;a&&a!==document.documentElement;){if(a.hasAttribute("data-rybbit-event")){let s=a.getAttribute("data-rybbit-event");if(s){let l={};for(let w of a.attributes)if(w.name.startsWith("data-rybbit-prop-")){let it=w.name.replace("data-rybbit-prop-","");l[it]=w.value}e.trackEvent(s,l)}break}a=a.parentElement}if(t.trackOutbound){let s=o.target.closest("a");s?.href&&W(s.href)&&e.trackOutbound(s.href,s.innerText||s.textContent||"",s.target||"_self")}}),t.autoTrackSpa){let o=history.pushState,a=history.replaceState;history.pushState=function(...s){o.apply(this,s),n()},history.replaceState=function(...s){a.apply(this,s),n()},window.addEventListener("popstate",n),window.addEventListener("hashchange",n)}}window.rybbit={pageview:()=>e.trackPageview(),event:(o,a={})=>e.trackEvent(o,a),trackOutbound:(o,a="",s="_self")=>e.trackOutbound(o,a,s),identify:o=>e.identify(o),clearUserId:()=>e.clearUserId(),getUserId:()=>e.getUserId()},c(),t.autoTrackPageview&&e.trackPageview()})();})();+"use strict";(()=>{var it=Object.defineProperty;var at=(r,t,e)=>t in r?it(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var h=(r,t,e)=>at(r,typeof t!="symbol"?t+"":t,e);function st(r){let t="__DOUBLE_ASTERISK_TOKEN__",e="__SINGLE_ASTERISK_TOKEN__",i=r.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 c=i.replace(new RegExp(e,"g"),"[^/]+");return new RegExp("^"+c+"$")}function E(r,t){for(let e of t)try{if(st(e).test(r))return e}catch(n){console.error(`Invalid pattern: ${e}`,n)}return null}function N(r,t){let e=null;return(...n)=>{e&&clearTimeout(e),e=setTimeout(()=>r(...n),t)}}function W(r){try{let t=window.location.hostname,e=new URL(r).hostname;return e!==t&&e!==""}catch{return!1}}function P(r,t){if(!r)return t;try{let e=JSON.parse(r);return Array.isArray(t)&&!Array.isArray(e)?t:e}catch(e){return console.error("Error parsing JSON:",e),t}}function B(r){let t=r.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 n=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!n||isNaN(Number(n)))return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,c=P(r.getAttribute("data-skip-patterns"),[]),s=P(r.getAttribute("data-mask-patterns"),[]),a=r.getAttribute("data-api-key")||void 0;return{analyticsHost:e,siteId:n,debounceDuration:i,autoTrackPageview:r.getAttribute("data-auto-track-pageview")!=="false",autoTrackSpa:r.getAttribute("data-track-spa")!=="false",trackQuerystring:r.getAttribute("data-track-query")!=="false",trackOutbound:r.getAttribute("data-track-outbound")!=="false",enableWebVitals:r.getAttribute("data-web-vitals")==="true",trackErrors:r.getAttribute("data-track-errors")==="true",skipPatterns:c,maskPatterns:s,apiKey:a}}var b=class{constructor(t){this.customUserId=null;this.config=t,this.loadUserId()}loadUserId(){try{let t=localStorage.getItem("rybbit-user-id");t&&(this.customUserId=t)}catch{}}createBasePayload(){let t=new URL(window.location.href),e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),E(e,this.config.skipPatterns))return null;let n=E(e,this.config.maskPatterns);n&&(e=n);let i={site_id:this.config.siteId,hostname:t.hostname,pathname:e,querystring:this.config.trackQuerystring?t.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(i.user_id=this.customUserId),this.config.apiKey&&(i.api_key=this.config.apiKey),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="",n={}){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 c={...i,type:t,event_name:e,properties:t==="custom_event"||t==="outbound"||t==="error"?JSON.stringify(n):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(t,e={}){this.track("custom_event",t,e)}trackOutbound(t,e="",n="_self"){this.track("outbound","",{url:t,text:e,target:n})}trackWebVitals(t){let e=this.createBasePayload();if(!e)return;let n={...e,type:"performance",event_name:"web-vitals",...t};this.sendTrackingData(n)}trackError(t,e={}){let n=window.location.origin,i=e.filename||"",c=t.stack||"";if(i)try{if(new URL(i).origin!==n)return}catch{}else if(c&&!c.includes(n))return;let s={message:t.message?.substring(0,500)||"Unknown error",stack:c.substring(0,2e3)||""};if(i&&(s.fileName=i),e.lineno){let a=typeof e.lineno=="string"?parseInt(e.lineno,10):e.lineno;a&&a!==0&&(s.lineNumber=a)}if(e.colno){let a=typeof e.colno=="string"?parseInt(e.colno,10):e.colno;a&&a!==0&&(s.columnNumber=a)}for(let a in e)!["lineno","colno"].includes(a)&&e[a]!==void 0&&(s[a]=e[a]);this.track("error",t.name||"Error",s)}identify(t){if(typeof t!="string"||t.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=t.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}};var G=-1,m=r=>{addEventListener("pageshow",t=>{t.persisted&&(G=t.timeStamp,r(t))},!0)},d=(r,t,e,n)=>{let i,c;return s=>{t.value>=0&&(s||n)&&(c=t.value-(i??0),(c||i===void 0)&&(i=t.value,t.delta=c,t.rating=((a,o)=>a>o[1]?"poor":a>o[0]?"needs-improvement":"good")(t.value,e),r(t)))}},R=r=>{requestAnimationFrame(()=>requestAnimationFrame(()=>r()))},M=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},p=()=>M()?.activationStart??0,u=(r,t=-1)=>{let e=M(),n="navigate";return G>=0?n="back-forward-cache":e&&(document.prerendering||p()>0?n="prerender":document.wasDiscarded?n="restore":e.type&&(n=e.type.replace(/_/g,"-"))),{name:r,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},S=new WeakMap;function U(r,t){return S.get(r)||S.set(r,new t),S.get(r)}var L=class{constructor(){h(this,"t");h(this,"i",0);h(this,"o",[])}h(t){if(t.hadRecentInput)return;let e=this.o[0],n=this.o.at(-1);this.i&&e&&n&&t.startTime-n.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)}},f=(r,t,e={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let n=new PerformanceObserver(i=>{Promise.resolve().then(()=>{t(i.getEntries())})});return n.observe({type:r,buffered:!0,...e}),n}}catch{}},O=r=>{let t=!1;return()=>{t||(r(),t=!0)}},g=-1,H=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,y=r=>{document.visibilityState==="hidden"&&g>-1&&(g=r.type==="visibilitychange"?r.timeStamp:0,ot())},V=()=>{addEventListener("visibilitychange",y,!0),addEventListener("prerenderingchange",y,!0)},ot=()=>{removeEventListener("visibilitychange",y,!0),removeEventListener("prerenderingchange",y,!0)},Q=()=>{if(g<0){let r=p();g=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(e=>e.name==="hidden"&&e.startTime>r)[0]?.startTime)??H(),V(),m(()=>{setTimeout(()=>{g=H(),V()})})}return{get firstHiddenTime(){return g}}},T=r=>{document.prerendering?addEventListener("prerenderingchange",()=>r(),!0):r()},F=[1800,3e3],x=(r,t={})=>{T(()=>{let e=Q(),n,i=u("FCP"),c=f("paint",s=>{for(let a of s)a.name==="first-contentful-paint"&&(c.disconnect(),a.startTime<e.firstHiddenTime&&(i.value=Math.max(a.startTime-p(),0),i.entries.push(a),n(!0)))});c&&(n=d(r,i,F,t.reportAllChanges),m(s=>{i=u("FCP"),n=d(r,i,F,t.reportAllChanges),R(()=>{i.value=performance.now()-s.timeStamp,n(!0)})}))})},K=[.1,.25],Y=(r,t={})=>{x(O(()=>{let e,n=u("CLS",0),i=U(t,L),c=a=>{for(let o of a)i.h(o);i.i>n.value&&(n.value=i.i,n.entries=i.o,e())},s=f("layout-shift",c);s&&(e=d(r,n,K,t.reportAllChanges),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(s.takeRecords()),e(!0))}),m(()=>{i.i=0,n=u("CLS",0),e=d(r,n,K,t.reportAllChanges),R(()=>e())}),setTimeout(e))}))},X=0,C=1/0,v=0,ct=r=>{for(let t of r)t.interactionId&&(C=Math.min(C,t.interactionId),v=Math.max(v,t.interactionId),X=v?(v-C)/7+1:0)},I,$=()=>I?X:performance.interactionCount??0,lt=()=>{"interactionCount"in performance||I||(I=f("event",ct,{type:"event",buffered:!0,durationThreshold:0}))},J=0,_=class{constructor(){h(this,"u",[]);h(this,"l",new Map);h(this,"m");h(this,"v")}p(){J=$(),this.u.length=0,this.l.clear()}P(){let t=Math.min(this.u.length-1,Math.floor(($()-J)/50));return this.u[t]}h(t){if(this.m?.(t),!t.interactionId&&t.entryType!=="first-input")return;let e=this.u.at(-1),n=this.l.get(t.interactionId);if(n||this.u.length<10||t.duration>e.T){if(n?t.duration>n.T?(n.entries=[t],n.T=t.duration):t.duration===n.T&&t.startTime===n.entries[0].startTime&&n.entries.push(t):(n={id:t.interactionId,entries:[t],T:t.duration},this.l.set(n.id,n),this.u.push(n)),this.u.sort((i,c)=>c.T-i.T),this.u.length>10){let i=this.u.splice(10);for(let c of i)this.l.delete(c.id)}this.v?.(n)}}},Z=r=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=O(r),document.addEventListener("visibilitychange",r,{once:!0}),t(()=>{r(),document.removeEventListener("visibilitychange",r)}))},j=[200,500],tt=(r,t={})=>{globalThis.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype&&T(()=>{lt();let e,n=u("INP"),i=U(t,_),c=a=>{Z(()=>{for(let l of a)i.h(l);let o=i.P();o&&o.T!==n.value&&(n.value=o.T,n.entries=o.entries,e())})},s=f("event",c,{durationThreshold:t.durationThreshold??40});e=d(r,n,j,t.reportAllChanges),s&&(s.observe({type:"first-input",buffered:!0}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(s.takeRecords()),e(!0))}),m(()=>{i.p(),n=u("INP"),e=d(r,n,j,t.reportAllChanges)}))})},A=class{constructor(){h(this,"m")}h(t){this.m?.(t)}},q=[2500,4e3],et=(r,t={})=>{T(()=>{let e=Q(),n,i=u("LCP"),c=U(t,A),s=o=>{t.reportAllChanges||(o=o.slice(-1));for(let l of o)c.h(l),l.startTime<e.firstHiddenTime&&(i.value=Math.max(l.startTime-p(),0),i.entries=[l],n())},a=f("largest-contentful-paint",s);if(a){n=d(r,i,q,t.reportAllChanges);let o=O(()=>{s(a.takeRecords()),a.disconnect(),n(!0)});for(let l of["keydown","click","visibilitychange"])addEventListener(l,()=>Z(o),{capture:!0,once:!0});m(l=>{i=u("LCP"),n=d(r,i,q,t.reportAllChanges),R(()=>{i.value=performance.now()-l.timeStamp,n(!0)})})}})},z=[800,1800],D=r=>{document.prerendering?T(()=>D(r)):document.readyState!=="complete"?addEventListener("load",()=>D(r),!0):setTimeout(r)},rt=(r,t={})=>{let e=u("TTFB"),n=d(r,e,z,t.reportAllChanges);D(()=>{let i=M();i&&(e.value=Math.max(i.responseStart-p(),0),e.entries=[i],n(!0),m(()=>{e=u("TTFB",0),n=d(r,e,z,t.reportAllChanges),n(!0)}))})};var k=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{et(this.collectMetric.bind(this)),Y(this.collectMetric.bind(this)),tt(this.collectMetric.bind(this)),x(this.collectMetric.bind(this)),rt(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}}};(function(){let r=document.currentScript;if(!r){console.error("Could not find current script tag");return}if(window.__RYBBIT_OPTOUT__||localStorage.getItem("disable-rybbit")!==null){window.rybbit={pageview:()=>{},event:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null};return}let t=B(r);if(!t)return;let e=new b(t);t.enableWebVitals&&new k(a=>{e.trackWebVitals(a)}).initialize(),t.trackErrors&&(window.addEventListener("error",s=>{e.trackError(s.error||new Error(s.message),{filename:s.filename,lineno:s.lineno,colno:s.colno})}),window.addEventListener("unhandledrejection",s=>{let a=s.reason instanceof Error?s.reason:new Error(String(s.reason));e.trackError(a,{type:"unhandledrejection"})}));let n=()=>e.trackPageview(),i=t.debounceDuration>0?N(n,t.debounceDuration):n;function c(){if(document.addEventListener("click",function(s){let a=s.target;for(;a&&a!==document.documentElement;){if(a.hasAttribute("data-rybbit-event")){let o=a.getAttribute("data-rybbit-event");if(o){let l={};for(let w of a.attributes)if(w.name.startsWith("data-rybbit-prop-")){let nt=w.name.replace("data-rybbit-prop-","");l[nt]=w.value}e.trackEvent(o,l)}break}a=a.parentElement}if(t.trackOutbound){let o=s.target.closest("a");o?.href&&W(o.href)&&e.trackOutbound(o.href,o.innerText||o.textContent||"",o.target||"_self")}}),t.autoTrackSpa){let s=history.pushState,a=history.replaceState;history.pushState=function(...o){s.apply(this,o),i()},history.replaceState=function(...o){a.apply(this,o),i()},window.addEventListener("popstate",i),window.addEventListener("hashchange",i)}}window.rybbit={pageview:()=>e.trackPageview(),event:(s,a={})=>e.trackEvent(s,a),trackOutbound:(s,a="",o="_self")=>e.trackOutbound(s,a,o),identify:s=>e.identify(s),clearUserId:()=>e.clearUserId(),getUserId:()=>e.getUserId()},c(),t.autoTrackPageview&&e.trackPageview()})();})();diff --git a/server/src/analytics-script/config.test.ts b/server/src/analytics-script/config.test.tsindex 2df3204a7..09673c51f 100644--- a/server/src/analytics-script/config.test.ts+++ b/server/src/analytics-script/config.test.ts@@ -32,8 +32,10 @@ describe("parseScriptConfig", () => {trackQuerystring: true,trackOutbound: true,enableWebVitals: false, // Default is false, only true when data-web-vitals="true"+ trackErrors: false, // Default is false, only true when data-track-errors="true"skipPatterns: [],maskPatterns: [],+ apiKey: undefined, // Default is undefined when no data-api-key attribute});});diff --git a/server/src/analytics-script/config.ts b/server/src/analytics-script/config.tsindex b90c75df5..9a660ceee 100644--- a/server/src/analytics-script/config.ts+++ b/server/src/analytics-script/config.ts@@ -1,55 +1,62 @@-import { ScriptConfig } from './types.js';-import { parseJsonSafely } from './utils.js';+import { ScriptConfig } from "./types.js";+import { parseJsonSafely } from "./utils.js";/*** Parse script configuration from the script tag attributes*/-export function parseScriptConfig(scriptTag: HTMLScriptElement): ScriptConfig | null {- const src = scriptTag.getAttribute('src');+export function parseScriptConfig(+ scriptTag: HTMLScriptElement+): ScriptConfig | null {+ const src = scriptTag.getAttribute("src");if (!src) {- console.error('Script src attribute is missing');+ console.error("Script src attribute is missing");return null;}- const analyticsHost = src.split('/script.js')[0];+ const analyticsHost = src.split("/script.js")[0];if (!analyticsHost) {- console.error('Please provide a valid analytics host');+ console.error("Please provide a valid analytics host");return null;}- const siteId = scriptTag.getAttribute('data-site-id') || scriptTag.getAttribute('site-id');+ const siteId =+ scriptTag.getAttribute("data-site-id") || scriptTag.getAttribute("site-id");if (!siteId || isNaN(Number(siteId))) {- console.error('Please provide a valid site ID using the data-site-id attribute');+ console.error(+ "Please provide a valid site ID using the data-site-id attribute"+ );return null;}- const debounceDuration = scriptTag.getAttribute('data-debounce')- ? Math.max(0, parseInt(scriptTag.getAttribute('data-debounce')!))+ const debounceDuration = scriptTag.getAttribute("data-debounce")+ ? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce")!)): 500;const skipPatterns = parseJsonSafely<string[]>(- scriptTag.getAttribute('data-skip-patterns'),+ scriptTag.getAttribute("data-skip-patterns"),[]);const maskPatterns = parseJsonSafely<string[]>(- scriptTag.getAttribute('data-mask-patterns'),+ scriptTag.getAttribute("data-mask-patterns"),[]);- const apiKey = scriptTag.getAttribute('data-api-key') || undefined;+ const apiKey = scriptTag.getAttribute("data-api-key") || undefined;return {analyticsHost,siteId,debounceDuration,- autoTrackPageview: scriptTag.getAttribute('data-auto-track-pageview') !== 'false',- autoTrackSpa: scriptTag.getAttribute('data-track-spa') !== 'false',- trackQuerystring: scriptTag.getAttribute('data-track-query') !== 'false',- trackOutbound: scriptTag.getAttribute('data-track-outbound') !== 'false',- enableWebVitals: scriptTag.getAttribute('data-web-vitals') === 'true',+ autoTrackPageview:+ scriptTag.getAttribute("data-auto-track-pageview") !== "false",+ autoTrackSpa: scriptTag.getAttribute("data-track-spa") !== "false",+ trackQuerystring: scriptTag.getAttribute("data-track-query") !== "false",+ trackOutbound: scriptTag.getAttribute("data-track-outbound") !== "false",+ enableWebVitals: scriptTag.getAttribute("data-web-vitals") === "true",+ trackErrors: scriptTag.getAttribute("data-track-errors") === "true",skipPatterns,maskPatterns,apiKey,};-}\ No newline at end of file+}diff --git a/server/src/analytics-script/index.ts b/server/src/analytics-script/index.tsindex dda9cb2ec..a90519297 100644--- a/server/src/analytics-script/index.ts+++ b/server/src/analytics-script/index.ts@@ -1,8 +1,8 @@-import { parseScriptConfig } from './config.js';-import { Tracker } from './tracking.js';-import { WebVitalsCollector } from './webVitals.js';-import { debounce, isOutboundLink } from './utils.js';-import { RybbitAPI, WebVitalsData } from './types.js';+import { parseScriptConfig } from "./config.js";+import { Tracker } from "./tracking.js";+import { WebVitalsCollector } from "./webVitals.js";+import { debounce, isOutboundLink } from "./utils.js";+import { RybbitAPI, WebVitalsData } from "./types.js";declare global {interface Window {@@ -14,12 +14,15 @@ declare global {(function () {const scriptTag = document.currentScript as HTMLScriptElement;if (!scriptTag) {- console.error('Could not find current script tag');+ console.error("Could not find current script tag");return;}// Check if user has opted out- if (window.__RYBBIT_OPTOUT__ || localStorage.getItem('disable-rybbit') !== null) {+ if (+ window.__RYBBIT_OPTOUT__ ||+ localStorage.getItem("disable-rybbit") !== null+ ) {// Create no-op implementationwindow.rybbit = {pageview: () => {},@@ -43,33 +46,59 @@ declare global {// Initialize web vitals if enabledif (config.enableWebVitals) {- const webVitalsCollector = new WebVitalsCollector((vitals: WebVitalsData) => {- tracker.trackWebVitals(vitals);- });+ const webVitalsCollector = new WebVitalsCollector(+ (vitals: WebVitalsData) => {+ tracker.trackWebVitals(vitals);+ }+ );webVitalsCollector.initialize();}+ // Initialize error tracking if enabled+ if (config.trackErrors) {+ // Global error handler for uncaught errors+ window.addEventListener("error", (event) => {+ tracker.trackError(event.error || new Error(event.message), {+ filename: event.filename,+ lineno: event.lineno,+ colno: event.colno,+ });+ });++ // Global handler for unhandled promise rejections+ window.addEventListener("unhandledrejection", (event) => {+ const error =+ event.reason instanceof Error+ ? event.reason+ : new Error(String(event.reason));+ tracker.trackError(error, {+ type: "unhandledrejection",+ });+ });+ }+// Create debounced pageview trackerconst trackPageview = () => tracker.trackPageview();- const debouncedTrackPageview = config!.debounceDuration > 0- ? debounce(trackPageview, config!.debounceDuration)- : trackPageview;+ const debouncedTrackPageview =+ config!.debounceDuration > 0+ ? debounce(trackPageview, config!.debounceDuration)+ : trackPageview;// Setup event listenersfunction setupEventListeners() {// Track custom events and outbound links- document.addEventListener('click', function (e) {+ document.addEventListener("click", function (e) {let target = e.target as HTMLElement;-+// Check for custom events via data attributeswhile (target && target !== document.documentElement) {- if (target.hasAttribute('data-rybbit-event')) {- const eventName = target.getAttribute('data-rybbit-event');+ if (target.hasAttribute("data-rybbit-event")) {+ const eventName = target.getAttribute("data-rybbit-event");if (eventName) {const properties: Record<string, string> = {};for (const attr of target.attributes) {- if (attr.name.startsWith('data-rybbit-prop-')) {- const propName = attr.name.replace('data-rybbit-prop-', '');+ if (attr.name.startsWith("data-rybbit-prop-")) {+ const propName = attr.name.replace("data-rybbit-prop-", "");properties[propName] = attr.value;}}@@ -82,12 +111,14 @@ declare global {// Check for outbound linksif (config!.trackOutbound) {- const link = (e.target as HTMLElement).closest('a') as HTMLAnchorElement;+ const link = (e.target as HTMLElement).closest(+ "a"+ ) as HTMLAnchorElement;if (link?.href && isOutboundLink(link.href)) {tracker.trackOutbound(link.href,- link.innerText || link.textContent || '',- link.target || '_self'+ link.innerText || link.textContent || "",+ link.target || "_self");}}@@ -108,17 +139,17 @@ declare global {debouncedTrackPageview();};- window.addEventListener('popstate', debouncedTrackPageview);- window.addEventListener('hashchange', debouncedTrackPageview);+ window.addEventListener("popstate", debouncedTrackPageview);+ window.addEventListener("hashchange", debouncedTrackPageview);}}// Setup public APIwindow.rybbit = {pageview: () => tracker.trackPageview(),- event: (name: string, properties: Record<string, any> = {}) =>+ event: (name: string, properties: Record<string, any> = {}) =>tracker.trackEvent(name, properties),- trackOutbound: (url: string, text: string = '', target: string = '_self') =>+ trackOutbound: (url: string, text: string = "", target: string = "_self") =>tracker.trackOutbound(url, text, target),identify: (userId: string) => tracker.identify(userId),clearUserId: () => tracker.clearUserId(),@@ -132,4 +163,4 @@ declare global {if (config!.autoTrackPageview) {tracker.trackPageview();}-})();\ No newline at end of file+})();diff --git a/server/src/analytics-script/tracking.test.ts b/server/src/analytics-script/tracking.test.tsindex 0d9bd8367..6f4bbe85f 100644--- a/server/src/analytics-script/tracking.test.ts+++ b/server/src/analytics-script/tracking.test.ts@@ -1,11 +1,11 @@-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { Tracker } from './tracking.js';-import { ScriptConfig } from './types.js';+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { Tracker } from "./tracking.js";+import { ScriptConfig } from "./types.js";// Mock fetch globallyglobal.fetch = vi.fn();-describe('Tracker', () => {+describe("Tracker", () => {let tracker: Tracker;let config: ScriptConfig;let mockLocation: any;@@ -21,26 +21,26 @@ describe('Tracker', () => {setItem: vi.fn(),removeItem: vi.fn(),};- Object.defineProperty(window, 'localStorage', {+ Object.defineProperty(window, "localStorage", {value: localStorageMock,writable: true,});// Mock window propertiesmockLocation = {- href: 'https://example.com/page?query=test',- hostname: 'example.com',- pathname: '/page',- search: '?query=test',- hash: '',+ href: "https://example.com/page?query=test",+ hostname: "example.com",+ pathname: "/page",+ search: "?query=test",+ hash: "",};-- Object.defineProperty(window, 'location', {++ Object.defineProperty(window, "location", {value: mockLocation,configurable: true,writable: true,});-+// Mock URL constructor to use our mockLocationglobal.URL = vi.fn().mockImplementation(() => ({hostname: mockLocation.hostname,@@ -49,39 +49,40 @@ describe('Tracker', () => {hash: mockLocation.hash,})) as any;- Object.defineProperty(window, 'innerWidth', {+ Object.defineProperty(window, "innerWidth", {value: 1920,writable: true,});- Object.defineProperty(window, 'innerHeight', {+ Object.defineProperty(window, "innerHeight", {value: 1080,writable: true,});- Object.defineProperty(navigator, 'language', {- value: 'en-US',+ Object.defineProperty(navigator, "language", {+ value: "en-US",writable: true,});- Object.defineProperty(document, 'title', {- value: 'Test Page',+ Object.defineProperty(document, "title", {+ value: "Test Page",writable: true,});- Object.defineProperty(document, 'referrer', {- value: 'https://google.com',+ Object.defineProperty(document, "referrer", {+ value: "https://google.com",writable: true,});config = {- analyticsHost: 'https://analytics.example.com',- siteId: '123',+ analyticsHost: "https://analytics.example.com",+ siteId: "123",debounceDuration: 0,autoTrackPageview: true,autoTrackSpa: true,trackQuerystring: true,trackOutbound: true,+ trackErrors: false,enableWebVitals: false,skipPatterns: [],maskPatterns: [],@@ -94,120 +95,128 @@ describe('Tracker', () => {vi.clearAllMocks();});- describe('createBasePayload', () => {- it('should create base payload with all required fields', () => {+ describe("createBasePayload", () => {+ it("should create base payload with all required fields", () => {const payload = tracker.createBasePayload();expect(payload).toEqual({- site_id: '123',- hostname: 'example.com',- pathname: '/page',- querystring: '?query=test',+ site_id: "123",+ hostname: "example.com",+ pathname: "/page",+ querystring: "?query=test",screenWidth: 1920,screenHeight: 1080,- language: 'en-US',- page_title: 'Test Page',- referrer: 'https://google.com',+ language: "en-US",+ page_title: "Test Page",+ referrer: "https://google.com",});});- it('should handle hash-based routing', () => {- mockLocation.hash = '#/dashboard/users';+ it("should handle hash-based routing", () => {+ mockLocation.hash = "#/dashboard/users";const payload = tracker.createBasePayload();- expect(payload?.pathname).toBe('/dashboard/users');+ expect(payload?.pathname).toBe("/dashboard/users");});- it('should skip tracking for matching skip patterns', () => {- config.skipPatterns = ['/admin/**', '/api/**'];+ it("should skip tracking for matching skip patterns", () => {+ config.skipPatterns = ["/admin/**", "/api/**"];tracker = new Tracker(config);-- mockLocation.pathname = '/admin/settings';++ mockLocation.pathname = "/admin/settings";const payload = tracker.createBasePayload();expect(payload).toBeNull();});- it('should apply mask patterns', () => {- config.maskPatterns = ['/user/*/profile'];+ it("should apply mask patterns", () => {+ config.maskPatterns = ["/user/*/profile"];tracker = new Tracker(config);-- mockLocation.pathname = '/user/123/profile';++ mockLocation.pathname = "/user/123/profile";const payload = tracker.createBasePayload();- expect(payload?.pathname).toBe('/user/*/profile');+ expect(payload?.pathname).toBe("/user/*/profile");});- it('should exclude querystring when disabled', () => {+ it("should exclude querystring when disabled", () => {config.trackQuerystring = false;tracker = new Tracker(config);-+const payload = tracker.createBasePayload();- expect(payload?.querystring).toBe('');+ expect(payload?.querystring).toBe("");});- it('should include user ID when set', () => {- vi.mocked(window.localStorage.getItem).mockReturnValue('user-123');+ it("should include user ID when set", () => {+ vi.mocked(window.localStorage.getItem).mockReturnValue("user-123");tracker = new Tracker(config);-+const payload = tracker.createBasePayload();- expect(payload?.user_id).toBe('user-123');+ expect(payload?.user_id).toBe("user-123");});});- describe('tracking methods', () => {- it('should track pageview', async () => {+ describe("tracking methods", () => {+ it("should track pageview", async () => {tracker.trackPageview();expect(global.fetch).toHaveBeenCalledWith(- 'https://analytics.example.com/track',+ "https://analytics.example.com/track",expect.objectContaining({- method: 'POST',- headers: { 'Content-Type': 'application/json' },+ method: "POST",+ headers: { "Content-Type": "application/json" },body: expect.stringContaining('"type":"pageview"'),- mode: 'cors',+ mode: "cors",keepalive: true,}));});- it('should track custom event', async () => {- tracker.trackEvent('button_click', { button: 'submit' });+ it("should track custom event", async () => {+ tracker.trackEvent("button_click", { button: "submit" });expect(global.fetch).toHaveBeenCalledWith(- 'https://analytics.example.com/track',+ "https://analytics.example.com/track",expect.objectContaining({body: expect.stringContaining('"type":"custom_event"'),}));- const body = JSON.parse(vi.mocked(global.fetch).mock.calls[0][1]!.body as string);- expect(body.event_name).toBe('button_click');- expect(body.properties).toBe(JSON.stringify({ button: 'submit' }));+ const body = JSON.parse(+ vi.mocked(global.fetch).mock.calls[0][1]!.body as string+ );+ expect(body.event_name).toBe("button_click");+ expect(body.properties).toBe(JSON.stringify({ button: "submit" }));});- it('should validate custom event name', () => {- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});-- tracker.trackEvent('', {});+ it("should validate custom event name", () => {+ const consoleSpy = vi+ .spyOn(console, "error")+ .mockImplementation(() => {});++ tracker.trackEvent("", {});expect(global.fetch).not.toHaveBeenCalled();expect(consoleSpy).toHaveBeenCalledWith(- 'Event name is required and must be a string for custom events'+ "Event name is required and must be a string for custom events");consoleSpy.mockRestore();});- it('should track outbound link', async () => {- tracker.trackOutbound('https://external.com', 'External Link', '_blank');+ it("should track outbound link", async () => {+ tracker.trackOutbound("https://external.com", "External Link", "_blank");- const body = JSON.parse(vi.mocked(global.fetch).mock.calls[0][1]!.body as string);- expect(body.type).toBe('outbound');- expect(body.properties).toBe(JSON.stringify({- url: 'https://external.com',- text: 'External Link',- target: '_blank',- }));+ const body = JSON.parse(+ vi.mocked(global.fetch).mock.calls[0][1]!.body as string+ );+ expect(body.type).toBe("outbound");+ expect(body.properties).toBe(+ JSON.stringify({+ url: "https://external.com",+ text: "External Link",+ target: "_blank",+ })+ );});- it('should track web vitals', async () => {+ it("should track web vitals", async () => {const vitals = {lcp: 2500,cls: 0.1,@@ -218,67 +227,214 @@ describe('Tracker', () => {tracker.trackWebVitals(vitals);- const body = JSON.parse(vi.mocked(global.fetch).mock.calls[0][1]!.body as string);- expect(body.type).toBe('performance');- expect(body.event_name).toBe('web-vitals');+ const body = JSON.parse(+ vi.mocked(global.fetch).mock.calls[0][1]!.body as string+ );+ expect(body.type).toBe("performance");+ expect(body.event_name).toBe("web-vitals");expect(body.lcp).toBe(2500);expect(body.cls).toBe(0.1);});- it('should handle fetch errors gracefully', async () => {- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});- vi.mocked(global.fetch).mockRejectedValue(new Error('Network error'));+ it("should handle fetch errors gracefully", async () => {+ const consoleSpy = vi+ .spyOn(console, "error")+ .mockImplementation(() => {});+ vi.mocked(global.fetch).mockRejectedValue(new Error("Network error"));tracker.trackPageview();-+// Wait for async operation- await new Promise(resolve => setTimeout(resolve, 0));-+ await new Promise((resolve) => setTimeout(resolve, 0));+expect(consoleSpy).toHaveBeenCalledWith(- 'Failed to send tracking data:',+ "Failed to send tracking data:",expect.any(Error));consoleSpy.mockRestore();});++ describe("error tracking", () => {+ it("should track first-party errors", () => {+ // Enable error tracking for this test+ const errorConfig = { ...config, trackErrors: true };+ const tracker = new Tracker(errorConfig);+ const sendSpy = vi+ .spyOn(tracker, "sendTrackingData")+ .mockResolvedValue();++ const error = new Error("Test error");+ error.stack =+ "Error: Test error\n at https://example.com/app.js:10:5";++ tracker.trackError(error, {+ filename: "https://example.com/app.js",+ lineno: 10,+ colno: 5,+ });++ expect(sendSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "error",+ event_name: "Error",+ properties: expect.stringContaining("Test error"),+ })+ );+ });++ it("should filter out third-party errors by filename", () => {+ const errorConfig = { ...config, trackErrors: true };+ const tracker = new Tracker(errorConfig);+ const sendSpy = vi+ .spyOn(tracker, "sendTrackingData")+ .mockResolvedValue();++ // Mock window.location.origin to ensure we have a proper origin for comparison+ Object.defineProperty(window, "location", {+ value: {+ ...mockLocation,+ origin: "https://example.com",+ },+ configurable: true,+ writable: true,+ });++ const error = new Error("Third party error");+ // Clear the stack to avoid test environment paths interfering+ error.stack = undefined;++ tracker.trackError(error, {+ filename: "https://ads.google.com/script.js",+ lineno: 1,+ colno: 1,+ });++ expect(sendSpy).not.toHaveBeenCalled();+ });++ it("should filter out third-party errors by stack trace", () => {+ const errorConfig = { ...config, trackErrors: true };+ const tracker = new Tracker(errorConfig);+ const sendSpy = vi+ .spyOn(tracker, "sendTrackingData")+ .mockResolvedValue();++ const error = new Error("Third party error");+ error.stack =+ "Error: Third party error\n at https://ads.google.com/script.js:1:1";++ tracker.trackError(error, {+ lineno: 1,+ colno: 1,+ });++ expect(sendSpy).not.toHaveBeenCalled();+ });++ it("should track errors with unknown origin (e.g., NetworkError)", () => {+ const errorConfig = { ...config, trackErrors: true };+ const tracker = new Tracker(errorConfig);+ const sendSpy = vi+ .spyOn(tracker, "sendTrackingData")+ .mockResolvedValue();++ const error = new Error(+ "NetworkError when attempting to fetch resource"+ );+ error.name = "TypeError";+ // Clear stack to avoid test environment paths+ error.stack = undefined;++ tracker.trackError(error, {+ type: "unhandledrejection",+ });++ expect(sendSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "error",+ event_name: "TypeError",+ properties: expect.stringContaining("NetworkError"),+ })+ );+ });++ it("should handle invalid filename URLs gracefully", () => {+ const errorConfig = { ...config, trackErrors: true };+ const tracker = new Tracker(errorConfig);+ const sendSpy = vi+ .spyOn(tracker, "sendTrackingData")+ .mockResolvedValue();++ const error = new Error("Test error");+ error.stack =+ "Error: Test error\n at https://example.com/app.js:10:5";++ tracker.trackError(error, {+ filename: "invalid-url",+ lineno: 10,+ colno: 5,+ });++ // Should fall back to stack trace check and track the error+ expect(sendSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "error",+ event_name: "Error",+ properties: expect.stringContaining("Test error"),+ })+ );+ });+ });});- describe('user identification', () => {- it('should identify user', () => {- tracker.identify('user-456');-- expect(window.localStorage.setItem).toHaveBeenCalledWith('rybbit-user-id', 'user-456');- expect(tracker.getUserId()).toBe('user-456');+ describe("user identification", () => {+ it("should identify user", () => {+ tracker.identify("user-456");++ expect(window.localStorage.setItem).toHaveBeenCalledWith(+ "rybbit-user-id",+ "user-456"+ );+ expect(tracker.getUserId()).toBe("user-456");});- it('should validate user ID', () => {- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});-- tracker.identify('');+ it("should validate user ID", () => {+ const consoleSpy = vi+ .spyOn(console, "error")+ .mockImplementation(() => {});++ tracker.identify("");expect(window.localStorage.setItem).not.toHaveBeenCalled();- expect(consoleSpy).toHaveBeenCalledWith('User ID must be a non-empty string');+ expect(consoleSpy).toHaveBeenCalledWith(+ "User ID must be a non-empty string"+ );consoleSpy.mockRestore();});- it('should clear user ID', () => {- tracker.identify('user-789');+ it("should clear user ID", () => {+ tracker.identify("user-789");tracker.clearUserId();-- expect(window.localStorage.removeItem).toHaveBeenCalledWith('rybbit-user-id');++ expect(window.localStorage.removeItem).toHaveBeenCalledWith(+ "rybbit-user-id"+ );expect(tracker.getUserId()).toBeNull();});- it('should handle localStorage errors', () => {- const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ it("should handle localStorage errors", () => {+ const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});vi.mocked(window.localStorage.setItem).mockImplementation(() => {- throw new Error('Storage full');+ throw new Error("Storage full");});- tracker.identify('user-123');- expect(consoleSpy).toHaveBeenCalledWith('Could not persist user ID to localStorage');+ tracker.identify("user-123");+ expect(consoleSpy).toHaveBeenCalledWith(+ "Could not persist user ID to localStorage"+ );consoleSpy.mockRestore();});});-});\ No newline at end of file+});diff --git a/server/src/analytics-script/tracking.ts b/server/src/analytics-script/tracking.tsindex f41837d6d..1c8463ac7 100644--- a/server/src/analytics-script/tracking.ts+++ b/server/src/analytics-script/tracking.ts@@ -1,5 +1,10 @@-import { BasePayload, ScriptConfig, TrackingPayload, WebVitalsData } from './types.js';-import { findMatchingPattern } from './utils.js';+import {+ BasePayload,+ ScriptConfig,+ TrackingPayload,+ WebVitalsData,+} from "./types.js";+import { findMatchingPattern } from "./utils.js";export class Tracker {private config: ScriptConfig;@@ -12,7 +17,7 @@ export class Tracker {private loadUserId(): void {try {- const storedUserId = localStorage.getItem('rybbit-user-id');+ const storedUserId = localStorage.getItem("rybbit-user-id");if (storedUserId) {this.customUserId = storedUserId;}@@ -26,7 +31,7 @@ export class Tracker {let pathname = url.pathname;// Handle hash-based SPA routing- if (url.hash && url.hash.startsWith('#/')) {+ if (url.hash && url.hash.startsWith("#/")) {pathname = url.hash.substring(1);}@@ -45,7 +50,7 @@ export class Tracker {site_id: this.config.siteId,hostname: url.hostname,pathname: pathname,- querystring: this.config.trackQuerystring ? url.search : '',+ querystring: this.config.trackQuerystring ? url.search : "",screenWidth: window.innerWidth,screenHeight: window.innerHeight,language: navigator.language,@@ -68,26 +73,31 @@ export class Tracker {async sendTrackingData(payload: TrackingPayload): Promise<void> {try {await fetch(`${this.config.analyticsHost}/track`, {- method: 'POST',+ method: "POST",headers: {- 'Content-Type': 'application/json',+ "Content-Type": "application/json",},body: JSON.stringify(payload),- mode: 'cors',+ mode: "cors",keepalive: true,});} catch (error) {- console.error('Failed to send tracking data:', error);+ console.error("Failed to send tracking data:", error);}}track(- eventType: TrackingPayload['type'],- eventName: string = '',+ eventType: TrackingPayload["type"],+ eventName: string = "",properties: Record<string, any> = {}): void {- if (eventType === 'custom_event' && (!eventName || typeof eventName !== 'string')) {- console.error('Event name is required and must be a string for custom events');+ if (+ eventType === "custom_event" &&+ (!eventName || typeof eventName !== "string")+ ) {+ console.error(+ "Event name is required and must be a string for custom events"+ );return;}@@ -100,24 +110,31 @@ export class Tracker {...basePayload,type: eventType,event_name: eventName,- properties: eventType === 'custom_event' || eventType === 'outbound'- ? JSON.stringify(properties)- : undefined,+ properties:+ eventType === "custom_event" ||+ eventType === "outbound" ||+ eventType === "error"+ ? JSON.stringify(properties)+ : undefined,};this.sendTrackingData(payload);}trackPageview(): void {- this.track('pageview');+ this.track("pageview");}trackEvent(name: string, properties: Record<string, any> = {}): void {- this.track('custom_event', name, properties);+ this.track("custom_event", name, properties);}- trackOutbound(url: string, text: string = '', target: string = '_self'): void {- this.track('outbound', '', { url, text, target });+ trackOutbound(+ url: string,+ text: string = "",+ target: string = "_self"+ ): void {+ this.track("outbound", "", { url, text, target });}trackWebVitals(vitals: WebVitalsData): void {@@ -128,32 +145,100 @@ export class Tracker {const payload: TrackingPayload = {...basePayload,- type: 'performance',- event_name: 'web-vitals',+ type: "performance",+ event_name: "web-vitals",...vitals,};this.sendTrackingData(payload);}+ trackError(error: Error, additionalInfo: Record<string, any> = {}): void {+ // Industry-standard filtering: Only track errors from the same origin to avoid noise from third-party scripts+ const currentOrigin = window.location.origin;+ const filename = additionalInfo.filename || "";+ const errorStack = error.stack || "";++ // Primary check: Use filename if available (most reliable)+ if (filename) {+ try {+ const fileUrl = new URL(filename);+ if (fileUrl.origin !== currentOrigin) {+ return; // Skip third-party script errors+ }+ } catch (e) {+ // If filename is not a valid URL, it might be a relative path or browser-generated+ // In this case, we'll continue to the stack check+ }+ }++ // Fallback check: Use stack trace if filename check was inconclusive+ else if (errorStack) {+ // Check if stack contains any reference to the current origin+ if (!errorStack.includes(currentOrigin)) {+ return; // Skip third-party script errors+ }+ }++ // If neither filename nor stack can determine origin, track the error+ // This covers cases like NetworkError where the source is unclear but could be first-party++ const errorProperties: Record<string, any> = {+ message: error.message?.substring(0, 500) || "Unknown error", // Truncate to 500 chars+ stack: errorStack.substring(0, 2000) || "", // Truncate to 2000 chars+ };++ // Only include properties if they have meaningful values+ if (filename) {+ errorProperties.fileName = filename;+ }++ if (additionalInfo.lineno) {+ const lineNum = typeof additionalInfo.lineno === 'string'+ ? parseInt(additionalInfo.lineno, 10)+ : additionalInfo.lineno;+ if (lineNum && lineNum !== 0) {+ errorProperties.lineNumber = lineNum;+ }+ }++ if (additionalInfo.colno) {+ const colNum = typeof additionalInfo.colno === 'string'+ ? parseInt(additionalInfo.colno, 10)+ : additionalInfo.colno;+ if (colNum && colNum !== 0) {+ errorProperties.columnNumber = colNum;+ }+ }++ // Add any other additional info+ for (const key in additionalInfo) {+ if (!['lineno', 'colno'].includes(key) && additionalInfo[key] !== undefined) {+ errorProperties[key] = additionalInfo[key];+ }+ }++ this.track("error", error.name || "Error", errorProperties);+ }+identify(userId: string): void {- if (typeof userId !== 'string' || userId.trim() === '') {- console.error('User ID must be a non-empty string');+ if (typeof userId !== "string" || userId.trim() === "") {+ console.error("User ID must be a non-empty string");return;}-+this.customUserId = userId.trim();try {- localStorage.setItem('rybbit-user-id', this.customUserId);+ localStorage.setItem("rybbit-user-id", this.customUserId);} catch (e) {- console.warn('Could not persist user ID to localStorage');+ console.warn("Could not persist user ID to localStorage");}}clearUserId(): void {this.customUserId = null;try {- localStorage.removeItem('rybbit-user-id');+ localStorage.removeItem("rybbit-user-id");} catch (e) {// localStorage not available}@@ -162,4 +247,4 @@ export class Tracker {getUserId(): string | null {return this.customUserId;}-}\ No newline at end of file+}diff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.tsindex 136d219ff..d577d8524 100644--- a/server/src/analytics-script/types.ts+++ b/server/src/analytics-script/types.ts@@ -7,6 +7,7 @@ export interface ScriptConfig {trackQuerystring: boolean;trackOutbound: boolean;enableWebVitals: boolean;+ trackErrors: boolean;skipPatterns: string[];maskPatterns: string[];apiKey?: string;@@ -27,7 +28,7 @@ export interface BasePayload {}export interface TrackingPayload extends BasePayload {- type: 'pageview' | 'custom_event' | 'outbound' | 'performance';+ type: "pageview" | "custom_event" | "outbound" | "performance" | "error";event_name?: string;properties?: string;// Web vitals metrics@@ -53,4 +54,4 @@ export interface RybbitAPI {identify: (userId: string) => void;clearUserId: () => void;getUserId: () => string | null;-}\ No newline at end of file+}diff --git a/server/src/api/analytics/getErrorBucketed.ts b/server/src/api/analytics/getErrorBucketed.tsnew file mode 100644index 000000000..1b3752cf0--- /dev/null+++ b/server/src/api/analytics/getErrorBucketed.ts@@ -0,0 +1,140 @@+import { FilterParams } from "@rybbit/shared";+import { FastifyReply, FastifyRequest } from "fastify";+import SqlString from "sqlstring";+import { clickhouse } from "../../db/clickhouse/clickhouse.js";+import { getUserHasAccessToSitePublic } from "../../lib/auth-utils.js";+import { validateTimeStatementFillParams } from "./query-validation.js";+import {+ getFilterStatement,+ getTimeStatement,+ TimeBucketToFn,+ bucketIntervalMap,+ processResults,+} from "./utils.js";+import { TimeBucket } from "./types.js";++function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {+ const { params: validatedParams, bucket: validatedBucket } =+ validateTimeStatementFillParams(params, bucket);++ if (+ validatedParams.startDate &&+ validatedParams.endDate &&+ validatedParams.timeZone+ ) {+ const { startDate, endDate, timeZone } = validatedParams;+ return `WITH FILL FROM toTimeZone(+ toDateTime(${+ TimeBucketToFn[validatedBucket]+ }(toDateTime(${SqlString.escape(startDate)}, ${SqlString.escape(+ timeZone+ )}))),+ 'UTC'+ )+ TO if(+ toDate(${SqlString.escape(endDate)}) = toDate(now(), ${SqlString.escape(+ timeZone+ )}),+ now(),+ toTimeZone(+ toDateTime(${+ TimeBucketToFn[validatedBucket]+ }(toDateTime(${SqlString.escape(endDate)}, ${SqlString.escape(+ timeZone+ )}))) + INTERVAL 1 DAY,+ 'UTC'+ )+ ) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;+ }+ // For specific past minutes range - convert to exact timestamps for better performance+ if (+ validatedParams.pastMinutesStart !== undefined &&+ validatedParams.pastMinutesEnd !== undefined+ ) {+ return `WITH FILL FROM now() - INTERVAL ${validatedParams.pastMinutesStart} MINUTE+ TO now() - INTERVAL ${validatedParams.pastMinutesEnd} MINUTE+ STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;+ }++ throw new Error("Invalid time parameters");+}++interface GetErrorBucketedRequest {+ Params: {+ site: string;+ };+ Querystring: FilterParams<{+ bucket: TimeBucket;+ errorMessage: string;+ }>;+}++export type GetErrorBucketedResponse = {+ time: string;+ error_count: number;+}[];++export async function getErrorBucketed(+ req: FastifyRequest<GetErrorBucketedRequest>,+ res: FastifyReply+) {+ const site = req.params.site;+ const { bucket, errorMessage } = req.query;++ if (!errorMessage) {+ return res+ .status(400)+ .send({ error: "errorMessage parameter is required" });+ }++ const numericSiteId = Number(site);+ const hasAccess = await getUserHasAccessToSitePublic(req, numericSiteId);++ if (!hasAccess) {+ return res.status(403).send({ error: "Access denied" });+ }++ const filterStatement = getFilterStatement(req.query.filters);+ const timeStatement = getTimeStatement(req.query);+ const timeStatementFill = getTimeStatementFill(req.query, bucket);++ try {+ const query = `+ SELECT+ ${TimeBucketToFn[bucket]}(timestamp) AS time,+ COUNT(*) AS error_count+ FROM events+ WHERE+ site_id = {siteId:Int32}+ AND type = 'error'+ AND JSONExtractString(toString(props), 'message') = {errorMessage:String}+ ${filterStatement}+ ${timeStatement}+ GROUP BY time+ ORDER BY time+ ${timeStatementFill}+ `;++ const result = await clickhouse.query({+ query,+ format: "JSONEachRow",+ query_params: {+ siteId: numericSiteId,+ errorMessage: errorMessage,+ },+ });++ const data = await processResults<GetErrorBucketedResponse>(result);++ return res.send({+ success: true,+ data: data,+ });+ } catch (error) {+ console.error("Error getting error bucketed data:", error);+ return res.status(500).send({+ success: false,+ error: "Failed to get error data",+ });+ }+}diff --git a/server/src/api/analytics/getErrorEvents.ts b/server/src/api/analytics/getErrorEvents.tsnew file mode 100644index 000000000..63383b95b--- /dev/null+++ b/server/src/api/analytics/getErrorEvents.ts@@ -0,0 +1,215 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { clickhouse } from "../../db/clickhouse/clickhouse.js";+import { getUserHasAccessToSitePublic } from "../../lib/auth-utils.js";+import {+ getFilterStatement,+ getTimeStatement,+ processResults,+} from "./utils.js";+import { FilterParams } from "@rybbit/shared";++interface GetErrorEventsRequest {+ Params: {+ site: string;+ };+ Querystring: FilterParams<{+ errorMessage: string;+ limit?: number;+ page?: number;+ }>;+}++// This type represents a single error event+export type ErrorEvent = {+ timestamp: string;+ session_id: string;+ user_id: string | null;+ pathname: string | null;+ hostname: string | null;+ page_title: string | null;+ referrer: string | null;+ browser: string | null;+ browser_version: string | null;+ operating_system: string | null;+ operating_system_version: string | null;+ device_type: string | null;+ country: string | null;+ city: string | null;+ region: string | null;+ // Parsed error properties+ message: string;+ stack: string | null;+ fileName: string | null;+ lineNumber: number | null;+ columnNumber: number | null;+};++// Structure for paginated response+type ErrorEventsPaginatedResponse = {+ data: ErrorEvent[];+ totalCount: number;+};++const getErrorEventsQuery = (+ request: FastifyRequest<GetErrorEventsRequest>,+ isCountQuery: boolean = false+) => {+ const {+ startDate,+ endDate,+ timeZone,+ filters,+ errorMessage,+ limit,+ page,+ pastMinutesStart,+ pastMinutesEnd,+ } = request.query;++ const filterStatement = getFilterStatement(filters);+ const timeStatement = getTimeStatement(request.query);++ let validatedLimit: number | null = null;+ if (!isCountQuery && limit !== undefined) {+ const parsedLimit = parseInt(String(limit), 10);+ if (!isNaN(parsedLimit) && parsedLimit > 0) {+ validatedLimit = parsedLimit;+ }+ }+ // Default to 20 for error events+ const limitStatement =+ !isCountQuery && validatedLimit+ ? `LIMIT ${validatedLimit}`+ : isCountQuery+ ? ""+ : "LIMIT 20";++ let validatedOffset: number | null = null;+ if (!isCountQuery && page !== undefined) {+ const parsedPage = parseInt(String(page), 10);+ if (!isNaN(parsedPage) && parsedPage >= 1) {+ const pageOffset = (parsedPage - 1) * (validatedLimit || 20);+ validatedOffset = pageOffset;+ }+ }+ const offsetStatement =+ !isCountQuery && validatedOffset ? `OFFSET ${validatedOffset}` : "";++ if (isCountQuery) {+ return `+ SELECT COUNT(*) as totalCount+ FROM events+ WHERE+ site_id = {siteId:Int32}+ AND type = 'error'+ AND JSONExtractString(toString(props), 'message') = {errorMessage:String}+ ${filterStatement}+ ${timeStatement}+ `;+ }++ return `+ SELECT+ timestamp,+ session_id,+ user_id,+ pathname,+ hostname,+ page_title,+ referrer,+ browser,+ browser_version,+ operating_system,+ operating_system_version,+ device_type,+ country,+ city,+ region,+ JSONExtractString(toString(props), 'message') as message,+ JSONExtractString(toString(props), 'stack') as stack,+ COALESCE(+ JSONExtractString(toString(props), 'fileName'),+ JSONExtractString(toString(props), 'filename')+ ) as fileName,+ CASE+ WHEN JSONHas(toString(props), 'lineNumber') THEN JSONExtractInt(toString(props), 'lineNumber')+ WHEN JSONHas(toString(props), 'lineno') THEN JSONExtractInt(toString(props), 'lineno')+ ELSE NULL+ END as lineNumber,+ CASE+ WHEN JSONHas(toString(props), 'columnNumber') THEN JSONExtractInt(toString(props), 'columnNumber')+ WHEN JSONHas(toString(props), 'colno') THEN JSONExtractInt(toString(props), 'colno')+ ELSE NULL+ END as columnNumber+ FROM events+ WHERE+ site_id = {siteId:Int32}+ AND type = 'error'+ AND JSONExtractString(toString(props), 'message') = {errorMessage:String}+ ${filterStatement}+ ${timeStatement}+ ORDER BY timestamp DESC+ ${limitStatement}+ ${offsetStatement}+ `;+};++export async function getErrorEvents(+ req: FastifyRequest<GetErrorEventsRequest>,+ res: FastifyReply+) {+ const site = req.params.site;+ const { errorMessage, page } = req.query;++ if (!errorMessage) {+ return res.status(400).send({ error: "errorMessage parameter is required" });+ }++ const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);+ if (!userHasAccessToSite) {+ return res.status(403).send({ error: "Forbidden" });+ }++ const isPaginatedRequest = page !== undefined;++ const dataQuery = getErrorEventsQuery(req, false);++ try {+ const dataResult = await clickhouse.query({+ query: dataQuery,+ format: "JSONEachRow",+ query_params: {+ siteId: Number(site),+ errorMessage: errorMessage,+ },+ });+ const items = await processResults<ErrorEvent>(dataResult);++ if (isPaginatedRequest) {+ const countQuery = getErrorEventsQuery(req, true);+ const countResult = await clickhouse.query({+ query: countQuery,+ format: "JSONEachRow",+ query_params: {+ siteId: Number(site),+ errorMessage: errorMessage,+ },+ });+ const countData = await processResults<{ totalCount: number }>(+ countResult+ );+ const totalCount = countData.length > 0 ? countData[0].totalCount : 0;+ return res.send({ data: { data: items, totalCount } });+ } else {+ return res.send({ data: items });+ }+ } catch (error) {+ console.error(`Error fetching error events:`, error);+ console.error("Failed dataQuery:", dataQuery);+ if (isPaginatedRequest) {+ const countQuery = getErrorEventsQuery(req, true);+ console.error("Failed countQuery:", countQuery);+ }+ return res.status(500).send({ error: `Failed to fetch error events` });+ }+}diff --git a/server/src/api/analytics/getErrorNames.ts b/server/src/api/analytics/getErrorNames.tsnew file mode 100644index 000000000..6f6176797--- /dev/null+++ b/server/src/api/analytics/getErrorNames.ts@@ -0,0 +1,173 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { clickhouse } from "../../db/clickhouse/clickhouse.js";+import { getUserHasAccessToSitePublic } from "../../lib/auth-utils.js";+import {+ getFilterStatement,+ getTimeStatement,+ processResults,+} from "./utils.js";+import { FilterParams } from "@rybbit/shared";++interface GetErrorNamesRequest {+ Params: {+ site: string;+ };+ Querystring: FilterParams<{+ limit?: number;+ page?: number;+ }>;+}++// This type represents a single error item in the array+export type ErrorNameItem = {+ value: string; // Error message+ errorName: string; // Error type (TypeError, ReferenceError, etc.)+ count: number; // Total occurrences+ sessionCount: number; // Unique sessions affected+ percentage: number;+};++// Structure for paginated response+type ErrorNamesPaginatedResponse = {+ data: ErrorNameItem[];+ totalCount: number;+};++const getErrorNamesQuery = (+ request: FastifyRequest<GetErrorNamesRequest>,+ isCountQuery: boolean = false+) => {+ const { filters, limit, page } = request.query;++ const filterStatement = getFilterStatement(filters);+ const timeStatement = getTimeStatement(request.query);++ let validatedLimit: number | null = null;+ if (!isCountQuery && limit !== undefined) {+ const parsedLimit = parseInt(String(limit), 10);+ if (!isNaN(parsedLimit) && parsedLimit > 0) {+ validatedLimit = parsedLimit;+ }+ }+ // Default to 10 for non-paginated use+ const limitStatement =+ !isCountQuery && validatedLimit+ ? `LIMIT ${validatedLimit}`+ : isCountQuery+ ? ""+ : "LIMIT 10";++ let validatedOffset: number | null = null;+ if (!isCountQuery && page !== undefined) {+ const parsedPage = parseInt(String(page), 10);+ if (!isNaN(parsedPage) && parsedPage >= 1) {+ const pageOffset = (parsedPage - 1) * (validatedLimit || 10);+ validatedOffset = pageOffset;+ }+ }+ const offsetStatement =+ !isCountQuery && validatedOffset ? `OFFSET ${validatedOffset}` : "";++ // For errors, we want to count total occurrences and unique sessions affected+ // Group by error message instead of error name+ const baseCteQuery = `+ ErrorStats AS (+ SELECT+ JSONExtractString(toString(props), 'message') as value,+ any(event_name) as errorName,+ count(*) as total_occurrences,+ count(DISTINCT session_id) as unique_sessions+ FROM events+ WHERE+ site_id = {siteId:Int32}+ AND type = 'error'+ AND event_name IS NOT NULL+ AND event_name <> ''+ AND JSONHas(toString(props), 'message')+ AND JSONExtractString(toString(props), 'message') <> ''+ ${filterStatement}+ ${timeStatement}+ GROUP BY value+ )+ `;++ if (isCountQuery) {+ return `+ WITH ${baseCteQuery}+ SELECT COUNT(*) as totalCount FROM ErrorStats;+ `;+ }++ return `+ WITH ${baseCteQuery}+ SELECT+ value,+ errorName,+ total_occurrences as count,+ unique_sessions as sessionCount,+ ROUND(+ unique_sessions * 100.0 / SUM(unique_sessions) OVER (),+ 2+ ) as percentage+ FROM ErrorStats+ ORDER BY total_occurrences DESC+ ${limitStatement}+ ${offsetStatement}+ `;+};++export async function getErrorNames(+ req: FastifyRequest<GetErrorNamesRequest>,+ res: FastifyReply+) {+ const site = req.params.site;+ const { page } = req.query;++ const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);+ if (!userHasAccessToSite) {+ return res.status(403).send({ error: "Forbidden" });+ }++ const isPaginatedRequest = page !== undefined; // True if page is present++ const dataQuery = getErrorNamesQuery(req, false);++ try {+ const dataResult = await clickhouse.query({+ query: dataQuery,+ format: "JSONEachRow",+ query_params: {+ siteId: Number(site),+ },+ });+ const items = await processResults<ErrorNameItem>(dataResult);++ if (isPaginatedRequest) {+ const countQuery = getErrorNamesQuery(req, true);+ const countResult = await clickhouse.query({+ query: countQuery,+ format: "JSONEachRow",+ query_params: {+ siteId: Number(site),+ },+ });+ const countData = await processResults<{ totalCount: number }>(+ countResult+ );+ const totalCount = countData.length > 0 ? countData[0].totalCount : 0;+ return res.send({ data: { data: items, totalCount } });+ } else {+ // For non-paginated (StandardSection default) use, return the simpler structure+ console.info(items);+ return res.send({ data: items });+ }+ } catch (error) {+ console.error(`Error fetching error names:`, error);+ console.error("Failed dataQuery:", dataQuery);+ if (isPaginatedRequest) {+ const countQuery = getErrorNamesQuery(req, true);+ console.error("Failed countQuery:", countQuery);+ }+ return res.status(500).send({ error: `Failed to fetch error names` });+ }+}diff --git a/server/src/api/analytics/getOverviewBucketed.ts b/server/src/api/analytics/getOverviewBucketed.tsindex 86c4d435b..81fe10f8b 100644--- a/server/src/api/analytics/getOverviewBucketed.ts+++ b/server/src/api/analytics/getOverviewBucketed.ts@@ -8,31 +8,11 @@ import {getFilterStatement,getTimeStatement,processResults,+ TimeBucketToFn,+ bucketIntervalMap,} from "./utils.js";+import { TimeBucket } from "./types.js";-const TimeBucketToFn = {- minute: "toStartOfMinute",- five_minutes: "toStartOfFiveMinutes",- ten_minutes: "toStartOfTenMinutes",- fifteen_minutes: "toStartOfFifteenMinutes",- hour: "toStartOfHour",- day: "toStartOfDay",- week: "toStartOfWeek",- month: "toStartOfMonth",- year: "toStartOfYear",-};--const bucketIntervalMap = {- minute: "1 MINUTE",- five_minutes: "5 MINUTES",- ten_minutes: "10 MINUTES",- fifteen_minutes: "15 MINUTES",- hour: "1 HOUR",- day: "1 DAY",- week: "7 DAY",- month: "1 MONTH",- year: "1 YEAR",-} as const;function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {const { params: validatedParams, bucket: validatedBucket } =@@ -192,16 +172,6 @@ ORDER BY time`;return query;};-type TimeBucket =- | "minute"- | "five_minutes"- | "ten_minutes"- | "fifteen_minutes"- | "hour"- | "day"- | "week"- | "month"- | "year";type getOverviewBucketed = { time: string; pageviews: number }[];diff --git a/server/src/api/analytics/performance/getPerformanceTimeSeries.ts b/server/src/api/analytics/performance/getPerformanceTimeSeries.tsindex b3d34dfb4..902f699b8 100644--- a/server/src/api/analytics/performance/getPerformanceTimeSeries.ts+++ b/server/src/api/analytics/performance/getPerformanceTimeSeries.ts@@ -4,6 +4,8 @@ import {getFilterStatement,getTimeStatement,processResults,+ TimeBucketToFn,+ bucketIntervalMap,} from "../utils.js";import SqlString from "sqlstring";import { getUserHasAccessToSitePublic } from "../../../lib/auth-utils.js";@@ -11,29 +13,6 @@ import { validateTimeStatementFillParams } from "../query-validation.js";import { TimeBucket, PerformanceTimeSeriesPoint } from "../types.js";import { FilterParams } from "@rybbit/shared";-const TimeBucketToFn = {- minute: "toStartOfMinute",- five_minutes: "toStartOfFiveMinutes",- ten_minutes: "toStartOfTenMinutes",- fifteen_minutes: "toStartOfFifteenMinutes",- hour: "toStartOfHour",- day: "toStartOfDay",- week: "toStartOfWeek",- month: "toStartOfMonth",- year: "toStartOfYear",-};--const bucketIntervalMap = {- minute: "1 MINUTE",- five_minutes: "5 MINUTES",- ten_minutes: "10 MINUTES",- fifteen_minutes: "15 MINUTES",- hour: "1 HOUR",- day: "1 DAY",- week: "7 DAY",- month: "1 MONTH",- year: "1 YEAR",-} as const;function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {const { params: validatedParams, bucket: validatedBucket } =diff --git a/server/src/api/analytics/utils.ts b/server/src/api/analytics/utils.tsindex 4f04170b9..7bef4324c 100644--- a/server/src/api/analytics/utils.ts+++ b/server/src/api/analytics/utils.ts@@ -297,3 +297,29 @@ export function patternToRegex(pattern: string): string {// Anchor the regex to start/end of string for exact matchesreturn `^${finalRegex}$`;}++// Time bucket mapping constants+export const TimeBucketToFn = {+ minute: "toStartOfMinute",+ five_minutes: "toStartOfFiveMinutes",+ ten_minutes: "toStartOfTenMinutes",+ fifteen_minutes: "toStartOfFifteenMinutes",+ hour: "toStartOfHour",+ day: "toStartOfDay",+ week: "toStartOfWeek",+ month: "toStartOfMonth",+ year: "toStartOfYear",+} as const;++export const bucketIntervalMap = {+ minute: "1 MINUTE",+ five_minutes: "5 MINUTES",+ ten_minutes: "10 MINUTES",+ fifteen_minutes: "15 MINUTES",+ hour: "1 HOUR",+ day: "1 DAY",+ week: "7 DAY",+ month: "1 MONTH",+ year: "1 YEAR",+} as const;+diff --git a/server/src/index.ts b/server/src/index.tsindex 37c228c7b..7869e6e75 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -20,6 +20,9 @@ import { getOrgEventCount } from "./api/analytics/getOrgEventCount.js";import { getOverview } from "./api/analytics/getOverview.js";import { getOverviewBucketed } from "./api/analytics/getOverviewBucketed.js";import { getPageTitles } from "./api/analytics/getPageTitles.js";+import { getErrorNames } from "./api/analytics/getErrorNames.js";+import { getErrorEvents } from "./api/analytics/getErrorEvents.js";+import { getErrorBucketed } from "./api/analytics/getErrorBucketed.js";import { getRetention } from "./api/analytics/getRetention.js";import { getSession } from "./api/analytics/getSession.js";import { getSessions } from "./api/analytics/getSessions.js";@@ -138,6 +141,7 @@ const ANALYTICS_ROUTES = ["/api/live-user-count/","/api/overview/","/api/overview-bucketed/",+ "/api/error-bucketed/","/api/single-col/","/api/page-titles/","/api/retention/",@@ -163,6 +167,9 @@ const ANALYTICS_ROUTES = ["/api/performance/time-series/","/api/performance/by-path/","/api/performance/by-dimension/",+ "/api/error-names/",+ "/api/error-events/",+ "/api/error-bucketed/",];server.addHook("onRequest", async (request, reply) => {@@ -203,7 +210,7 @@ server.addHook("onRequest", async (request, reply) => {});// Add this with your other routes, around line 273-server.get("/api/script.js", async (request, reply) => {+server.get("/api/script.js", async (_, reply) => {return reply.sendFile("script.js");});@@ -219,6 +226,9 @@ server.get("/api/overview/:site", getOverview);server.get("/api/overview-bucketed/:site", getOverviewBucketed);server.get("/api/single-col/:site", getSingleCol);server.get("/api/page-titles/:site", getPageTitles);+server.get("/api/error-names/:site", getErrorNames);+server.get("/api/error-events/:site", getErrorEvents);+server.get("/api/error-bucketed/:site", getErrorBucketed);server.get("/api/retention/:site", getRetention);server.get("/api/site-has-data/:site", getSiteHasData);server.get("/api/site-is-public/:site", getSiteIsPublic);diff --git a/server/src/tracker/trackEvent.ts b/server/src/tracker/trackEvent.tsindex 9d993c731..9770aefa0 100644--- a/server/src/tracker/trackEvent.ts+++ b/server/src/tracker/trackEvent.ts@@ -99,6 +99,68 @@ export const trackingPayloadSchema = z.discriminatedUnion("type", [ttfb: z.number().min(0).nullable().optional(),}).strict(),+ z+ .object({+ type: z.literal("error"),+ site_id: z.string().min(1),+ hostname: z.string().max(253).optional(),+ pathname: z.string().max(2048).optional(),+ querystring: z.string().max(2048).optional(),+ screenWidth: z.number().int().positive().optional(),+ screenHeight: z.number().int().positive().optional(),+ language: z.string().max(35).optional(),+ page_title: z.string().max(512).optional(),+ referrer: z.string().max(2048).optional(),+ event_name: z.string().min(1).max(256), // Error type (TypeError, ReferenceError, etc.)+ properties: z+ .string()+ .max(4096) // Larger limit for error details+ .refine(+ (val) => {+ try {+ const parsed = JSON.parse(val);+ // Validate error-specific properties+ if (typeof parsed.message !== "string") return false;+ if (parsed.stack && typeof parsed.stack !== "string")+ return false;++ // Support both camelCase and lowercase for backwards compatibility+ if (parsed.fileName && typeof parsed.fileName !== "string")+ return false;++ if (parsed.lineNumber && typeof parsed.lineNumber !== "number")+ return false;++ if (+ parsed.columnNumber &&+ typeof parsed.columnNumber !== "number"+ )+ return false;++ // Apply truncation limits+ if (parsed.message && parsed.message.length > 500) {+ parsed.message = parsed.message.substring(0, 500);+ }+ if (parsed.stack && parsed.stack.length > 2000) {+ parsed.stack = parsed.stack.substring(0, 2000);+ }++ return true;+ } catch (e) {+ return false;+ }+ },+ {+ message:+ "Properties must be valid JSON with error fields (message, stack, fileName, lineNumber, columnNumber)",+ }+ ),+ user_id: z.string().max(255).optional(),+ api_key: z.string().max(35).optional(), // rb_ prefix + 32 hex chars+ ip_address: z.string().ip().optional(), // Custom IP for geolocation+ user_agent: z.string().max(512).optional(), // Custom user agent+ })+ .strict(),]);// Update session for both pageviews and events@@ -306,7 +368,8 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {);return reply.status(429).send({success: false,- error: "Rate limit exceeded. Maximum 20 requests per second per API key.",+ error:+ "Rate limit exceeded. Maximum 20 requests per second per API key.",});}}diff --git a/server/src/tracker/trackingUtils.ts b/server/src/tracker/trackingUtils.tsindex acef4543e..bb05de052 100644--- a/server/src/tracker/trackingUtils.ts+++ b/server/src/tracker/trackingUtils.ts@@ -114,7 +114,7 @@ export async function getExistingSession(userId: string, siteId: string) {// Create base tracking payload from requestexport function createBasePayload(request: FastifyRequest,- eventType: "pageview" | "custom_event" | "performance" = "pageview",+ eventType: "pageview" | "custom_event" | "performance" | "error" = "pageview",validatedBody: ValidatedTrackingPayload): TotalTrackingPayload {// Use custom user agent if provided, otherwise fall back to header