Skip to content

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

Fix a batch of low-hanging dashboard and server bugs (#1303)

Goldflagbc23257db96a
diff --git a/client/messages/en.json b/client/messages/en.json
index 484285d83..5880efcea 100644
--- a/client/messages/en.json
+++ b/client/messages/en.json
@@ -821,6 +821,7 @@
"HwsSKe": "Replays of sessions that converted",
"HxrAIj": "Enter a path pattern.",
"Hy1h6W": "conversions per month",
+ "Hy4Tjd": "Couldn't load your subscription",
"I/6XsJ": "per 10 minutes",
"I3ko52": "unlimited members",
"I3rqT8": "Confirm your new password",
diff --git a/client/src/app/[site]/bots/components/sections/BotCountries.tsx b/client/src/app/[site]/bots/components/sections/BotCountries.tsx
index 71817343c..dec60d36f 100644
--- a/client/src/app/[site]/bots/components/sections/BotCountries.tsx
+++ b/client/src/app/[site]/bots/components/sections/BotCountries.tsx
@@ -1,22 +1,13 @@
"use client";
import { ChevronRight } from "lucide-react";
-import { useSubdivisions } from "../../../../../lib/geo";
+import { parseCityValue, useSubdivisions } from "../../../../../lib/geo";
import { getCountryName } from "../../../../../lib/utils";
import { CountryFlag } from "../../../components/shared/icons/CountryFlag";
import { BotSectionTabs, type BotSectionTab } from "../BotSectionTabs";
type Tab = "countries" | "regions" | "cities";
-function getCountryCity(value: string) {
- if (value.split("-").length === 2) {
- const [country, city] = value.split("-");
- return { country, region: "", city };
- }
- const [country, region, city] = value.split("-");
- return { country, region, city };
-}
-
export function BotCountries() {
const { data: subdivisions } = useSubdivisions();
@@ -73,7 +64,7 @@ export function BotCountries() {
getKey: item => item.value || "unknown",
getLabel: item => {
if (!item.value || item.value === "-") return "Unknown";
- const { country, region, city } = getCountryCity(item.value);
+ const { country, region, city } = parseCityValue(item.value);
const regionName = subdivisions?.features.find(
feature => feature.properties.iso_3166_2 === `${country}-${region}`
)?.properties.name;
diff --git a/client/src/app/[site]/components/Sidebar/Sidebar.tsx b/client/src/app/[site]/components/Sidebar/Sidebar.tsx
index d8cb23538..9568b2eb2 100644
--- a/client/src/app/[site]/components/Sidebar/Sidebar.tsx
+++ b/client/src/app/[site]/components/Sidebar/Sidebar.tsx
@@ -195,18 +195,23 @@ function SidebarContent() {
icon={<Gauge className="w-4 h-4" />}
/>
)}
- {/* API Playground is desktop-only, so on self-hosted builds without Query/Dashboards the header must hide with it */}
- <div className={IS_CLOUD || DEPLOYMENT ? undefined : "hidden md:block"}>
- <SidebarComponents.SectionHeader>{t("Explore")}</SidebarComponents.SectionHeader>
- </div>
- <div className="hidden md:block">
- <SidebarComponents.Item
- label={t("API Playground")}
- active={isActiveTab("api-playground")}
- href={getTabPath("api-playground")}
- icon={<Code className="w-4 h-4" />}
- />
- </div>
+ {/* API Playground is desktop-only, and it and Dashboards have no private-link route, so the header
+ hides with whatever is left: Query, else API Playground on desktop, else nothing */}
+ {(IS_CLOUD || DEPLOYMENT || !privateKey) && (
+ <div className={IS_CLOUD || DEPLOYMENT ? undefined : "hidden md:block"}>
+ <SidebarComponents.SectionHeader>{t("Explore")}</SidebarComponents.SectionHeader>
+ </div>
+ )}
+ {!privateKey && (
+ <div className="hidden md:block">
+ <SidebarComponents.Item
+ label={t("API Playground")}
+ active={isActiveTab("api-playground")}
+ href={getTabPath("api-playground")}
+ icon={<Code className="w-4 h-4" />}
+ />
+ </div>
+ )}
{(IS_CLOUD || DEPLOYMENT) && (
<>
<SidebarComponents.Item
@@ -215,12 +220,14 @@ function SidebarContent() {
href={getTabPath("query")}
icon={<Database className="w-4 h-4" />}
/>
- <SidebarComponents.Item
- label={t("Dashboards")}
- active={isActiveTab("dashboards")}
- href={getTabPath("dashboards")}
- icon={<LayoutGrid className="w-4 h-4" />}
- />
+ {!privateKey && (
+ <SidebarComponents.Item
+ label={t("Dashboards")}
+ active={isActiveTab("dashboards")}
+ href={getTabPath("dashboards")}
+ icon={<LayoutGrid className="w-4 h-4" />}
+ />
+ )}
</>
)}
{/* <SidebarComponents.Item
diff --git a/client/src/app/[site]/components/SubHeader/Export/exportCsv.ts b/client/src/app/[site]/components/SubHeader/Export/exportCsv.ts
index 0f077e51d..b45a76882 100644
--- a/client/src/app/[site]/components/SubHeader/Export/exportCsv.ts
+++ b/client/src/app/[site]/components/SubHeader/Export/exportCsv.ts
@@ -34,6 +34,8 @@ const METRIC_FILES: { param: FilterParameter; filename: string }[] = [
{ param: "timezone", filename: "timezones.csv" },
];
+const METRIC_EXPORT_LIMIT = 10000;
+
type ExportDescriptor = {
filename: string;
path: string;
@@ -46,7 +48,8 @@ const EXPORTS: ExportDescriptor[] = [
...METRIC_FILES.map(({ param, filename }) => ({
filename,
path: "metric",
- params: { parameter: param },
+ // The metric endpoint defaults to the top 100 rows; an export wants the long tail.
+ params: { parameter: param, limit: METRIC_EXPORT_LIMIT },
rows: (payload: { data: Record<string, unknown>[] }) => payload.data,
})),
{ filename: "overview-timeseries.csv", path: "overview/time-series", params: { bucket: "day" } },
diff --git a/client/src/app/[site]/events/components/EventLog/useEventLogState.ts b/client/src/app/[site]/events/components/EventLog/useEventLogState.ts
index d63376848..8cd55ab6b 100644
--- a/client/src/app/[site]/events/components/EventLog/useEventLogState.ts
+++ b/client/src/app/[site]/events/components/EventLog/useEventLogState.ts
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { type Arrivals, NO_ARRIVALS, recordArrivals } from "@/components/interior/use-arrival-highlight";
import { Event } from "../../../../../api/analytics/endpoints";
import { useGetEventsCursor, useNewEventsPoll } from "../../../../../api/analytics/hooks/events/useGetEvents";
+import { useStore } from "../../../../../lib/store";
import { getEventKey } from "./eventLogUtils";
const MAX_EVENTS = 10_000;
@@ -56,9 +57,13 @@ export function useEventLogState(
const cursorEvents = useMemo(() => cursorData?.pages.flatMap(p => p.data) ?? [], [cursorData]);
// --- Combined event list ---
+ // The cursor query refetches (staleTime 0, window refocus) and then returns events that already
+ // arrived live, so drop those from the prepended rows.
const mergedEvents = useMemo(() => {
if (prependedEvents.length === 0) return cursorEvents;
- return [...prependedEvents, ...cursorEvents].slice(0, MAX_EVENTS);
+ const cursorKeys = new Set(cursorEvents.map(getEventKey));
+ const liveOnly = prependedEvents.filter(ev => !cursorKeys.has(getEventKey(ev)));
+ return [...liveOnly, ...cursorEvents].slice(0, MAX_EVENTS);
}, [prependedEvents, cursorEvents]);
// --- Client-side type filter ---
@@ -68,17 +73,39 @@ export function useEventLogState(
return mergedEvents.filter(ev => visibleTypes.has(ev.type));
}, [mergedEvents, visibleTypes]);
- // --- Rebuild seenKeys + set latestTimestamp when cursor data changes ---
+ // --- Reset key: live rows were fetched for one mode, site and filter set ---
+ // Filters are compared by content: URL hydration re-sets an equal array on date changes.
+ const site = useStore(state => state.site);
+ const filtersKey = useStore(state => JSON.stringify(state.filters));
+ const resetKey = `${isRealtime}|${site}|${filtersKey}`;
+ const resetKeyRef = useRef(resetKey);
+
+ // --- Rebuild seenKeys + set latestTimestamp when cursor data changes, resetting live state first on a new key ---
+ // One effect, so a reset always re-seeds the poll cursor from the rows on screen and never re-adds the
+ // keys of live rows it just discarded.
useEffect(() => {
+ const isReset = resetKeyRef.current !== resetKey;
+ resetKeyRef.current = resetKey;
+ if (isReset) {
+ setPrependedEvents([]);
+ latestTimestampRef.current = null;
+ bufferedEventsRef.current = [];
+ setBufferedCount(0);
+ setIsLive(true);
+ setArrivals(prev => (prev.size ? NO_ARRIVALS : prev));
+ }
+
seenKeysRef.current = new Set(cursorEvents.map(getEventKey));
- for (const ev of prependedEvents) {
- seenKeysRef.current.add(getEventKey(ev));
+ if (!isReset) {
+ for (const ev of prependedEvents) {
+ seenKeysRef.current.add(getEventKey(ev));
+ }
}
if (cursorEvents.length > 0 && !latestTimestampRef.current) {
latestTimestampRef.current = cursorEvents[0].timestamp;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [cursorEvents]);
+ }, [cursorEvents, resetKey]);
// --- Poll query (realtime only) ---
const getSinceTimestamp = useCallback(() => latestTimestampRef.current, []);
@@ -124,17 +151,6 @@ export function useEventLogState(
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pollData]);
- // --- Reset on mode toggle ---
- useEffect(() => {
- setPrependedEvents([]);
- seenKeysRef.current.clear();
- latestTimestampRef.current = null;
- bufferedEventsRef.current = [];
- setBufferedCount(0);
- setIsLive(true);
- setArrivals(prev => (prev.size ? NO_ARRIVALS : prev));
- }, [isRealtime]);
-
// --- Callback ref: capture viewport whenever ScrollArea mounts ---
const scrollAreaCallbackRef = useCallback((node: HTMLDivElement | null) => {
if (node) {
diff --git a/client/src/app/[site]/funnels/components/CreateFunnel.tsx b/client/src/app/[site]/funnels/components/CreateFunnel.tsx
index 3298ce00a..edefc1bc7 100644
--- a/client/src/app/[site]/funnels/components/CreateFunnel.tsx
+++ b/client/src/app/[site]/funnels/components/CreateFunnel.tsx
@@ -44,7 +44,7 @@ export function CreateFunnelDialog() {
{ steps, name },
{
onSuccess: () => {
- setOpen(false);
+ handleOpenChange(false);
toast?.success(t("Funnel saved successfully"));
},
onError: error => {
@@ -55,7 +55,8 @@ export function CreateFunnelDialog() {
);
};
- // Reset form when the editor closes
+ // Reset form when the editor closes. Radix only calls this for its own dismissals (Esc, overlay),
+ // so save and cancel route through it too.
const handleOpenChange = (open: boolean) => {
setOpen(open);
if (!open) {
@@ -85,7 +86,7 @@ export function CreateFunnelDialog() {
steps={steps}
setSteps={setSteps}
onSave={handleSaveFunnel}
- onCancel={() => setOpen(false)}
+ onCancel={() => handleOpenChange(false)}
saveButtonText={t("Save Funnel")}
isSaving={isSaving}
isError={isError}
diff --git a/client/src/app/[site]/funnels/components/Funnel.tsx b/client/src/app/[site]/funnels/components/Funnel.tsx
index a19d17ab9..86e4ec832 100644
--- a/client/src/app/[site]/funnels/components/Funnel.tsx
+++ b/client/src/app/[site]/funnels/components/Funnel.tsx
@@ -65,7 +65,7 @@ function StepSessions({
const time = useStore(state => state.time);
const [page, setPage] = useState(1);
- const { data, isLoading } = useGetFunnelStepSessions({
+ const { data, isLoading, isError, refetch } = useGetFunnelStepSessions({
steps,
stepNumber: panel.stepIndex + 1,
siteId: Number(site),
@@ -89,6 +89,8 @@ function StepSessions({
<SessionsList
sessions={sessions.slice(0, LIMIT)}
isLoading={isLoading}
+ isError={isError}
+ onRetry={refetch}
page={page}
onPageChange={setPage}
hasNextPage={sessions.length > LIMIT}
diff --git a/client/src/app/[site]/main/components/MainSection/Overview.tsx b/client/src/app/[site]/main/components/MainSection/Overview.tsx
index d03a25fa8..fb7be672d 100644
--- a/client/src/app/[site]/main/components/MainSection/Overview.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Overview.tsx
@@ -1,12 +1,14 @@
"use client";
import { ValueFlash, type ValueFlashProps } from "@/components/interior/value-flash";
+import { Delta } from "@/components/site/Delta";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { percentDelta } from "@/lib/delta";
import { cn, formatSecondsAsMinutesAndSeconds } from "@/lib/utils";
import NumberFlow from "@number-flow/react";
-import { AlertCircle, ArrowDown, ArrowUp, ChevronDown, ChevronUp, RefreshCcw } from "lucide-react";
+import { AlertCircle, ChevronDown, ChevronUp, RefreshCcw } from "lucide-react";
import { useExtracted } from "next-intl";
import { useState } from "react";
import { useGetOverview } from "../../../../../api/analytics/hooks/useGetOverview";
@@ -32,34 +34,13 @@ export const ChangePercentage = ({
reverseColor?: boolean;
}) => {
const comparisonEnabled = useComparisonEnabled();
- const change = ((current - previous) / previous) * 100;
// Nothing to compare against: a delta here would be a percentage of a period
// the user has explicitly stopped asking for.
if (!comparisonEnabled) return null;
- if (previous === 0) {
- if (current === 0) {
- return <div className="text-sm">0%</div>;
- }
- return <div className="text-sm">+999%</div>;
- }
-
- if (change === 0) {
- return <div className="text-sm">0%</div>;
- }
-
- return (
- <div
- className={cn(
- "text-xs flex items-center gap-0.5",
- (reverseColor ? -change : change) > 0 ? "text-green-400" : "text-red-400"
- )}
- >
- {change > 0 ? <ArrowUp className="w-3 h-3" strokeWidth={3} /> : <ArrowDown className="w-3 h-3" strokeWidth={3} />}
- {Math.abs(change).toFixed(1)}%
- </div>
- );
+ // An empty comparison period draws "—" rather than an invented percentage.
+ return <Delta value={percentDelta(current, previous)} upIsGood={!reverseColor} />;
};
const Stat = ({
diff --git a/client/src/app/[site]/main/components/sections/Countries.tsx b/client/src/app/[site]/main/components/sections/Countries.tsx
index ac92ad253..016298087 100644
--- a/client/src/app/[site]/main/components/sections/Countries.tsx
+++ b/client/src/app/[site]/main/components/sections/Countries.tsx
@@ -1,7 +1,7 @@
"use client";
import { ChevronRight, Globe } from "lucide-react";
import { useExtracted } from "next-intl";
-import { useSubdivisions } from "../../../../../lib/geo";
+import { parseCityValue, useSubdivisions } from "../../../../../lib/geo";
import { getCountryName, getLanguageName } from "../../../../../lib/utils";
import { MapComponent } from "../../../components/shared/Map/MapComponent";
import {
@@ -12,15 +12,6 @@ import { CountryFlag } from "../../../components/shared/icons/CountryFlag";
type Tab = "countries" | "regions" | "languages" | "cities" | "map" | "timezones";
-function getCountryCity(value: string) {
- if (value.split("-").length === 2) {
- const [country, city] = value.split("-");
- return { country, region: "", city };
- }
- const [country, region, city] = value.split("-");
- return { country, region, city };
-}
-
// Helper to extract country code from language code
const getCountryFromLanguage = (languageCode: string): string | null => {
if (languageCode.includes("-")) {
@@ -96,7 +87,7 @@ export function Countries() {
return t("Unknown");
}
- const { country, region, city } = getCountryCity(e.value) ?? {};
+ const { country, region, city } = parseCityValue(e.value);
const region_ = subdivisions?.features.find(
feature => feature.properties.iso_3166_2 === `${country}-${region}`
)?.properties;
diff --git a/client/src/app/[site]/main/components/sections/Weekdays.tsx b/client/src/app/[site]/main/components/sections/Weekdays.tsx
index 556c4652c..11b6661a5 100644
--- a/client/src/app/[site]/main/components/sections/Weekdays.tsx
+++ b/client/src/app/[site]/main/components/sections/Weekdays.tsx
@@ -3,6 +3,7 @@ import { useExtracted } from "next-intl";
import { useMemo, useState } from "react";
import { useGetOverviewBucketed } from "../../../../../api/analytics/hooks/useGetOverviewBucketed";
import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
+import { ErrorState } from "../../../../../components/ErrorState";
import { Tabs, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
import { Card, CardContent, CardLoader } from "../../../../../components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../../../components/ui/select";
@@ -18,7 +19,7 @@ export function Weekdays() {
const timezone = getTimezone();
const t = useExtracted();
- const { data, isFetching, error } = useGetOverviewBucketed({
+ const { data, isFetching, error, refetch } = useGetOverviewBucketed({
site,
bucket: "hour",
});
@@ -167,82 +168,86 @@ export function Weekdays() {
</SelectContent>
</Select>
</div>
- <div className="flex mt-1 p-2">
- <div className="w-12">
- {/* Empty top-left cell */}
- <div className="h-5"></div>
-
- {/* Time labels - only display every other hour */}
- {Array(24)
- .fill(0)
- .map((_, hour) => (
- <div
- key={hour}
- className="h-4 text-xs flex items-center justify-end pr-2 text-neutral-600 dark:text-neutral-400"
- >
- {hour % 2 === 1 ? hourLabels[hour] : ""}
- </div>
- ))}
- </div>
-
- <div className="flex-1">
- {/* Day labels */}
- <div className="flex h-5">
- {shortDayNames.map((day, i) => (
- <div key={i} className="flex-1 text-center text-xs text-neutral-600 dark:text-neutral-400">
- {day}
- </div>
- ))}
+ {error && !data ? (
+ <ErrorState title="" message="" refetch={refetch} />
+ ) : (
+ <div className="flex mt-1 p-2">
+ <div className="w-12">
+ {/* Empty top-left cell */}
+ <div className="h-5"></div>
+
+ {/* Time labels - only display every other hour */}
+ {Array(24)
+ .fill(0)
+ .map((_, hour) => (
+ <div
+ key={hour}
+ className="h-4 text-xs flex items-center justify-end pr-2 text-neutral-600 dark:text-neutral-400"
+ >
+ {hour % 2 === 1 ? hourLabels[hour] : ""}
+ </div>
+ ))}
</div>
- {/* Heatmap grid */}
- {Array(24)
- .fill(0)
- .map((_, hour) => (
- <div key={hour} className="flex h-4">
- {Array(7)
- .fill(0)
- .map((_, day) => {
- const value =
- heatmapData &&
- heatmapData.length > day &&
- Array.isArray(heatmapData[day]) &&
- heatmapData[day].length > hour
- ? heatmapData[day][hour]
- : 0;
- const colorClass = value > 0 ? getColorIntensity(value) : "bg-neutral-50 dark:bg-neutral-850";
- return (
- <Tooltip key={day}>
- <TooltipTrigger asChild>
- <div
- className={cn(
- "flex-1 mx-0.5 hover:ring-1 hover:ring-emerald-300 transition-all rounded-sm my-0.5",
- colorClass
- )}
- />
- </TooltipTrigger>
- <TooltipContent className="p-0 border-0 bg-transparent">
- <ChartTooltip>
- <div className="flex flex-col gap-1 p-2">
- <div className="font-medium text-sm">
- {longDayNames[day]} {formatLocalTime(hour, 0)} - {formatLocalTime(hour, 59)}
- </div>
- <div className="flex items-center gap-2">
- <span className="font-semibold">{formatMetricValue(value)}</span>
- <span className="text-neutral-500 dark:text-neutral-400 text-xs">
- {getMetricDisplayName(metric)}
- </span>
+ <div className="flex-1">
+ {/* Day labels */}
+ <div className="flex h-5">
+ {shortDayNames.map((day, i) => (
+ <div key={i} className="flex-1 text-center text-xs text-neutral-600 dark:text-neutral-400">
+ {day}
+ </div>
+ ))}
+ </div>
+
+ {/* Heatmap grid */}
+ {Array(24)
+ .fill(0)
+ .map((_, hour) => (
+ <div key={hour} className="flex h-4">
+ {Array(7)
+ .fill(0)
+ .map((_, day) => {
+ const value =
+ heatmapData &&
+ heatmapData.length > day &&
+ Array.isArray(heatmapData[day]) &&
+ heatmapData[day].length > hour
+ ? heatmapData[day][hour]
+ : 0;
+ const colorClass = value > 0 ? getColorIntensity(value) : "bg-neutral-50 dark:bg-neutral-850";
+ return (
+ <Tooltip key={day}>
+ <TooltipTrigger asChild>
+ <div
+ className={cn(
+ "flex-1 mx-0.5 hover:ring-1 hover:ring-emerald-300 transition-all rounded-sm my-0.5",
+ colorClass
+ )}
+ />
+ </TooltipTrigger>
+ <TooltipContent className="p-0 border-0 bg-transparent">
+ <ChartTooltip>
+ <div className="flex flex-col gap-1 p-2">
+ <div className="font-medium text-sm">
+ {longDayNames[day]} {formatLocalTime(hour, 0)} - {formatLocalTime(hour, 59)}
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="font-semibold">{formatMetricValue(value)}</span>
+ <span className="text-neutral-500 dark:text-neutral-400 text-xs">
+ {getMetricDisplayName(metric)}
+ </span>
+ </div>
</div>
- </div>
- </ChartTooltip>
- </TooltipContent>
- </Tooltip>
- );
- })}
- </div>
- ))}
+ </ChartTooltip>
+ </TooltipContent>
+ </Tooltip>
+ );
+ })}
+ </div>
+ ))}
+ </div>
</div>
- </div>
+ )}
</CardContent>
</Card>
);
diff --git a/client/src/app/[site]/replay/components/ReplayList.tsx b/client/src/app/[site]/replay/components/ReplayList.tsx
index 140d372dc..622b065cd 100644
--- a/client/src/app/[site]/replay/components/ReplayList.tsx
+++ b/client/src/app/[site]/replay/components/ReplayList.tsx
@@ -40,11 +40,13 @@ export function ReplayList({ onSelect }: { onSelect?: () => void }) {
const totalCount = data?.pages[0]?.totalCount;
+ // The selected session lives in a global store, so it can belong to another
+ // site or a replay this list doesn't contain; fall back to the first replay.
useEffect(() => {
- if (flattenedData.length > 0 && !sessionId) {
+ if (flattenedData.length > 0 && !flattenedData.some(replay => replay.session_id === sessionId)) {
setSessionId(flattenedData[0].session_id);
}
- }, [flattenedData]);
+ }, [flattenedData, sessionId, setSessionId]);
useEffect(() => {
if (entry?.isIntersecting && hasNextPage && !isFetchingNextPage && !isLoading) {
diff --git a/client/src/app/[site]/replay/page.tsx b/client/src/app/[site]/replay/page.tsx
index c83aef1ff..fc3b53f65 100644
--- a/client/src/app/[site]/replay/page.tsx
+++ b/client/src/app/[site]/replay/page.tsx
@@ -29,8 +29,11 @@ export default function SessionReplayPage() {
useShallow(s => ({ minDuration: s.minDuration, sessionId: s.sessionId }))
);
- const { data, isLoading } = useGetSessionReplays({ minDuration });
- const hasNoReplays = !isLoading && !data?.pages[0].data?.length;
+ const { data, isLoading, error } = useGetSessionReplays({ minDuration });
+ // The list stays mounted even when empty: it holds the Min duration input, and
+ // a site whose recordings are all shorter than the default would otherwise
+ // have no way to lower it. Errors are shown by the list itself.
+ const hasNoReplays = !isLoading && !error && !data?.pages[0].data?.length;
// On narrow screens the player can't sit beside the list, so selecting a
// replay opens the fullscreen drawer (player + timeline) instead.
@@ -48,32 +51,34 @@ export default function SessionReplayPage() {
{/* Renders null in the common case, so it adds no flex gap. */}
<EnableSessionReplay />
- {hasNoReplays ? (
- <div className="flex flex-1 items-center justify-center">
- <NothingFound
- icon={<Video className="w-10 h-10" />}
- title={t("No session replays found")}
- description={t("Replays will appear here once session replay is enabled.")}
- />
+ <div className="flex gap-3 flex-1 min-h-0">
+ {/* List */}
+ <div className="w-full md:w-[200px] lg:w-[210px] shrink-0 min-h-0">
+ <ReplayList onSelect={isCompact ? () => setMobileOpen(true) : undefined} />
</div>
- ) : (
- <div className="flex gap-3 flex-1 min-h-0">
- {/* List */}
- <div className="w-full md:w-[200px] lg:w-[210px] shrink-0 min-h-0">
- <ReplayList onSelect={isCompact ? () => setMobileOpen(true) : undefined} />
- </div>
- {/* Player */}
- <div ref={playerRef} className="hidden md:block flex-1 min-w-0 overflow-hidden">
- {playerWidth && playerHeight ? <ReplayPlayer width={playerWidth} height={playerHeight} /> : null}
+ {hasNoReplays ? (
+ <div className="hidden md:flex flex-1 items-center justify-center">
+ <NothingFound
+ icon={<Video className="w-10 h-10" />}
+ title={t("No session replays found")}
+ description={t("Replays will appear here once session replay is enabled.")}
+ />
</div>
+ ) : (
+ <>
+ {/* Player */}
+ <div ref={playerRef} className="hidden md:block flex-1 min-w-0 overflow-hidden">
+ {playerWidth && playerHeight ? <ReplayPlayer width={playerWidth} height={playerHeight} /> : null}
+ </div>
- {/* Timeline */}
- <div className="hidden xl:block w-[300px] shrink-0 min-h-0">
- <ReplayBreadcrumbs />
- </div>
- </div>
- )}
+ {/* Timeline */}
+ <div className="hidden xl:block w-[300px] shrink-0 min-h-0">
+ <ReplayBreadcrumbs />
+ </div>
+ </>
+ )}
+ </div>
{isCompact && <ReplayDrawer sessionId={sessionId} open={mobileOpen} onOpenChange={setMobileOpen} />}
</div>
diff --git a/client/src/app/[site]/sessions/components/SessionsStatBand.test.tsx b/client/src/app/[site]/sessions/components/SessionsStatBand.test.tsx
index 186ebdb6b..885725c1e 100644
--- a/client/src/app/[site]/sessions/components/SessionsStatBand.test.tsx
+++ b/client/src/app/[site]/sessions/components/SessionsStatBand.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, render, screen } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SessionsSummary } from "@/api/analytics/endpoints";
import { SessionsStatBand } from "./SessionsStatBand";
@@ -137,4 +137,14 @@ describe("SessionsStatBand", () => {
expect(screen.queryByText("0s")).toBeNull();
expect(document.querySelectorAll(".animate-pulse").length).toBeGreaterThan(0);
});
+
+ it("shows an error with a retry instead of loading forever when the summary fails", () => {
+ const refetch = vi.fn();
+ render(<SessionsStatBand summary={undefined} previous={undefined} isLoading={false} isError refetch={refetch} />);
+
+ expect(screen.getByText("Failed to load data")).toBeTruthy();
+ expect(document.querySelectorAll(".animate-pulse")).toHaveLength(0);
+ fireEvent.click(screen.getByRole("button", { name: /Try Again/ }));
+ expect(refetch).toHaveBeenCalledOnce();
+ });
});
diff --git a/client/src/app/[site]/sessions/components/SessionsStatBand.tsx b/client/src/app/[site]/sessions/components/SessionsStatBand.tsx
index 89493677f..50e047d0e 100644
--- a/client/src/app/[site]/sessions/components/SessionsStatBand.tsx
+++ b/client/src/app/[site]/sessions/components/SessionsStatBand.tsx
@@ -3,6 +3,7 @@
import { Clock, Files, LogOut, Rewind, Target, TriangleAlert } from "lucide-react";
import { useExtracted } from "next-intl";
import { SessionsSummary } from "@/api/analytics/endpoints";
+import { ErrorState } from "@/components/ErrorState";
import { StatBand } from "@/components/site/StatBand";
import { formatShortDuration } from "@/lib/dateTimeUtils";
import { percentDelta, pointDelta } from "@/lib/delta";
@@ -22,16 +23,27 @@ interface SessionsStatBandProps {
/** The comparison period's summary; undefined while it loads or when the comparison is off. */
previous: SessionsSummary | undefined;
isLoading: boolean;
+ isError?: boolean;
+ refetch?: () => void;
}
/**
* The period at a glance. These figures describe every session the filters
* allow; the ranges and the saved views narrow the ledger below, not the band.
*/
-export function SessionsStatBand({ summary, previous, isLoading }: SessionsStatBandProps) {
+export function SessionsStatBand({ summary, previous, isLoading, isError, refetch }: SessionsStatBandProps) {
const t = useExtracted();
const comparisonEnabled = useComparisonEnabled();
+ // Without this the band would wait on a summary that never arrives and skeleton forever.
+ if (isError) {
+ return (
+ <div className="flex rounded-lg border border-neutral-100 bg-white dark:border-neutral-850 dark:bg-neutral-900">
+ <ErrorState title="" message="" refetch={refetch} />
+ </div>
+ );
+ }
+
// With the comparison on, the line is reserved while the previous period loads.
const previousLine = (format: (period: SessionsSummary) => string) =>
comparisonEnabled ? (previous ? t("{value} prev.", { value: format(previous) }) : "") : undefined;
diff --git a/client/src/app/[site]/sessions/page.tsx b/client/src/app/[site]/sessions/page.tsx
index 210d9978a..3c19c5a1c 100644
--- a/client/src/app/[site]/sessions/page.tsx
+++ b/client/src/app/[site]/sessions/page.tsx
@@ -60,7 +60,12 @@ export default function SessionsPage() {
includeGoals: true,
...rangeParams,
});
- const { data: summary, isLoading: isSummaryLoading } = useGetSessionsSummary(rangeParams);
+ const {
+ data: summary,
+ isLoading: isSummaryLoading,
+ isError: isSummaryError,
+ refetch: refetchSummary,
+ } = useGetSessionsSummary(rangeParams);
// The band describes the whole period, so its comparison takes no ranges.
const { data: previousSummary } = useGetSessionsSummary({ periodTime: "previous" });
@@ -79,6 +84,8 @@ export default function SessionsPage() {
summary={summary}
previous={comparisonEnabled ? previousSummary : undefined}
isLoading={isSummaryLoading}
+ isError={isSummaryError && !summary}
+ refetch={refetchSummary}
/>
<AnalysisBar
end={
diff --git a/client/src/app/[site]/user/[userId]/components/UserSessions.tsx b/client/src/app/[site]/user/[userId]/components/UserSessions.tsx
index 57ea479c5..3d9263a87 100644
--- a/client/src/app/[site]/user/[userId]/components/UserSessions.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserSessions.tsx
@@ -7,6 +7,7 @@ import { useRef, useState } from "react";
import { useGetSessions } from "../../../../../api/analytics/hooks/useGetUserSessions";
import { useUserGoals, useUserSessionGoals } from "../../../../../api/analytics/hooks/useUserProfile";
import { Time } from "../../../../../components/DateSelector/types";
+import { ErrorState } from "../../../../../components/ErrorState";
import { NothingFound } from "../../../../../components/NothingFound";
import { Pagination } from "../../../../../components/pagination";
import { SessionsList } from "../../../../../components/Sessions/SessionsList";
@@ -50,7 +51,7 @@ export function UserSessions({ userId, breakdown, selectedDay, onClearDay, total
const dayTime: Time | undefined = selectedDay ? { mode: "day", day: selectedDay } : undefined;
// One row past the page size tells whether there is a next page.
- const { data, isLoading } = useGetSessions({
+ const { data, isLoading, isError, refetch } = useGetSessions({
userId,
page,
limit: SESSIONS_PAGE_SIZE + 1,
@@ -168,6 +169,10 @@ export function UserSessions({ userId, breakdown, selectedDay, onClearDay, total
{isLoading ? (
<LedgerSkeleton />
+ ) : isError && !data ? (
+ <Card>
+ <ErrorState title="" message="" refetch={refetch} />
+ </Card>
) : sessions.length === 0 ? (
<NothingFound
icon={<Rewind className="w-10 h-10" />}
@@ -217,6 +222,8 @@ export function UserSessions({ userId, breakdown, selectedDay, onClearDay, total
<SessionsList
sessions={sessions}
isLoading={isLoading}
+ isError={isError}
+ onRetry={refetch}
page={page}
onPageChange={changePage}
hasNextPage={hasNextPage}
@@ -227,7 +234,7 @@ export function UserSessions({ userId, breakdown, selectedDay, onClearDay, total
/>
)}
- {!isLoading && sessions.length >= 10 && (hasNextPage || hasPrevPage) && (
+ {!isLoading && !isError && sessions.length >= 10 && (hasNextPage || hasPrevPage) && (
<Pagination
page={page}
onPageChange={changePageFromBottom}
diff --git a/client/src/app/as/callback/page.tsx b/client/src/app/as/callback/page.tsx
index 50e93baf2..f970cf061 100644
--- a/client/src/app/as/callback/page.tsx
+++ b/client/src/app/as/callback/page.tsx
@@ -300,6 +300,7 @@ export default function AppSumoSignupPage() {
id="email"
label="Email"
type="email"
+ autoComplete="email"
placeholder="[email protected]"
required
value={email}
@@ -310,6 +311,7 @@ export default function AppSumoSignupPage() {
id="password"
label="Password"
type="password"
+ autoComplete="new-password"
placeholder="••••••••"
required
value={password}
diff --git a/client/src/app/invitation/components/login.tsx b/client/src/app/invitation/components/login.tsx
index 7a165d3a1..8b64b7768 100644
--- a/client/src/app/invitation/components/login.tsx
+++ b/client/src/app/invitation/components/login.tsx
@@ -57,6 +57,7 @@ export function Login({ callbackURL }: LoginProps) {
id="email"
label={t("Email")}
type="email"
+ autoComplete="email"
placeholder="[email protected]"
required
value={email}
@@ -66,6 +67,7 @@ export function Login({ callbackURL }: LoginProps) {
id="password"
label={t("Password")}
type="password"
+ autoComplete="current-password"
placeholder="••••••••"
required
value={password}
diff --git a/client/src/app/invitation/components/signup.tsx b/client/src/app/invitation/components/signup.tsx
index 2a4e48667..d8150273f 100644
--- a/client/src/app/invitation/components/signup.tsx
+++ b/client/src/app/invitation/components/signup.tsx
@@ -78,6 +78,7 @@ export function Signup({ callbackURL }: SignupProps) {
id="email"
label={t("Email")}
type="email"
+ autoComplete="email"
placeholder="[email protected]"
required
value={email}
@@ -88,6 +89,7 @@ export function Signup({ callbackURL }: SignupProps) {
id="password"
label={t("Password")}
type="password"
+ autoComplete="new-password"
placeholder="••••••••"
required
value={password}
diff --git a/client/src/app/login/page.tsx b/client/src/app/login/page.tsx
index 852e67071..0a3c0756c 100644
--- a/client/src/app/login/page.tsx
+++ b/client/src/app/login/page.tsx
@@ -96,6 +96,7 @@ function LoginPage() {
id="email"
label={t("Email")}
type="email"
+ autoComplete="email"
placeholder="[email protected]"
required
value={email}
@@ -106,6 +107,7 @@ function LoginPage() {
id="password"
label={t("Password")}
type="password"
+ autoComplete="current-password"
placeholder="••••••••"
required
value={password}
diff --git a/client/src/app/reset-password/page.tsx b/client/src/app/reset-password/page.tsx
index 92cbb5f5e..afeefe0ba 100644
--- a/client/src/app/reset-password/page.tsx
+++ b/client/src/app/reset-password/page.tsx
@@ -145,6 +145,7 @@ export default function ResetPasswordPage() {
id="new-password"
label={t("New Password")}
type="password"
+ autoComplete="new-password"
placeholder="••••••••"
required
value={newPassword}
@@ -177,6 +178,7 @@ export default function ResetPasswordPage() {
id="email"
label={t("Email")}
type="email"
+ autoComplete="email"
placeholder="[email protected]"
required
value={email}
diff --git a/client/src/app/rollup/components/sections/Countries.tsx b/client/src/app/rollup/components/sections/Countries.tsx
index c38cb6e8e..ce2cc7b01 100644
--- a/client/src/app/rollup/components/sections/Countries.tsx
+++ b/client/src/app/rollup/components/sections/Countries.tsx
@@ -11,21 +11,12 @@ import {
} from "@/components/ui/basic-tabs";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
-import { useSubdivisions } from "@/lib/geo";
+import { parseCityValue, useSubdivisions } from "@/lib/geo";
import { getCountryName, getLanguageName } from "@/lib/utils";
import { RollupSection } from "./RollupSection";
type Tab = "countries" | "regions" | "cities" | "languages" | "timezones";
-function getCountryCity(value: string) {
- if (value.split("-").length === 2) {
- const [country, city] = value.split("-");
- return { country, region: "", city };
- }
- const [country, region, city] = value.split("-");
- return { country, region, city };
-}
-
const getCountryFromLanguage = (languageCode: string): string | null => {
if (languageCode.includes("-")) {
const [_, region] = languageCode.split("-");
@@ -122,7 +113,7 @@ export function Countries({ siteIds }: { siteIds: number[] }) {
getValue={(e) => e.value}
getLabel={(e) => {
if (!e.value || e.value === "-") return t("Unknown");
- const { country, region, city } = getCountryCity(e.value) ?? {};
+ const { country, region, city } = parseCityValue(e.value);
const region_ = subdivisions?.features.find(
(f) => f.properties.iso_3166_2 === `${country}-${region}`
)?.properties;
diff --git a/client/src/app/settings/account/components/ChangePassword.tsx b/client/src/app/settings/account/components/ChangePassword.tsx
index 85737aea5..4830925cd 100644
--- a/client/src/app/settings/account/components/ChangePassword.tsx
+++ b/client/src/app/settings/account/components/ChangePassword.tsx
@@ -149,6 +149,7 @@ export function ChangePassword() {
value={currentPassword}
onChange={e => setCurrentPassword(e.target.value)}
type="password"
+ autoComplete="current-password"
placeholder={t("Your current password")}
className="pr-10"
/>
@@ -184,6 +185,7 @@ export function ChangePassword() {
value={newPassword}
onChange={e => setNewPassword(e.target.value)}
type="password"
+ autoComplete="new-password"
placeholder={t("Your new password")}
className="pr-10"
/>
@@ -240,6 +242,7 @@ export function ChangePassword() {
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
type="password"
+ autoComplete="new-password"
placeholder={t("Confirm your new password")}
className="pr-10"
/>
diff --git a/client/src/app/settings/billing/page.tsx b/client/src/app/settings/billing/page.tsx
index 94ed84781..8cf17c440 100644
--- a/client/src/app/settings/billing/page.tsx
+++ b/client/src/app/settings/billing/page.tsx
@@ -2,6 +2,7 @@
import { useExtracted } from "next-intl";
import { useEffect } from "react";
+import { ErrorState } from "@/components/ErrorState";
import { NoOrganization } from "@/components/NoOrganization";
import { AppSumoPlan } from "@/components/subscription/AppSumoPlan";
import { CustomPlan } from "@/components/subscription/CustomPlan";
@@ -50,7 +51,12 @@ function BillingSkeleton() {
export default function OrganizationBillingPage() {
useSetPageTitle("Organization Billing");
const t = useExtracted();
- const { data: activeSubscription, isLoading: isLoadingSubscription } = useStripeSubscription();
+ const {
+ data: activeSubscription,
+ isLoading: isLoadingSubscription,
+ isError: isSubscriptionError,
+ refetch: refetchSubscription,
+ } = useStripeSubscription();
const { data: activeOrg, isPending } = authClient.useActiveOrganization();
const { data: session } = authClient.useSession();
@@ -88,6 +94,19 @@ export default function OrganizationBillingPage() {
);
}
+ // A failed fetch leaves no subscription either; without this a paying owner would be told their trial expired.
+ if (isSubscriptionError && !activeSubscription) {
+ return (
+ <LedgerSection title={t("Plan")}>
+ <LedgerRows>
+ <LedgerRow label={t("Current plan")}>
+ <ErrorState title={t("Couldn't load your subscription")} message="" refetch={refetchSubscription} />
+ </LedgerRow>
+ </LedgerRows>
+ </LedgerSection>
+ );
+ }
+
if (!activeSubscription) {
return <ExpiredTrialPlan />;
}
diff --git a/client/src/app/settings/organization/components/CreateUserDialog.tsx b/client/src/app/settings/organization/components/CreateUserDialog.tsx
index aba8d1216..adfd791fe 100644
--- a/client/src/app/settings/organization/components/CreateUserDialog.tsx
+++ b/client/src/app/settings/organization/components/CreateUserDialog.tsx
@@ -122,6 +122,7 @@ export function CreateUserDialog({ organizationId, onSuccess, assignableRoles }:
<Input
id="password"
type="password"
+ autoComplete="new-password"
placeholder="********"
value={password}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}
diff --git a/client/src/app/signup/components/AccountStep.tsx b/client/src/app/signup/components/AccountStep.tsx
index c7a43192c..3006a4217 100644
--- a/client/src/app/signup/components/AccountStep.tsx
+++ b/client/src/app/signup/components/AccountStep.tsx
@@ -55,6 +55,7 @@ export function AccountStep({
id="email"
label={t("Email")}
type="email"
+ autoComplete="email"
placeholder="[email protected]"
required
value={email}
@@ -64,6 +65,7 @@ export function AccountStep({
id="password"
label={t("Password")}
type="password"
+ autoComplete="new-password"
placeholder="••••••••"
required
value={password}
diff --git a/client/src/app/widget/[siteId]/route.ts b/client/src/app/widget/[siteId]/route.ts
index 4104a2945..210ec496d 100644
--- a/client/src/app/widget/[siteId]/route.ts
+++ b/client/src/app/widget/[siteId]/route.ts
@@ -1,4 +1,5 @@
import { NextRequest } from "next/server";
+import { BACKEND_URL } from "@/lib/const";
const ALLOWED_MINUTES = new Set([30, 1440, 10080]);
@@ -8,11 +9,6 @@ const MINUTES_LABEL: Record<number, string> = {
10080: "LAST 7 DAYS",
};
-function getBackendUrl() {
- const raw = process.env.NEXT_PUBLIC_BACKEND_URL || "http://localhost:3001";
- return raw === "http://localhost:3001" ? "http://localhost:3001/api" : `${raw}/api`;
-}
-
interface Config {
siteId: string;
minutes: number;
@@ -323,7 +319,10 @@ export async function GET(
theme,
accent,
variant,
- backendUrl: getBackendUrl(),
+ // The widget's script fetches from the browser inside the iframe, which is served from this
+ // app's origin, so the dashboard's URL works here too, including the relative "/api" that
+ // self-hosted images are built with (an empty NEXT_PUBLIC_BACKEND_URL).
+ backendUrl: BACKEND_URL,
windowLabel: MINUTES_LABEL[minutes],
});
diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsx
index 65c65ce99..158343e59 100644
--- a/client/src/components/Sessions/SessionCard.tsx
+++ b/client/src/components/Sessions/SessionCard.tsx
@@ -6,9 +6,9 @@ import { ArrowRight, ChevronDown, ChevronRight, Video } from "lucide-react";
import { DateTime } from "luxon";
import { useExtracted } from "next-intl";
import Link from "next/link";
-import { useParams } from "next/navigation";
import { memo, useCallback, useState } from "react";
import { GetSessionsResponse } from "../../api/analytics/endpoints";
+import { useSitePath } from "@/app/[site]/sessions/components/useSitePath";
import { useDateTimeFormat } from "@/hooks/useDateTimeFormat";
import { formatShortDuration } from "../../lib/dateTimeUtils";
import { cn, formatter, getUserDisplayName, truncateString } from "../../lib/utils";
@@ -36,7 +36,7 @@ interface SessionCardProps {
}
export function SessionCard({ session, onClick, userId, expandedByDefault, highlightedEventTimestamp }: SessionCardProps) {
- const { site } = useParams();
+ const sitePath = useSitePath();
const t = useExtracted();
const { hour12, formatDateTime } = useDateTimeFormat();
const [expanded, setExpanded] = useState(expandedByDefault || false);
@@ -181,9 +181,9 @@ export function SessionCard({ session, onClick, userId, expandedByDefault, highl
<div className="hidden md:flex items-center gap-2">
{!userId && (
<Link
- href={`/${site}/user/${encodeURIComponent(
+ href={sitePath(`user/${encodeURIComponent(
isIdentified ? session.identified_user_id : session.user_id
- )}`}
+ )}`)}
onClick={e => e.stopPropagation()}
className="flex items-center gap-2"
>
diff --git a/client/src/components/Sessions/SessionDetails/SessionDetails.tsx b/client/src/components/Sessions/SessionDetails/SessionDetails.tsx
index e750aed88..a42f8447e 100644
--- a/client/src/components/Sessions/SessionDetails/SessionDetails.tsx
+++ b/client/src/components/Sessions/SessionDetails/SessionDetails.tsx
@@ -1,9 +1,9 @@
import { Alert, AlertDescription } from "@/components/ui/alert";
+import { useSitePath } from "@/app/[site]/sessions/components/useSitePath";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/basic-tabs";
import { ArrowRight } from "lucide-react";
import { useExtracted } from "next-intl";
import Link from "next/link";
-import { useParams } from "next/navigation";
import { useMemo, useState } from "react";
import { useGetSessionDetailsInfinite } from "../../../api/analytics/hooks/useGetUserSessions";
@@ -28,7 +28,7 @@ export function SessionDetails({ session, userId, highlightedEventTimestamp }: S
hasNextPage,
isFetchingNextPage,
} = useGetSessionDetailsInfinite(session.session_id);
- const { site } = useParams();
+ const sitePath = useSitePath();
const t = useExtracted();
// Flatten all events into a single array
@@ -98,9 +98,9 @@ export function SessionDetails({ session, userId, highlightedEventTimestamp }: S
</TabsList>
{!userId && (
<Link
- href={`/${site}/user/${encodeURIComponent(
+ href={sitePath(`user/${encodeURIComponent(
isIdentified ? session.identified_user_id : session.user_id
- )}`}
+ )}`)}
>
<Button size={"sm"} variant={"success"}>
{t("View User")} <ArrowRight className="w-4 h-4" />
diff --git a/client/src/components/Sessions/SessionsList.tsx b/client/src/components/Sessions/SessionsList.tsx
index 6e744d9d7..001f357fb 100644
--- a/client/src/components/Sessions/SessionsList.tsx
+++ b/client/src/components/Sessions/SessionsList.tsx
@@ -1,6 +1,7 @@
import { Rewind } from "lucide-react";
import { useExtracted } from "next-intl";
import { GetSessionsResponse } from "../../api/analytics/endpoints";
+import { ErrorState } from "../ErrorState";
import { NothingFound } from "../NothingFound";
import { Pagination } from "../pagination";
import { SessionCard, SessionCardSkeleton } from "./SessionCard";
@@ -8,6 +9,9 @@ import { SessionCard, SessionCardSkeleton } from "./SessionCard";
interface SessionsListProps {
sessions: GetSessionsResponse;
isLoading: boolean;
+ /** A failed fetch shows an error with a retry, not "No sessions found". */
+ isError?: boolean;
+ onRetry?: () => void;
page: number;
onPageChange: (page: number) => void;
hasNextPage: boolean;
@@ -21,6 +25,8 @@ interface SessionsListProps {
export function SessionsList({
sessions,
isLoading,
+ isError,
+ onRetry,
page,
onPageChange,
hasNextPage,
@@ -45,7 +51,9 @@ export function SessionsList({
/>
</div>
- {sessions.length === 0 && !isLoading && (
+ {isError && !isLoading && sessions.length === 0 && <ErrorState title="" message="" refetch={onRetry} />}
+
+ {sessions.length === 0 && !isLoading && !isError && (
<NothingFound icon={<Rewind className="w-10 h-10" />} title={t("No sessions found")} description={emptyMessage || t("Try a different date range or filter")} />
)}
diff --git a/client/src/components/SiteSettings/GeneralTab.tsx b/client/src/components/SiteSettings/GeneralTab.tsx
index 7f89f7280..929e9b0d2 100644
--- a/client/src/components/SiteSettings/GeneralTab.tsx
+++ b/client/src/components/SiteSettings/GeneralTab.tsx
@@ -110,6 +110,13 @@ export function GeneralTab({
}
}, [adminMode, queryClient, refetch]);
+ // After an edit: the header, site selector and this dialog read the single-site query, not the
+ // lists. Prefix match so both string- and number-keyed useGetSite instances update.
+ const refreshSite = useCallback(() => {
+ refreshSiteLists();
+ queryClient.invalidateQueries({ queryKey: ["get-site"] });
+ }, [queryClient, refreshSiteLists]);
+
const handleToggle = useCallback(
async (
key: keyof typeof toggleStates,
@@ -129,7 +136,7 @@ export function GeneralTab({
: successMessage.disabled
: `${key.replace(/([A-Z])/g, " $1").toLowerCase()} ${checked ? "enabled" : "disabled"}`;
toast.success(message);
- refreshSiteLists();
+ refreshSite();
} catch (error) {
console.error(`Error updating ${key}:`, error);
toast.error(`Failed to update ${key.replace(/([A-Z])/g, " $1").toLowerCase()}`);
@@ -138,7 +145,7 @@ export function GeneralTab({
setLoadingStates(prev => ({ ...prev, [key]: false }));
}
},
- [siteMetadata.siteId, onPublicChange, refreshSiteLists]
+ [siteMetadata.siteId, onPublicChange, refreshSite]
);
const handleNameChange = async () => {
@@ -152,7 +159,7 @@ export function GeneralTab({
await updateSiteConfig(siteMetadata.siteId, { name: newName.trim() });
toast.success(t("Name updated successfully"));
router.refresh();
- refreshSiteLists();
+ refreshSite();
} catch (error) {
console.error("Error changing name:", error);
toast.error(t("Failed to update name"));
@@ -173,7 +180,7 @@ export function GeneralTab({
await updateSiteConfig(siteMetadata.siteId, { domain: normalizedDomain });
toast.success(isMobileSite ? t("App identifier updated successfully") : t("Domain updated successfully"));
router.refresh();
- refreshSiteLists();
+ refreshSite();
} catch (error) {
console.error("Error changing domain:", error);
toast.error(t("Failed to update domain"));
diff --git a/client/src/components/SiteSettings/ImportManager.tsx b/client/src/components/SiteSettings/ImportManager.tsx
index 4d8e11daf..b7149577b 100644
--- a/client/src/components/SiteSettings/ImportManager.tsx
+++ b/client/src/components/SiteSettings/ImportManager.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo, useState, useRef, useEffect } from "react";
+import { useMemo, useState, useRef } from "react";
import { DateTime } from "luxon";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -66,7 +66,6 @@ export function ImportManager({ siteId, disabled }: ImportManagerProps) {
const [selectedPlatform, setSelectedPlatform] = useState<ImportPlatform | "">("");
const [fileError, setFileError] = useState<string>("");
const fileInputRef = useRef<HTMLInputElement>(null);
- const workerManagerRef = useRef<CsvParser | PlausibleCsvParser | null>(null);
function validateFile(file: File | null, platform: ImportPlatform | ""): string {
if (!file) {
@@ -91,12 +90,6 @@ export function ImportManager({ siteId, disabled }: ImportManagerProps) {
const createImportMutation = useCreateSiteImport(siteId);
const deleteMutation = useDeleteSiteImport(siteId);
- useEffect(() => {
- return () => {
- workerManagerRef.current?.cancel();
- };
- }, []);
-
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0] || null;
setSelectedFile(file);
@@ -114,49 +107,54 @@ export function ImportManager({ siteId, disabled }: ImportManagerProps) {
}
};
- const executeImport = () => {
+ const executeImport = async () => {
if (!selectedFile || !selectedPlatform) return;
+ const file = selectedFile;
+ const platform = selectedPlatform;
+ setShowConfirmDialog(false);
- createImportMutation.mutate(
- { platform: selectedPlatform },
- {
- onSuccess: response => {
- const { importId, allowedDateRange } = response.data;
-
- if (selectedPlatform === "plausible") {
- const parser = new PlausibleCsvParser(
- siteId,
- importId,
- allowedDateRange.earliestAllowedDate,
- allowedDateRange.latestAllowedDate
- );
- workerManagerRef.current = parser;
- parser.startImport(selectedFile).catch(err => {
- console.error("Plausible import failed:", err);
- });
- } else {
- const parser = new CsvParser(
- siteId,
- importId,
- selectedPlatform,
- allowedDateRange.earliestAllowedDate,
- allowedDateRange.latestAllowedDate
- );
- workerManagerRef.current = parser;
- parser.startImport(selectedFile);
- }
-
- setSelectedFile(null);
- setSelectedPlatform("");
- setFileError("");
- if (fileInputRef.current) {
- fileInputRef.current.value = "";
- }
- },
- }
- );
+ // mutateAsync rather than a per-call onSuccess: React Query drops per-call callbacks once the
+ // component unmounts (closing the dialog mid-request), which would leave the import created
+ // on the server with no parser feeding it.
+ let response;
+ try {
+ response = await createImportMutation.mutateAsync({ platform });
+ } catch (error) {
+ console.error("Failed to create import:", error);
+ return;
+ }
+ const { importId, allowedDateRange } = response.data;
- setShowConfirmDialog(false);
+ if (platform === "plausible") {
+ const parser = new PlausibleCsvParser(
+ siteId,
+ importId,
+ allowedDateRange.earliestAllowedDate,
+ allowedDateRange.latestAllowedDate
+ );
+ // The parser is deliberately not tied to this component: switching settings tabs or
+ // closing the dialog unmounts it, and cancelling then would strand the import
+ // "In Progress" forever (blocking new imports). It runs until done or the page unloads.
+ parser.startImport(file).catch(err => {
+ console.error("Plausible import failed:", err);
+ });
+ } else {
+ const parser = new CsvParser(
+ siteId,
+ importId,
+ platform,
+ allowedDateRange.earliestAllowedDate,
+ allowedDateRange.latestAllowedDate
+ );
+ parser.startImport(file);
+ }
+
+ setSelectedFile(null);
+ setSelectedPlatform("");
+ setFileError("");
+ if (fileInputRef.current) {
+ fileInputRef.current.value = "";
+ }
};
const handleDeleteClick = (importId: string) => {
diff --git a/client/src/components/auth/AuthInput.tsx b/client/src/components/auth/AuthInput.tsx
index 3cd23cb48..6eba1c671 100644
--- a/client/src/components/auth/AuthInput.tsx
+++ b/client/src/components/auth/AuthInput.tsx
@@ -12,6 +12,8 @@ interface AuthInputProps {
value: string;
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
required?: boolean;
+ /** Lets password managers tell sign-in from sign-up, e.g. "current-password" or "new-password". */
+ autoComplete?: string;
className?: string;
rightElement?: ReactNode;
}
@@ -24,6 +26,7 @@ export function AuthInput({
value,
onChange,
required = false,
+ autoComplete,
className = "",
rightElement,
}: AuthInputProps) {
@@ -40,6 +43,7 @@ export function AuthInput({
value={value}
onChange={onChange}
required={required}
+ autoComplete={autoComplete}
minLength={type === "password" ? 8 : undefined}
/>
</div>
diff --git a/client/src/lib/geo.test.ts b/client/src/lib/geo.test.ts
new file mode 100644
index 000000000..6a288008c
--- /dev/null
+++ b/client/src/lib/geo.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { parseCityValue } from "./geo";
+
+describe("parseCityValue", () => {
+ it("splits country, region and city", () => {
+ expect(parseCityValue("US-CA-San Francisco")).toEqual({ country: "US", region: "CA", city: "San Francisco" });
+ });
+
+ it("keeps hyphens inside the city name", () => {
+ expect(parseCityValue("US-NC-Winston-Salem")).toEqual({ country: "US", region: "NC", city: "Winston-Salem" });
+ expect(parseCityValue("FR-PAC-Aix-en-Provence")).toEqual({ country: "FR", region: "PAC", city: "Aix-en-Provence" });
+ });
+
+ it("handles a city without a region", () => {
+ expect(parseCityValue("-Paris")).toEqual({ country: "", region: "", city: "Paris" });
+ expect(parseCityValue("-Saint-Denis")).toEqual({ country: "", region: "", city: "Saint-Denis" });
+ });
+});
diff --git a/client/src/lib/geo.ts b/client/src/lib/geo.ts
index baa2579e2..bed09aed2 100644
--- a/client/src/lib/geo.ts
+++ b/client/src/lib/geo.ts
@@ -36,3 +36,21 @@ export const getRegionName = (region: string) => {
// Direct access to current data
export { getSubdivisions, getCountries };
+
+/**
+ * Splits a city metric value, `${region}-${city}`, where region is an ISO 3166-2 code ("US-NC") or
+ * empty. City names can contain hyphens themselves ("Winston-Salem"), so everything after the region
+ * belongs to the city.
+ */
+export function parseCityValue(value: string): { country: string; region: string; city: string } {
+ const parts = value.split("-");
+ if (parts.length === 2) {
+ const [country, city] = parts;
+ return { country, region: "", city };
+ }
+ if (parts[0] === "") {
+ return { country: "", region: "", city: parts.slice(1).join("-") };
+ }
+ const [country, region, ...city] = parts;
+ return { country, region, city: city.join("-") };
+}
diff --git a/server/drizzle/0024_sites_id_index.sql b/server/drizzle/0024_sites_id_index.sql
new file mode 100644
index 000000000..3966fd132
--- /dev/null
+++ b/server/drizzle/0024_sites_id_index.sql
@@ -0,0 +1 @@
+CREATE INDEX IF NOT EXISTS "sites_id_idx" ON "sites" USING btree ("id");
\ No newline at end of file
diff --git a/server/drizzle/meta/0024_snapshot.json b/server/drizzle/meta/0024_snapshot.json
new file mode 100644
index 000000000..e2379a2d5
--- /dev/null
+++ b/server/drizzle/meta/0024_snapshot.json
@@ -0,0 +1,4694 @@
+{
+ "id": "56adc13a-c882-46cd-b5ae-e366f7f67bf0",
+ "prevId": "2f39b51e-948e-4b52-acdf-2263643d1583",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accountId": {
+ "name": "accountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "providerId": {
+ "name": "providerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "idToken": {
+ "name": "idToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessTokenExpiresAt": {
+ "name": "accessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshTokenExpiresAt": {
+ "name": "refreshTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_userId_user_id_fk": {
+ "name": "account_userId_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.active_sessions": {
+ "name": "active_sessions",
+ "schema": "",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "last_activity": {
+ "name": "last_activity",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.annotations": {
+ "name": "annotations",
+ "schema": "",
+ "columns": {
+ "annotation_id": {
+ "name": "annotation_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "date": {
+ "name": "date",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "end_date": {
+ "name": "end_date",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_public": {
+ "name": "is_public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "annotations_site_date_idx": {
+ "name": "annotations_site_date_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "annotations_org_date_idx": {
+ "name": "annotations_org_date_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "annotations_site_id_sites_site_id_fk": {
+ "name": "annotations_site_id_sites_site_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "annotations_organization_id_organization_id_fk": {
+ "name": "annotations_organization_id_organization_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "annotations_user_id_user_id_fk": {
+ "name": "annotations_user_id_user_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.apikey": {
+ "name": "apikey",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start": {
+ "name": "start",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "prefix": {
+ "name": "prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refillInterval": {
+ "name": "refillInterval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refillAmount": {
+ "name": "refillAmount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRefillAt": {
+ "name": "lastRefillAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "rateLimitEnabled": {
+ "name": "rateLimitEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "rateLimitTimeWindow": {
+ "name": "rateLimitTimeWindow",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rateLimitMax": {
+ "name": "rateLimitMax",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestCount": {
+ "name": "requestCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "remaining": {
+ "name": "remaining",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRequest": {
+ "name": "lastRequest",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "configId": {
+ "name": "configId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.cancellation_feedback": {
+ "name": "cancellation_feedback",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason_details": {
+ "name": "reason_details",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retention_offer_shown": {
+ "name": "retention_offer_shown",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retention_offer_accepted": {
+ "name": "retention_offer_accepted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "outcome": {
+ "name": "outcome",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "plan_name_at_cancellation": {
+ "name": "plan_name_at_cancellation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthly_event_count_at_cancellation": {
+ "name": "monthly_event_count_at_cancellation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.dashboards": {
+ "name": "dashboards",
+ "schema": "",
+ "columns": {
+ "dashboard_id": {
+ "name": "dashboard_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{\"cards\":[]}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "dashboards_site_id_sites_site_id_fk": {
+ "name": "dashboards_site_id_sites_site_id_fk",
+ "tableFrom": "dashboards",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dashboards_user_id_user_id_fk": {
+ "name": "dashboards_user_id_user_id_fk",
+ "tableFrom": "dashboards",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.experiments": {
+ "name": "experiments",
+ "schema": "",
+ "columns": {
+ "experiment_id": {
+ "name": "experiment_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "feature_flag_id": {
+ "name": "feature_flag_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "primary_goal_id": {
+ "name": "primary_goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "hypothesis": {
+ "name": "hypothesis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'draft'"
+ },
+ "winning_variant": {
+ "name": "winning_variant",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "experiments_site_idx": {
+ "name": "experiments_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "experiments_feature_flag_idx": {
+ "name": "experiments_feature_flag_idx",
+ "columns": [
+ {
+ "expression": "feature_flag_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "experiments_primary_goal_idx": {
+ "name": "experiments_primary_goal_idx",
+ "columns": [
+ {
+ "expression": "primary_goal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "experiments_site_id_sites_site_id_fk": {
+ "name": "experiments_site_id_sites_site_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "experiments_feature_flag_id_feature_flags_flag_id_fk": {
+ "name": "experiments_feature_flag_id_feature_flags_flag_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "feature_flags",
+ "columnsFrom": [
+ "feature_flag_id"
+ ],
+ "columnsTo": [
+ "flag_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "experiments_primary_goal_id_goals_goal_id_fk": {
+ "name": "experiments_primary_goal_id_goals_goal_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "primary_goal_id"
+ ],
+ "columnsTo": [
+ "goal_id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "experiments_site_flag_unique": {
+ "name": "experiments_site_flag_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "feature_flag_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "experiments_status_check": {
+ "name": "experiments_status_check",
+ "value": "status IN ('draft', 'running', 'paused', 'completed')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.feature_flags": {
+ "name": "feature_flags",
+ "schema": "",
+ "columns": {
+ "flag_id": {
+ "name": "flag_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "runtime": {
+ "name": "runtime",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'client'"
+ },
+ "flag_type": {
+ "name": "flag_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'boolean'"
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "variants": {
+ "name": "variants",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "rollout_percentage": {
+ "name": "rollout_percentage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 100
+ },
+ "rules": {
+ "name": "rules",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "condition_sets": {
+ "name": "condition_sets",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "salt": {
+ "name": "salt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "md5(random()::text || clock_timestamp()::text)"
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feature_flags_site_idx": {
+ "name": "feature_flags_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "feature_flags_site_id_sites_site_id_fk": {
+ "name": "feature_flags_site_id_sites_site_id_fk",
+ "tableFrom": "feature_flags",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "feature_flags_site_key_unique": {
+ "name": "feature_flags_site_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "feature_flags_rollout_check": {
+ "name": "feature_flags_rollout_check",
+ "value": "rollout_percentage >= 0 AND rollout_percentage <= 100"
+ },
+ "feature_flags_runtime_check": {
+ "name": "feature_flags_runtime_check",
+ "value": "runtime IN ('client', 'server', 'both')"
+ },
+ "feature_flags_type_check": {
+ "name": "feature_flags_type_check",
+ "value": "flag_type IN ('boolean', 'multivariate', 'remote_config')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.funnels": {
+ "name": "funnels",
+ "schema": "",
+ "columns": {
+ "report_id": {
+ "name": "report_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "funnels_site_id_sites_site_id_fk": {
+ "name": "funnels_site_id_sites_site_id_fk",
+ "tableFrom": "funnels",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "funnels_user_id_user_id_fk": {
+ "name": "funnels_user_id_user_id_fk",
+ "tableFrom": "funnels",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goals": {
+ "name": "goals",
+ "schema": "",
+ "columns": {
+ "goal_id": {
+ "name": "goal_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "goal_type": {
+ "name": "goal_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_site_id_sites_site_id_fk": {
+ "name": "goals_site_id_sites_site_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.gsc_connections": {
+ "name": "gsc_connections",
+ "schema": "",
+ "columns": {
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "gsc_property_url": {
+ "name": "gsc_property_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "gsc_connections_site_id_sites_site_id_fk": {
+ "name": "gsc_connections_site_id_sites_site_id_fk",
+ "tableFrom": "gsc_connections",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.import_status": {
+ "name": "import_status",
+ "schema": "",
+ "columns": {
+ "import_id": {
+ "name": "import_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "platform": {
+ "name": "platform",
+ "type": "import_platform_enum",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "imported_events": {
+ "name": "imported_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "skipped_events": {
+ "name": "skipped_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "invalid_events": {
+ "name": "invalid_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "import_status_site_id_sites_site_id_fk": {
+ "name": "import_status_site_id_sites_site_id_fk",
+ "tableFrom": "import_status",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "import_status_organization_id_organization_id_fk": {
+ "name": "import_status_organization_id_organization_id_fk",
+ "tableFrom": "import_status",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.invitation": {
+ "name": "invitation",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "inviterId": {
+ "name": "inviterId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "has_restricted_site_access": {
+ "name": "has_restricted_site_access",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "site_ids": {
+ "name": "site_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "site_role": {
+ "name": "site_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "teamId": {
+ "name": "teamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "invitation_inviterId_user_id_fk": {
+ "name": "invitation_inviterId_user_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "user",
+ "columnsFrom": [
+ "inviterId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "invitation_organizationId_organization_id_fk": {
+ "name": "invitation_organizationId_organization_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "invitation_teamId_team_id_fk": {
+ "name": "invitation_teamId_team_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "team",
+ "columnsFrom": [
+ "teamId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.jwks": {
+ "name": "jwks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "publicKey": {
+ "name": "publicKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "privateKey": {
+ "name": "privateKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "alg": {
+ "name": "alg",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "crv": {
+ "name": "crv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.lifecycle_email_log": {
+ "name": "lifecycle_email_log",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_key": {
+ "name": "email_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "lifecycle_email_log_user_id_user_id_fk": {
+ "name": "lifecycle_email_log_user_id_user_id_fk",
+ "tableFrom": "lifecycle_email_log",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "lifecycle_email_log_user_email_key_unique": {
+ "name": "lifecycle_email_log_user_email_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user_id",
+ "email_key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member": {
+ "name": "member",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "has_restricted_site_access": {
+ "name": "has_restricted_site_access",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "member_organizationId_organization_id_fk": {
+ "name": "member_organizationId_organization_id_fk",
+ "tableFrom": "member",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "member_userId_user_id_fk": {
+ "name": "member_userId_user_id_fk",
+ "tableFrom": "member",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member_site_access": {
+ "name": "member_site_access",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "member_id": {
+ "name": "member_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "member_site_access_member_idx": {
+ "name": "member_site_access_member_idx",
+ "columns": [
+ {
+ "expression": "member_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "member_site_access_site_idx": {
+ "name": "member_site_access_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "member_site_access_member_id_member_id_fk": {
+ "name": "member_site_access_member_id_member_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "member",
+ "columnsFrom": [
+ "member_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_site_access_site_id_sites_site_id_fk": {
+ "name": "member_site_access_site_id_sites_site_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_site_access_created_by_user_id_fk": {
+ "name": "member_site_access_created_by_user_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "member_site_access_unique": {
+ "name": "member_site_access_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "member_id",
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthAccessToken": {
+ "name": "oauthAccessToken",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessTokenExpiresAt": {
+ "name": "accessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshTokenExpiresAt": {
+ "name": "refreshTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthAccessToken_clientId_oauthApplication_clientId_fk": {
+ "name": "oauthAccessToken_clientId_oauthApplication_clientId_fk",
+ "tableFrom": "oauthAccessToken",
+ "tableTo": "oauthApplication",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessToken_userId_user_id_fk": {
+ "name": "oauthAccessToken_userId_user_id_fk",
+ "tableFrom": "oauthAccessToken",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthAccessToken_accessToken_unique": {
+ "name": "oauthAccessToken_accessToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "accessToken"
+ ]
+ },
+ "oauthAccessToken_refreshToken_unique": {
+ "name": "oauthAccessToken_refreshToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "refreshToken"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthAccessTokenV2": {
+ "name": "oauthAccessTokenV2",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sessionId": {
+ "name": "sessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authorizationCodeId": {
+ "name": "authorizationCodeId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedUserInfoClaims": {
+ "name": "requestedUserInfoClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshId": {
+ "name": "refreshId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked": {
+ "name": "revoked",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "confirmation": {
+ "name": "confirmation",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "oauthAccessTokenV2_clientId_idx": {
+ "name": "oauthAccessTokenV2_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_sessionId_idx": {
+ "name": "oauthAccessTokenV2_sessionId_idx",
+ "columns": [
+ {
+ "expression": "sessionId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_userId_idx": {
+ "name": "oauthAccessTokenV2_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_authorizationCodeId_idx": {
+ "name": "oauthAccessTokenV2_authorizationCodeId_idx",
+ "columns": [
+ {
+ "expression": "authorizationCodeId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_refreshId_idx": {
+ "name": "oauthAccessTokenV2_refreshId_idx",
+ "columns": [
+ {
+ "expression": "refreshId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthAccessTokenV2_clientId_oauthClient_clientId_fk": {
+ "name": "oauthAccessTokenV2_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessTokenV2_sessionId_session_id_fk": {
+ "name": "oauthAccessTokenV2_sessionId_session_id_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "session",
+ "columnsFrom": [
+ "sessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "oauthAccessTokenV2_userId_user_id_fk": {
+ "name": "oauthAccessTokenV2_userId_user_id_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessTokenV2_refreshId_oauthRefreshToken_id_fk": {
+ "name": "oauthAccessTokenV2_refreshId_oauthRefreshToken_id_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "oauthRefreshToken",
+ "columnsFrom": [
+ "refreshId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthAccessTokenV2_token_unique": {
+ "name": "oauthAccessTokenV2_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthApplication": {
+ "name": "oauthApplication",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientSecret": {
+ "name": "clientSecret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redirectUrls": {
+ "name": "redirectUrls",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthApplication_userId_user_id_fk": {
+ "name": "oauthApplication_userId_user_id_fk",
+ "tableFrom": "oauthApplication",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthApplication_clientId_unique": {
+ "name": "oauthApplication_clientId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "clientId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthClient": {
+ "name": "oauthClient",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientSecret": {
+ "name": "clientSecret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientDiscoveryId": {
+ "name": "clientDiscoveryId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "skipConsent": {
+ "name": "skipConsent",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enableEndSession": {
+ "name": "enableEndSession",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subjectType": {
+ "name": "subjectType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientCredentialsScopes": {
+ "name": "clientCredentialsScopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "uri": {
+ "name": "uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contacts": {
+ "name": "contacts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tos": {
+ "name": "tos",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "policy": {
+ "name": "policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "softwareId": {
+ "name": "softwareId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "softwareVersion": {
+ "name": "softwareVersion",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "softwareStatement": {
+ "name": "softwareStatement",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redirectUris": {
+ "name": "redirectUris",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "postLogoutRedirectUris": {
+ "name": "postLogoutRedirectUris",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "backchannelLogoutUri": {
+ "name": "backchannelLogoutUri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "backchannelLogoutSessionRequired": {
+ "name": "backchannelLogoutSessionRequired",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tokenEndpointAuthMethod": {
+ "name": "tokenEndpointAuthMethod",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "applicationType": {
+ "name": "applicationType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "jwks": {
+ "name": "jwks",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "jwksUri": {
+ "name": "jwksUri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "grantTypes": {
+ "name": "grantTypes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "responseTypes": {
+ "name": "responseTypes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requirePKCE": {
+ "name": "requirePKCE",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dpopBoundAccessTokens": {
+ "name": "dpopBoundAccessTokens",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "oauthClient_userId_idx": {
+ "name": "oauthClient_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthClient_userId_user_id_fk": {
+ "name": "oauthClient_userId_user_id_fk",
+ "tableFrom": "oauthClient",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthClient_clientId_unique": {
+ "name": "oauthClient_clientId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "clientId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthClientAssertion": {
+ "name": "oauthClientAssertion",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthClientResource": {
+ "name": "oauthClientResource",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resourceId": {
+ "name": "resourceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "oauthClientResource_clientId_resourceId_uidx": {
+ "name": "oauthClientResource_clientId_resourceId_uidx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resourceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthClientResource_clientId_idx": {
+ "name": "oauthClientResource_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthClientResource_resourceId_idx": {
+ "name": "oauthClientResource_resourceId_idx",
+ "columns": [
+ {
+ "expression": "resourceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthClientResource_clientId_oauthClient_clientId_fk": {
+ "name": "oauthClientResource_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthClientResource",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthClientResource_resourceId_oauthResource_identifier_fk": {
+ "name": "oauthClientResource_resourceId_oauthResource_identifier_fk",
+ "tableFrom": "oauthClientResource",
+ "tableTo": "oauthResource",
+ "columnsFrom": [
+ "resourceId"
+ ],
+ "columnsTo": [
+ "identifier"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthConsent": {
+ "name": "oauthConsent",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consentGiven": {
+ "name": "consentGiven",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthConsent_clientId_oauthApplication_clientId_fk": {
+ "name": "oauthConsent_clientId_oauthApplication_clientId_fk",
+ "tableFrom": "oauthConsent",
+ "tableTo": "oauthApplication",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthConsent_userId_user_id_fk": {
+ "name": "oauthConsent_userId_user_id_fk",
+ "tableFrom": "oauthConsent",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthConsentV2": {
+ "name": "oauthConsentV2",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedUserInfoClaims": {
+ "name": "requestedUserInfoClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "oauthConsentV2_clientId_idx": {
+ "name": "oauthConsentV2_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthConsentV2_userId_idx": {
+ "name": "oauthConsentV2_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthConsentV2_clientId_oauthClient_clientId_fk": {
+ "name": "oauthConsentV2_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthConsentV2",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthConsentV2_userId_user_id_fk": {
+ "name": "oauthConsentV2_userId_user_id_fk",
+ "tableFrom": "oauthConsentV2",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthRefreshToken": {
+ "name": "oauthRefreshToken",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sessionId": {
+ "name": "sessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authorizationCodeId": {
+ "name": "authorizationCodeId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedUserInfoClaims": {
+ "name": "requestedUserInfoClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked": {
+ "name": "revoked",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rotatedAt": {
+ "name": "rotatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rotationReplayResponse": {
+ "name": "rotationReplayResponse",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rotationReplayExpiresAt": {
+ "name": "rotationReplayExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authTime": {
+ "name": "authTime",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "confirmation": {
+ "name": "confirmation",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "oauthRefreshToken_clientId_idx": {
+ "name": "oauthRefreshToken_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthRefreshToken_sessionId_idx": {
+ "name": "oauthRefreshToken_sessionId_idx",
+ "columns": [
+ {
+ "expression": "sessionId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthRefreshToken_userId_idx": {
+ "name": "oauthRefreshToken_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthRefreshToken_authorizationCodeId_idx": {
+ "name": "oauthRefreshToken_authorizationCodeId_idx",
+ "columns": [
+ {
+ "expression": "authorizationCodeId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthRefreshToken_clientId_oauthClient_clientId_fk": {
+ "name": "oauthRefreshToken_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthRefreshToken",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthRefreshToken_sessionId_session_id_fk": {
+ "name": "oauthRefreshToken_sessionId_session_id_fk",
+ "tableFrom": "oauthRefreshToken",
+ "tableTo": "session",
+ "columnsFrom": [
+ "sessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "oauthRefreshToken_userId_user_id_fk": {
+ "name": "oauthRefreshToken_userId_user_id_fk",
+ "tableFrom": "oauthRefreshToken",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthRefreshToken_token_unique": {
+ "name": "oauthRefreshToken_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthResource": {
+ "name": "oauthResource",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessTokenTtl": {
+ "name": "accessTokenTtl",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshTokenTtl": {
+ "name": "refreshTokenTtl",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "signingAlgorithm": {
+ "name": "signingAlgorithm",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "signingKeyId": {
+ "name": "signingKeyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "allowedScopes": {
+ "name": "allowedScopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "customClaims": {
+ "name": "customClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dpopBoundAccessTokensRequired": {
+ "name": "dpopBoundAccessTokensRequired",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "policyVersion": {
+ "name": "policyVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 1
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthResource_identifier_unique": {
+ "name": "oauthResource_identifier_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "identifier"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.organization": {
+ "name": "organization",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "logo": {
+ "name": "logo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthlyEventCount": {
+ "name": "monthlyEventCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "overMonthlyLimit": {
+ "name": "overMonthlyLimit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "approachingLimitNotifiedPeriodStart": {
+ "name": "approachingLimitNotifiedPeriodStart",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "planOverride": {
+ "name": "planOverride",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "custom_plan": {
+ "name": "custom_plan",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "organization_slug_unique": {
+ "name": "organization_slug_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "slug"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.segments": {
+ "name": "segments",
+ "schema": "",
+ "columns": {
+ "segment_id": {
+ "name": "segment_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "filters": {
+ "name": "filters",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "is_public": {
+ "name": "is_public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'segment'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "segments_organization_idx": {
+ "name": "segments_organization_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "segments_site_idx": {
+ "name": "segments_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "segments_organization_id_organization_id_fk": {
+ "name": "segments_organization_id_organization_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "segments_site_id_sites_site_id_fk": {
+ "name": "segments_site_id_sites_site_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "segments_user_id_user_id_fk": {
+ "name": "segments_user_id_user_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ipAddress": {
+ "name": "ipAddress",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userAgent": {
+ "name": "userAgent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "impersonatedBy": {
+ "name": "impersonatedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "activeOrganizationId": {
+ "name": "activeOrganizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "activeTeamId": {
+ "name": "activeTeamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_userId_user_id_fk": {
+ "name": "session_userId_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.site_transfers": {
+ "name": "site_transfers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_organization_id": {
+ "name": "source_organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "recipient_email": {
+ "name": "recipient_email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "site_transfers_site_id_sites_site_id_fk": {
+ "name": "site_transfers_site_id_sites_site_id_fk",
+ "tableFrom": "site_transfers",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "site_transfers_source_organization_id_organization_id_fk": {
+ "name": "site_transfers_source_organization_id_organization_id_fk",
+ "tableFrom": "site_transfers",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "source_organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "site_transfers_created_by_user_id_fk": {
+ "name": "site_transfers_created_by_user_id_fk",
+ "tableFrom": "site_transfers",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "site_transfers_site_unique": {
+ "name": "site_transfers_site_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sites": {
+ "name": "sites",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "domain": {
+ "name": "domain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "embed_enabled": {
+ "name": "embed_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "saltUserIds": {
+ "name": "saltUserIds",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "blockBots": {
+ "name": "blockBots",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "first_party_proxy": {
+ "name": "first_party_proxy",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "excluded_ips": {
+ "name": "excluded_ips",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_countries": {
+ "name": "excluded_countries",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_paths": {
+ "name": "excluded_paths",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_hostnames": {
+ "name": "excluded_hostnames",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_user_agents": {
+ "name": "excluded_user_agents",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_asns": {
+ "name": "excluded_asns",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_query_params": {
+ "name": "excluded_query_params",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "sessionReplay": {
+ "name": "sessionReplay",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "webVitals": {
+ "name": "webVitals",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackErrors": {
+ "name": "trackErrors",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackOutbound": {
+ "name": "trackOutbound",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackUrlParams": {
+ "name": "trackUrlParams",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackUrlFragments": {
+ "name": "trackUrlFragments",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackInitialPageView": {
+ "name": "trackInitialPageView",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackSpaNavigation": {
+ "name": "trackSpaNavigation",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackIp": {
+ "name": "trackIp",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackButtonClicks": {
+ "name": "trackButtonClicks",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackCopy": {
+ "name": "trackCopy",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackFormInteractions": {
+ "name": "trackFormInteractions",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "api_key": {
+ "name": "api_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "private_link_key": {
+ "name": "private_link_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "detected_platform": {
+ "name": "detected_platform",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claim_expires_at": {
+ "name": "claim_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "sites_id_idx": {
+ "name": "sites_id_idx",
+ "columns": [
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "sites_created_by_user_id_fk": {
+ "name": "sites_created_by_user_id_fk",
+ "tableFrom": "sites",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sites_organization_id_organization_id_fk": {
+ "name": "sites_organization_id_organization_id_fk",
+ "tableFrom": "sites",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "sites_type_check": {
+ "name": "sites_type_check",
+ "value": "\"sites\".\"type\" IS NULL OR \"sites\".\"type\" IN ('web', 'mobile')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.team": {
+ "name": "team",
+ "schema": "",
+ "columns": {
+ "memberCount": {
+ "name": "memberCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "team_organizationId_organization_id_fk": {
+ "name": "team_organizationId_organization_id_fk",
+ "tableFrom": "team",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.teamMember": {
+ "name": "teamMember",
+ "schema": "",
+ "columns": {
+ "membershipKey": {
+ "name": "membershipKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "teamId": {
+ "name": "teamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "teamMember_teamId_team_id_fk": {
+ "name": "teamMember_teamId_team_id_fk",
+ "tableFrom": "teamMember",
+ "tableTo": "team",
+ "columnsFrom": [
+ "teamId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "teamMember_userId_user_id_fk": {
+ "name": "teamMember_userId_user_id_fk",
+ "tableFrom": "teamMember",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "teamMember_membershipKey_unique": {
+ "name": "teamMember_membershipKey_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "membershipKey"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.team_site_access": {
+ "name": "team_site_access",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "team_site_access_team_idx": {
+ "name": "team_site_access_team_idx",
+ "columns": [
+ {
+ "expression": "team_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "team_site_access_site_idx": {
+ "name": "team_site_access_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "team_site_access_team_id_team_id_fk": {
+ "name": "team_site_access_team_id_team_id_fk",
+ "tableFrom": "team_site_access",
+ "tableTo": "team",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "team_site_access_site_id_sites_site_id_fk": {
+ "name": "team_site_access_site_id_sites_site_id_fk",
+ "tableFrom": "team_site_access",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "team_site_access_unique": {
+ "name": "team_site_access_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "team_id",
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.telemetry": {
+ "name": "telemetry",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "instance_id": {
+ "name": "instance_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "version": {
+ "name": "version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "table_counts": {
+ "name": "table_counts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clickhouse_size_gb": {
+ "name": "clickhouse_size_gb",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "username": {
+ "name": "username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user'"
+ },
+ "displayUsername": {
+ "name": "displayUsername",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banned": {
+ "name": "banned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banReason": {
+ "name": "banReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banExpires": {
+ "name": "banExpires",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "overMonthlyLimit": {
+ "name": "overMonthlyLimit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "monthlyEventCount": {
+ "name": "monthlyEventCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "sendAutoEmailReports": {
+ "name": "sendAutoEmailReports",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "scheduled_tip_email_ids": {
+ "name": "scheduled_tip_email_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_username_unique": {
+ "name": "user_username_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "username"
+ ]
+ },
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_aliases": {
+ "name": "user_aliases",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "anonymous_id": {
+ "name": "anonymous_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_aliases_user_idx": {
+ "name": "user_aliases_user_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_aliases_anon_idx": {
+ "name": "user_aliases_anon_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "anonymous_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_aliases_site_id_sites_site_id_fk": {
+ "name": "user_aliases_site_id_sites_site_id_fk",
+ "tableFrom": "user_aliases",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_aliases_site_anon_unique": {
+ "name": "user_aliases_site_anon_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "anonymous_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_profiles": {
+ "name": "user_profiles",
+ "schema": "",
+ "columns": {
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "traits": {
+ "name": "traits",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_profiles_site_idx": {
+ "name": "user_profiles_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_profiles_site_id_sites_site_id_fk": {
+ "name": "user_profiles_site_id_sites_site_id_fk",
+ "tableFrom": "user_profiles",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "user_profiles_site_id_user_id_pk": {
+ "name": "user_profiles_site_id_user_id_pk",
+ "columns": [
+ "site_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {
+ "public.import_platform_enum": {
+ "name": "import_platform_enum",
+ "schema": "public",
+ "values": [
+ "umami",
+ "simple_analytics",
+ "plausible"
+ ]
+ }
+ },
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json
index 6304c8f2f..2acd94657 100644
--- a/server/drizzle/meta/_journal.json
+++ b/server/drizzle/meta/_journal.json
@@ -169,6 +169,13 @@
"when": 1791346537258,
"tag": "0023_track_url_fragments",
"breakpoints": true
+ },
+ {
+ "idx": 24,
+ "version": "7",
+ "when": 1791523545363,
+ "tag": "0024_sites_id_index",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/server/src/api/admin/collectTelemetry.ts b/server/src/api/admin/collectTelemetry.ts
index 2278b0c88..004b55f26 100644
--- a/server/src/api/admin/collectTelemetry.ts
+++ b/server/src/api/admin/collectTelemetry.ts
@@ -1,31 +1,32 @@
import { FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
import { IS_CLOUD } from "../../lib/const.js";
import { db } from "../../db/postgres/postgres.js";
import { telemetry } from "../../db/postgres/schema.js";
-export async function collectTelemetry(
- request: FastifyRequest<{
- Body: {
- instanceId: string;
- version: string;
- tableCounts: Record<string, number>;
- clickhouseSizeGb: number;
- };
- }>,
- reply: FastifyReply
-) {
+// The endpoint is public, so bound what an anonymous caller can store.
+const telemetryBodySchema = z.object({
+ instanceId: z.string().min(1).max(128),
+ version: z.string().min(1).max(64),
+ tableCounts: z
+ .record(z.string().max(128), z.number().nonnegative())
+ .refine(counts => Object.keys(counts).length <= 50, { message: "Too many tables" }),
+ clickhouseSizeGb: z.number().nonnegative(),
+});
+
+export async function collectTelemetry(request: FastifyRequest, reply: FastifyReply) {
// Only allow telemetry collection on cloud instances
if (!IS_CLOUD) {
return reply.status(403).send({ error: "Telemetry collection is only available on cloud instances" });
}
- try {
- const { instanceId, version, tableCounts, clickhouseSizeGb } = request.body;
+ const parsed = telemetryBodySchema.safeParse(request.body);
+ if (!parsed.success) {
+ return reply.status(400).send({ error: "Invalid telemetry payload" });
+ }
- // Validate required fields
- if (!instanceId || !version || !tableCounts || clickhouseSizeGb === undefined) {
- return reply.status(400).send({ error: "Missing required fields" });
- }
+ try {
+ const { instanceId, version, tableCounts, clickhouseSizeGb } = parsed.data;
// Insert telemetry data
await db.insert(telemetry).values({
diff --git a/server/src/api/analytics/utils/getFilterStatement.test.ts b/server/src/api/analytics/utils/getFilterStatement.test.ts
index f60fe0feb..0d24d73e4 100644
--- a/server/src/api/analytics/utils/getFilterStatement.test.ts
+++ b/server/src/api/analytics/utils/getFilterStatement.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { getFilterStatement, getSqlParam } from "./getFilterStatement.js";
+import { filterParamError, getFilterStatement, getSqlParam } from "./getFilterStatement.js";
import { FilterParameter } from "../types.js";
describe("getSqlParam", () => {
@@ -678,3 +678,29 @@ describe("getFilterStatement", () => {
});
});
});
+
+describe("filterParamError", () => {
+ it("accepts absent and valid filters", () => {
+ expect(filterParamError(undefined)).toBeNull();
+ expect(filterParamError("")).toBeNull();
+ expect(filterParamError(JSON.stringify([{ parameter: "pathname", type: "equals", value: ["/"] }]))).toBeNull();
+ });
+
+ it("explains malformed JSON, unknown parameters, bad regexes and non-numeric comparisons", () => {
+ expect(filterParamError("not json")).toBe("Invalid JSON format");
+ expect(filterParamError(JSON.stringify([{ parameter: "nope", type: "equals", value: ["x"] }]))).toMatch(
+ /0\.parameter/
+ );
+ expect(
+ filterParamError(JSON.stringify([{ parameter: "pathname", type: "regex", value: ["[invalid"] }]))
+ ).toBeTruthy();
+ expect(filterParamError(JSON.stringify([{ parameter: "pathname", type: "greater_than", value: ["abc"] }]))).toMatch(
+ /Invalid numeric value/
+ );
+ expect(filterParamError(["array"])).toBe("filters must be a JSON array");
+ expect(filterParamError(JSON.stringify([{ parameter: "pathname", type: "equals", value: [] }]))).toMatch(
+ /needs at least one value/
+ );
+ expect(filterParamError(JSON.stringify([{ parameter: "pathname", type: "is_null", value: [] }]))).toBeNull();
+ });
+});
diff --git a/server/src/api/analytics/utils/getFilterStatement.ts b/server/src/api/analytics/utils/getFilterStatement.ts
index 776b16666..80bcb4226 100644
--- a/server/src/api/analytics/utils/getFilterStatement.ts
+++ b/server/src/api/analytics/utils/getFilterStatement.ts
@@ -1,4 +1,5 @@
import SqlString from "sqlstring";
+import { ZodError } from "zod";
import { filterParamSchema, validateFilters } from "./query-validation.js";
import { SESSION_CHANNEL_AGG } from "./sessionAttribution.js";
import { FilterParameter, FilterType } from "../types.js";
@@ -195,6 +196,38 @@ export const getSqlParam = (parameter: FilterParameter) => {
return filterParamSchema.parse(parameter);
};
+/**
+ * Returns why a request's `filters` param can't be used, or null when it is
+ * valid or absent. Builds the statement once so regex and numeric checks run
+ * too: handlers throw on the same input, which surfaced as a 500.
+ */
+export function filterParamError(filters: unknown): string | null {
+ if (filters === undefined || filters === "") {
+ return null;
+ }
+ if (typeof filters !== "string") {
+ return "filters must be a JSON array";
+ }
+ try {
+ // An empty value list builds `AND ()`, which ClickHouse rejects.
+ const empty = validateFilters(filters).find(
+ filter => filter.type !== "is_null" && filter.type !== "is_not_null" && filter.value.length === 0
+ );
+ if (empty) {
+ return `filter on "${empty.parameter}" needs at least one value`;
+ }
+ getFilterStatement(filters);
+ return null;
+ } catch (error) {
+ if (error instanceof ZodError) {
+ return error.issues
+ .map(issue => (issue.path.length ? `${issue.path.join(".")}: ` : "") + issue.message)
+ .join("; ");
+ }
+ return error instanceof Error ? error.message : "Invalid filters";
+ }
+}
+
export function getFilterStatement(
filters: string,
siteId?: number,
diff --git a/server/src/api/routes.ts b/server/src/api/routes.ts
index 21760c86f..a37834de9 100644
--- a/server/src/api/routes.ts
+++ b/server/src/api/routes.ts
@@ -188,6 +188,7 @@ import {
updateAccountSettings,
} from "./user/index.js";
import { createDashboardCache } from "./analytics/utils/dashboardCache.js";
+import { filterParamError } from "./analytics/utils/getFilterStatement.js";
import { validateHttpTimeParams } from "./analytics/utils/query-validation.js";
import { handleAppSumoWebhook, activateAppSumoLicense } from "./as/index.js";
import { unclaimedSiteRouteOptions } from "./sites/createUnclaimedSite.js";
@@ -223,6 +224,15 @@ const validateTimeParams = async (request: FastifyRequest, reply: FastifyReply)
}
};
+// Reject a malformed `filters` param (bad JSON, unknown parameter, invalid
+// regex) up front; handlers throw on it, which answered 500.
+const validateFilterParam = async (request: FastifyRequest, reply: FastifyReply) => {
+ const error = filterParamError((request.query as Record<string, unknown> | undefined)?.filters);
+ if (error) {
+ return reply.status(400).send({ error: `Invalid filters: ${error}` });
+ }
+};
+
// Route access. Every /api route declares who may call it (config.access) and
// the onRoute check below refuses to boot a route that doesn't, so a new
// endpoint cannot ship without an explicit decision.
@@ -241,11 +251,15 @@ const validateTimeParams = async (request: FastifyRequest, reply: FastifyReply)
// expandSegmentParam turns a `segment_id` query param into `filters` after the
// access guard has run, so every analytics endpoint accepts a saved segment
// with no per-endpoint change. It is a no-op when the param is absent.
-const site = (permission: Permission, options: { allowPublic?: boolean; validateTime?: boolean } = {}) => ({
+const site = (
+ permission: Permission,
+ options: { allowPublic?: boolean; validateTime?: boolean; validateFilters?: boolean } = {}
+) => ({
preHandler: [
resolveSiteId,
requireSitePermission(permission, { allowPublic: options.allowPublic }),
...(options.validateTime === false ? [] : [validateTimeParams]),
+ ...(options.validateFilters === false ? [] : [validateFilterParam]),
expandSegmentParam,
] as any,
config: { access: { level: "site", permission, allowPublic: !!options.allowPublic } as RouteAccess },
@@ -288,7 +302,9 @@ const publicFunnelsRead = publicSite("funnels:read");
const publicGoalsRead = publicSite("goals:read");
const publicSitesRead = publicSite("sites:read");
const publicReplayRead = publicSite("replay:read");
-const publicGscRead = publicSite("gsc:read");
+// Search Console's `filters` param is its own {dimension, operator, expression}
+// shape, validated by the handler.
+const publicGscRead = site("gsc:read", { allowPublic: true, validateFilters: false });
// Annotations validate their own optional start/end bounds (either may stand
// alone), so the shared time validator is left off this chain.
const publicAnnotationsRead = site("annotations:read", { allowPublic: true, validateTime: false });
@@ -569,7 +585,14 @@ async function stripeAdminRoutes(fastify: FastifyInstance) {
fastify.patch("/admin/organizations/:organizationId/members/:memberId", systemAdmin, updateAdminOrganizationMember);
fastify.delete("/admin/organizations/:organizationId/members/:memberId", systemAdmin, deleteAdminOrganizationMember);
fastify.get("/admin/service-event-count", systemAdmin, getAdminServiceEventCount);
- fastify.post("/admin/telemetry", publicRoute, collectTelemetry); // Public - telemetry collection
+ fastify.post(
+ "/admin/telemetry",
+ {
+ bodyLimit: 16 * 1024,
+ config: { access: "public" as RouteAccess, rateLimit: { max: 10, timeWindow: "1 hour" } },
+ },
+ collectTelemetry
+ ); // Public - telemetry collection
// STRIPE & ADMIN
if (IS_CLOUD) {
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index 910f93070..67792e5cb 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -112,7 +112,12 @@ export const sites = pgTable(
// privateLinkKey until it is claimed; the cleanup cron deletes it after this.
claimExpiresAt: timestamp("claim_expires_at", { mode: "string" }),
},
- table => [check("sites_type_check", sql`${table.type} IS NULL OR ${table.type} IN ('web', 'mobile')`)]
+ table => [
+ check("sites_type_check", sql`${table.type} IS NULL OR ${table.type} IN ('web', 'mobile')`),
+ // Tracking and the route guards resolve a Site by its text id on every
+ // cache miss.
+ index("sites_id_idx").on(table.id),
+ ]
);
// Active sessions table.
diff --git a/server/src/index.ts b/server/src/index.ts
index 703b4342b..760e1b547 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -19,7 +19,9 @@ import { createCorsOptionsDelegate, createRejectUntrustedOriginHook } from "./li
import { IS_CLOUD } from "./lib/const.js";
import { logger } from "./lib/logger/logger.js";
import { registerRequestLogging } from "./lib/logger/requestLogging.js";
+import { botEventQueue, botObservationQueue } from "./services/tracker/botBlocking/botEventQueue.js";
import { identityBackfillQueue } from "./services/tracker/identityBackfillQueue.js";
+import { pageviewQueue } from "./services/tracker/pageviewQueue.js";
import { lifecycleEmailService } from "./services/lifecycleEmails/lifecycleEmailService.js";
import { telemetryService } from "./services/telemetryService.js";
import { handleIdentify } from "./services/tracker/identifyService.js";
@@ -205,8 +207,10 @@ const shutdown = async (signal: string) => {
await server.close();
server.log.info("Server closed");
- // Identity backfills are buffered for several minutes to keep mutation
+ // Flush events still buffered for the next batch insert, then the
+ // identity backfills, which are held for several minutes to keep mutation
// submissions rare; without this, a deploy drops whatever is still pending.
+ await Promise.all([pageviewQueue.drain(), botEventQueue.drain(), botObservationQueue.drain()]);
await identityBackfillQueue.drainCompletely();
// Clear the timeout since we're done
diff --git a/server/src/lib/auth.ts b/server/src/lib/auth.ts
index 54777a364..fe84581d1 100644
--- a/server/src/lib/auth.ts
+++ b/server/src/lib/auth.ts
@@ -265,6 +265,13 @@ const pluginList = [
: []),
];
+// Duck-typed: the api-key plugin can resolve its own copy of APIError.
+function isApiErrorLike(value: unknown): boolean {
+ return (
+ typeof value === "object" && value !== null && typeof (value as { statusCode?: unknown }).statusCode === "number"
+ );
+}
+
export const auth = betterAuth({
basePath: "/api/auth",
baseURL: getAuthBaseUrl(),
@@ -273,6 +280,12 @@ export const auth = betterAuth({
log: (level, message, ...args) => {
// Route better-auth's internal logs (e.g. API key rate-limit errors)
// through the project's pino logger instead of console.
+ // better-auth logs every unknown or expired API key at error level; a
+ // caller presenting a bad credential isn't a server fault (#1095).
+ if (message.startsWith("Failed to validate API key") && isApiErrorLike(args[0])) {
+ authLogger.debug({ args }, message);
+ return;
+ }
authLogger[level]({ args }, message);
},
},
@@ -357,7 +370,8 @@ export const auth = betterAuth({
create: {
after: async u => {
authLogger.info({ userId: u.id }, "User created");
- const users = await db.select().from(schema.user).orderBy(asc(user.createdAt));
+ // Two rows are enough to tell whether this is the first user.
+ const users = await db.select({ id: user.id }).from(user).orderBy(asc(user.createdAt)).limit(2);
// If this is the first user, make them an admin
if (users.length === 1) {
diff --git a/server/src/lib/bearerAuth.test.ts b/server/src/lib/bearerAuth.test.ts
index 0b34ce0e5..c5e9b28c3 100644
--- a/server/src/lib/bearerAuth.test.ts
+++ b/server/src/lib/bearerAuth.test.ts
@@ -66,6 +66,16 @@ describe("resolveBearerIdentity", () => {
expect(identity).toEqual({ status: "valid", userId: "u2", statements: { analytics: ["read"] } });
});
+ it("sends a JWT access token straight to the OAuth lookup, skipping the API-key check", async () => {
+ const verifyApiKey = vi.fn(async () => ({ valid: false, error: { code: "KEY_NOT_FOUND" } }));
+ const identity = await resolveBearerIdentity(
+ "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1MiJ9.c2ln",
+ deps({ verifyApiKey, getOAuthSession: async () => ({ userId: "u2", accessTokenExpiresAt: future(), scopes: "openid" }) })
+ );
+ expect(verifyApiKey).not.toHaveBeenCalled();
+ expect(identity.status).toBe("valid");
+ });
+
it("rejects an expired OAuth token", async () => {
const identity = await resolveBearerIdentity(
"t",
diff --git a/server/src/lib/bearerAuth.ts b/server/src/lib/bearerAuth.ts
index 7195a07c7..e7ee31d5b 100644
--- a/server/src/lib/bearerAuth.ts
+++ b/server/src/lib/bearerAuth.ts
@@ -110,13 +110,21 @@ async function applyRateLimit(identity: BearerIdentity, deps: BearerResolverDeps
return { ...identity, rateLimit: decision };
}
+// API keys are a prefix plus letters (prefixes allow only [A-Za-z0-9_-]), so a
+// dotted token is a JWT access token and can skip the API-key lookup.
+function looksLikeJwt(token: string): boolean {
+ return token.split(".").length === 3;
+}
+
export async function resolveBearerIdentity(token: string, deps: BearerResolverDeps): Promise<BearerIdentity> {
let verifyError = false;
let verification: ApiKeyVerification | null = null;
- try {
- verification = await deps.verifyApiKey(token);
- } catch {
- verifyError = true;
+ if (!looksLikeJwt(token)) {
+ try {
+ verification = await deps.verifyApiKey(token);
+ } catch {
+ verifyError = true;
+ }
}
if (verification?.valid && verification.key?.referenceId) {
diff --git a/server/src/services/sites/siteConfigurationLifecycle.test.ts b/server/src/services/sites/siteConfigurationLifecycle.test.ts
index 809894dc1..8c7e623e9 100644
--- a/server/src/services/sites/siteConfigurationLifecycle.test.ts
+++ b/server/src/services/sites/siteConfigurationLifecycle.test.ts
@@ -35,6 +35,17 @@ vi.mock("../../db/postgres/postgres.js", () => ({
state.deletes += 1;
},
})),
+ // Rolls back the counted deletes when the callback throws.
+ transaction: vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => {
+ const { db } = await import("../../db/postgres/postgres.js");
+ const deletesBefore = state.deletes;
+ try {
+ return await fn(db);
+ } catch (error) {
+ state.deletes = deletesBefore;
+ throw error;
+ }
+ }),
},
}));
@@ -109,15 +120,24 @@ describe("siteConfigurationLifecycle", () => {
expect(mocks.invalidate).toHaveBeenCalledWith(state.site);
});
- it("deletes replay data before the Site row and then invalidates the Site", async () => {
+ it("deletes the import rows and the Site row, wipes replay data, then invalidates the Site", async () => {
await siteConfigurationLifecycle.delete(1);
+ expect(state.deletes).toBe(2);
expect(mocks.clickhouseCommand).toHaveBeenCalledTimes(2);
- expect(state.deletes).toBe(1);
expect(mocks.invalidate).toHaveBeenCalledWith(state.site);
});
- it("does not report deletion when replay cleanup fails", async () => {
+ it("keeps replay data when the Postgres delete fails", async () => {
+ state.deleteError = new Error("foreign key violation");
+
+ await expect(siteConfigurationLifecycle.delete(1)).rejects.toThrow("foreign key violation");
+
+ expect(mocks.clickhouseCommand).not.toHaveBeenCalled();
+ expect(mocks.invalidate).not.toHaveBeenCalled();
+ });
+
+ it("rolls the Site back when replay cleanup fails", async () => {
mocks.clickhouseCommand.mockRejectedValueOnce(new Error("clickhouse unavailable"));
await expect(siteConfigurationLifecycle.delete(1)).rejects.toThrow("clickhouse unavailable");
diff --git a/server/src/services/sites/siteConfigurationLifecycle.ts b/server/src/services/sites/siteConfigurationLifecycle.ts
index c1666fa73..46e972ec3 100644
--- a/server/src/services/sites/siteConfigurationLifecycle.ts
+++ b/server/src/services/sites/siteConfigurationLifecycle.ts
@@ -3,7 +3,7 @@ import { and, eq, gt, isNull, lt, sql } from "drizzle-orm";
import { getSubscriptionInner } from "../../api/stripe/getSubscription.js";
import { clickhouse } from "../../db/clickhouse/clickhouse.js";
import { db } from "../../db/postgres/postgres.js";
-import { sites } from "../../db/postgres/schema.js";
+import { importStatus, sites } from "../../db/postgres/schema.js";
import { IS_CLOUD } from "../../lib/const.js";
import { validateIPPattern } from "../../lib/ipUtils.js";
import { detectPlatform } from "../lifecycleEmails/platformDetect.js";
@@ -533,8 +533,9 @@ class SiteConfigurationLifecycle {
.for("update");
if (!site) return false;
- await this.deleteReplayData(siteId);
+ await tx.delete(importStatus).where(eq(importStatus.siteId, siteId));
await tx.delete(sites).where(eq(sites.siteId, siteId));
+ await this.deleteReplayData(siteId);
siteConfig.invalidate(site);
return true;
});
@@ -555,8 +556,15 @@ class SiteConfigurationLifecycle {
async delete(siteId: number): Promise<void> {
const site = await this.findSite(siteId);
- await this.deleteReplayData(siteId);
- await db.delete(sites).where(eq(sites.siteId, siteId));
+ // Delete the Postgres rows first so a constraint failure can't leave the
+ // Site in place with its replays already wiped. import_status is the one
+ // table whose foreign key to sites doesn't cascade. Replay cleanup runs
+ // inside the transaction, so a ClickHouse failure rolls the Site back.
+ await db.transaction(async tx => {
+ await tx.delete(importStatus).where(eq(importStatus.siteId, siteId));
+ await tx.delete(sites).where(eq(sites.siteId, siteId));
+ await this.deleteReplayData(siteId);
+ });
siteConfig.invalidate(site);
}
}
diff --git a/server/src/services/sites/unclaimedSites.test.ts b/server/src/services/sites/unclaimedSites.test.ts
index 137eeb889..df22046b6 100644
--- a/server/src/services/sites/unclaimedSites.test.ts
+++ b/server/src/services/sites/unclaimedSites.test.ts
@@ -77,6 +77,12 @@ CREATE TABLE sites (
"detected_platform" text,
"claim_expires_at" timestamp
);
+-- The real foreign key has no ON DELETE CASCADE.
+CREATE TABLE import_status (
+ "import_id" text PRIMARY KEY,
+ "site_id" integer NOT NULL REFERENCES sites(site_id),
+ "organization_id" text NOT NULL
+);
`);
});
afterAll(async () => {
@@ -86,7 +92,7 @@ beforeEach(async () => {
vi.clearAllMocks();
state.isCloud = false;
mocks.getSubscriptionInner.mockResolvedValue({ siteLimit: 1 });
- await (client as any).exec("TRUNCATE sites RESTART IDENTITY");
+ await (client as any).exec("TRUNCATE sites, import_status RESTART IDENTITY");
});
async function unclaimed() {
@@ -218,6 +224,14 @@ describe("cleanup", () => {
expect(await readSite(site.siteId)).toBeDefined();
expect(await cleanup.deleteExpiredSites()).toBe(1);
});
+ it("deletes a Site that has import history", async () => {
+ const site = await unclaimed();
+ await lifecycle.claim(claimInput(site));
+ await (client as any).query("INSERT INTO import_status VALUES ('imp_1', $1, 'org_1')", [site.siteId]);
+ await lifecycle.delete(site.siteId);
+ expect(await readSite(site.siteId)).toBeUndefined();
+ expect(mocks.clickhouseCommand).toHaveBeenCalledTimes(2);
+ });
it("does nothing when there are no expired sites", async () => {
expect(await cleanup.deleteExpiredSites()).toBe(0);
expect(mocks.clickhouseCommand).not.toHaveBeenCalled();
diff --git a/server/src/services/tracker/botBlocking/botEventQueue.ts b/server/src/services/tracker/botBlocking/botEventQueue.ts
index 2cbfd57f4..1eac72e88 100644
--- a/server/src/services/tracker/botBlocking/botEventQueue.ts
+++ b/server/src/services/tracker/botBlocking/botEventQueue.ts
@@ -32,6 +32,20 @@ class BotEventQueue {
this.queue.push(botEvent);
}
+ /**
+ * Flushes everything still buffered. Only for shutdown: process exit would
+ * otherwise drop up to a flush interval of events on every deploy.
+ */
+ async drain(): Promise<void> {
+ while (this.processing || this.queue.length > 0) {
+ if (this.processing) {
+ await new Promise(resolve => setTimeout(resolve, 50));
+ } else {
+ await this.processQueue();
+ }
+ }
+ }
+
private async processQueue() {
if (this.processing || this.queue.length === 0) return;
this.processing = true;
diff --git a/server/src/services/tracker/const.ts b/server/src/services/tracker/const.ts
index c8889c6d9..a8c5a491e 100644
--- a/server/src/services/tracker/const.ts
+++ b/server/src/services/tracker/const.ts
@@ -374,15 +374,7 @@ const aiChatSources = [
];
// AI chat mediums (utm_medium values)
-const aiChatMediums = [
- "ai",
- "ai-chat",
- "chatbot",
- "llm",
- "ai-assistant",
- "gen-ai",
- "ai-search",
-];
+const aiChatMediums = ["ai", "ai-chat", "chatbot", "llm", "ai-assistant", "gen-ai", "ai-search"];
// AI chat mobile app IDs
export const aiChatAppIds = [
@@ -1226,7 +1218,7 @@ function getDomainSourceType(source: string): string | null {
for (const domain of domains) {
const length = Math.max(
domainMatchLength(host, domain),
- countrylessHost ? domainMatchLength(countrylessHost, domain) : 0,
+ countrylessHost ? domainMatchLength(countrylessHost, domain) : 0
);
if (length > bestLength) {
bestType = type;
@@ -1291,6 +1283,24 @@ export function getMediumType(medium: string): string {
return "organic";
}
+// Run-together paid mediums that whole-word matching would otherwise miss.
+const compactPaidMediums = new Set([
+ "ecpc",
+ "googleads",
+ "bingads",
+ "fbads",
+ "facebookads",
+ "metaads",
+ "instagramads",
+ "linkedinads",
+ "tiktokads",
+ "socialads",
+ "searchads",
+ "displayads",
+ "bannerads",
+ "videoads",
+]);
+
// Helper function to check if traffic is paid
export function isPaidTraffic(medium: string, source: string): boolean {
const lowerMedium = medium.toLowerCase();
@@ -1323,5 +1333,18 @@ export function isPaidTraffic(medium: string, source: string): boolean {
"pinterest ads",
];
- return paidMediums.some(pm => lowerMedium.includes(pm)) || paidSources.some(ps => lowerSource.includes(ps));
+ // Match whole words and phrases, not substrings: "ad" is inside "readme" and
+ // "download", "sem" inside "seminar" (#1262). Run-together spellings that
+ // substring matching used to catch are listed explicitly.
+ const tokens = lowerMedium.split(/[^a-z0-9]+/).filter(Boolean);
+ const containsPhrase = (phrase: string) => {
+ const words = phrase.split(/[^a-z0-9]+/).filter(Boolean);
+ return tokens.some((_, start) => words.every((word, offset) => tokens[start + offset] === word));
+ };
+ const isPaidMedium =
+ lowerMedium.startsWith("paid") ||
+ tokens.some(token => compactPaidMediums.has(token)) ||
+ paidMediums.some(containsPhrase);
+
+ return isPaidMedium || paidSources.some(ps => lowerSource.includes(ps));
}
diff --git a/server/src/services/tracker/getChannel.test.ts b/server/src/services/tracker/getChannel.test.ts
index da707ff54..bd2b6a7c8 100644
--- a/server/src/services/tracker/getChannel.test.ts
+++ b/server/src/services/tracker/getChannel.test.ts
@@ -9,6 +9,24 @@ describe("getChannel - UTM parameter fallback", () => {
expect(getChannel("", "utm_campaign=custom_campaign")).toBe("Referral");
});
+ it("does not read paid intent into mediums that merely contain an ad keyword", () => {
+ for (const medium of ["readme", "download", "badge", "header", "lead_magnet", "alternatives", "leads"]) {
+ expect(getChannel("", `utm_source=github&utm_medium=${medium}`)).not.toMatch(/^Paid/);
+ }
+ expect(getChannel("", "utm_source=devconf&utm_medium=seminar")).toBe("Event");
+ });
+
+ it("still treats paid mediums as paid when they are whole words", () => {
+ expect(getChannel("", "utm_source=google&utm_medium=cpc")).toBe("Paid Search");
+ expect(getChannel("", "utm_source=newsletter_partner&utm_medium=display_ad")).toMatch(/^Paid/);
+ expect(getChannel("", "utm_source=facebook&utm_medium=paid_social")).toBe("Paid Social");
+ expect(getChannel("", "utm_source=facebook&utm_medium=paidsocial")).toBe("Paid Social");
+ expect(getChannel("", "utm_source=github&utm_medium=ads")).toMatch(/^Paid/);
+ expect(getChannel("", "utm_source=google&utm_medium=ecpc")).toBe("Paid Search");
+ expect(getChannel("", "utm_source=partner&utm_medium=rich-media-campaign")).toMatch(/^Paid/);
+ expect(getChannel("", "utm_source=facebook&utm_medium=facebookads")).toBe("Paid Social");
+ });
+
it("retains Direct classification when no referrer and no UTM parameters exist", () => {
expect(getChannel("", "")).toBe("Direct");
});
diff --git a/server/src/services/tracker/pageviewQueue.test.ts b/server/src/services/tracker/pageviewQueue.test.ts
index ce4b81806..6a60b02fd 100644
--- a/server/src/services/tracker/pageviewQueue.test.ts
+++ b/server/src/services/tracker/pageviewQueue.test.ts
@@ -69,6 +69,18 @@ describe("pageviewQueue", () => {
Settings.defaultZone = originalZone;
});
+ it("drain flushes everything buffered without waiting for the interval", async () => {
+ for (let i = 0; i < 5001; i++) {
+ await pageviewQueue.add(makePayload());
+ }
+
+ await pageviewQueue.drain();
+
+ expect(mocks.insert).toHaveBeenCalledTimes(2);
+ expect(mocks.insert.mock.calls[0][0].values).toHaveLength(5000);
+ expect(mocks.insert.mock.calls[1][0].values).toHaveLength(1);
+ });
+
it("stores the ASN, org, and datacenter classification for a recognized IP", async () => {
mocks.lookupAsn.mockReturnValue({ asn: 16509, organization: "AMAZON-02" });
mocks.isDatacenterAsn.mockReturnValue(true);
diff --git a/server/src/services/tracker/pageviewQueue.ts b/server/src/services/tracker/pageviewQueue.ts
index b2ed8b9a6..687745a1b 100644
--- a/server/src/services/tracker/pageviewQueue.ts
+++ b/server/src/services/tracker/pageviewQueue.ts
@@ -39,6 +39,20 @@ class PageviewQueue {
this.queue.push(pageview);
}
+ /**
+ * Flushes everything still buffered. Only for shutdown: process exit would
+ * otherwise drop up to a flush interval of events on every deploy.
+ */
+ async drain(): Promise<void> {
+ while (this.processing || this.queue.length > 0) {
+ if (this.processing) {
+ await new Promise(resolve => setTimeout(resolve, 50));
+ } else {
+ await this.processQueue();
+ }
+ }
+ }
+
private async processQueue() {
if (this.processing || this.queue.length === 0) return;
this.processing = true;