Merge branch 'session-recording' into dev

This commit is contained in:
Mike Cao committed 2026-02-25 02:32:07 -08:00
commit e73d827d21
35 files changed
+1104 -20

No files matched your search

@@ -116,6 +116,11 @@ export function TestConsolePage({ websiteId }: { websiteId: string }) {
src={`${process.env.basePath || ''}/script.js`}
data-cache="true"
/>
<Script
async
data-website-id={websiteId}
src={`${process.env.basePath || ''}/recorder.js`}
/>
<Panel>
<Grid columns="1fr 1fr 1fr" gap>
<Column gap>
@@ -0,0 +1,15 @@
import { DataGrid } from '@/components/common/DataGrid';
import { useReplaysQuery } from '@/components/hooks';
import { ReplaysTable } from './ReplaysTable';
export function ReplaysDataTable({ websiteId }: { websiteId: string }) {
const queryResult = useReplaysQuery(websiteId);
return (
<DataGrid query={queryResult} allowPaging allowSearch>
{({ data }) => {
return <ReplaysTable data={data} websiteId={websiteId} />;
}}
</DataGrid>
);
}
@@ -0,0 +1,16 @@
'use client';
import { Column } from '@umami/react-zen';
import { WebsiteControls } from '@/app/(main)/websites/[websiteId]/WebsiteControls';
import { Panel } from '@/components/common/Panel';
import { ReplaysDataTable } from './ReplaysDataTable';
export function ReplaysPage({ websiteId }: { websiteId: string }) {
return (
<Column gap="3">
<WebsiteControls websiteId={websiteId} />
<Panel>
<ReplaysDataTable websiteId={websiteId} />
</Panel>
</Column>
);
}
@@ -0,0 +1,66 @@
import { Button, DataColumn, DataTable, type DataTableProps, Icon } from '@umami/react-zen';
import { Play } from 'lucide-react';
import Link from 'next/link';
import { Avatar } from '@/components/common/Avatar';
import { DateDistance } from '@/components/common/DateDistance';
import { TypeIcon } from '@/components/common/TypeIcon';
import { useFormat, useMessages } from '@/components/hooks';
function formatDuration(ms: number) {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${minutes}:${secs.toString().padStart(2, '0')}`;
}
export function ReplaysTable({ websiteId, ...props }: DataTableProps & { websiteId: string }) {
const { formatMessage, labels } = useMessages();
const { formatValue } = useFormat();
return (
<DataTable {...props}>
<DataColumn id="id" label={formatMessage(labels.session)} width="100px">
{(row: any) => <Avatar seed={row.id} size={32} />}
</DataColumn>
<DataColumn id="duration" label={formatMessage(labels.duration)} width="100px">
{(row: any) => formatDuration(row.duration || 0)}
</DataColumn>
<DataColumn id="eventCount" label={formatMessage(labels.events)} width="80px" />
<DataColumn id="country" label={formatMessage(labels.country)}>
{(row: any) => (
<TypeIcon type="country" value={row.country}>
{formatValue(row.country, 'country')}
</TypeIcon>
)}
</DataColumn>
<DataColumn id="browser" label={formatMessage(labels.browser)}>
{(row: any) => (
<TypeIcon type="browser" value={row.browser}>
{formatValue(row.browser, 'browser')}
</TypeIcon>
)}
</DataColumn>
<DataColumn id="os" label={formatMessage(labels.os)}>
{(row: any) => (
<TypeIcon type="os" value={row.os}>
{formatValue(row.os, 'os')}
</TypeIcon>
)}
</DataColumn>
<DataColumn id="createdAt" label={formatMessage(labels.recordedAt)}>
{(row: any) => <DateDistance date={new Date(row.createdAt)} />}
</DataColumn>
<DataColumn id="play" label="" width="80px">
{(row: any) => (
<Link href={`/websites/${websiteId}/replays/${row.id}`}>
<Button variant="quiet">
<Icon>
<Play />
</Icon>
</Button>
</Link>
)}
</DataColumn>
</DataTable>
);
}
@@ -0,0 +1,41 @@
'use client';
import { Column, Row, Text } from '@umami/react-zen';
import { SessionInfo } from '@/app/(main)/websites/[websiteId]/sessions/SessionInfo';
import { Avatar } from '@/components/common/Avatar';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import { useMessages, useReplayQuery, useWebsiteSessionQuery } from '@/components/hooks';
import { ReplayPlayer } from './ReplayPlayer';
export function ReplayPlayback({ websiteId, sessionId }: { websiteId: string; sessionId: string }) {
const { data: replay, isLoading, error } = useReplayQuery(websiteId, sessionId);
const { data: session } = useWebsiteSessionQuery(websiteId, sessionId);
const { formatMessage, labels } = useMessages();
return (
<LoadingPanel
data={replay}
isLoading={isLoading}
error={error}
loadingIcon="spinner"
loadingPlacement="absolute"
>
{replay && (
<Column gap="6">
{session && (
<Row alignItems="center" gap="4">
<Avatar seed={sessionId} size={48} />
<Column>
<Text weight="bold">{formatMessage(labels.replay)}</Text>
<Text color="muted">
{replay.eventCount} {formatMessage(labels.events).toLowerCase()}
</Text>
</Column>
</Row>
)}
<ReplayPlayer events={replay.events} />
{session && <SessionInfo data={session} />}
</Column>
)}
</LoadingPanel>
);
}
@@ -0,0 +1,77 @@
'use client';
import { Column } from '@umami/react-zen';
import { useEffect, useRef, useState } from 'react';
import 'rrweb-player/dist/style.css';
export function ReplayPlayer({ events }: { events: any[] }) {
const containerRef = useRef<HTMLDivElement>(null);
const playerRef = useRef<any>(null);
const [loaded, setLoaded] = useState(false);
useEffect(() => {
if (!containerRef.current || !events?.length) return;
// Debug: log event info
const typeCounts: Record<number, number> = {};
events.forEach((e: any) => {
typeCounts[e.type] = (typeCounts[e.type] || 0) + 1;
});
const timestamps = events.map((e: any) => e.timestamp).filter(Boolean);
console.log('[ReplayPlayer] Events:', events.length, 'Types:', typeCounts);
console.log(
'[ReplayPlayer] Time range:',
timestamps.length
? `${Math.min(...timestamps)} - ${Math.max(...timestamps)} (${Math.max(...timestamps) - Math.min(...timestamps)}ms)`
: 'no timestamps',
);
console.log('[ReplayPlayer] First 3 events:', events.slice(0, 3));
// Dynamically import rrweb-player to avoid SSR issues
import('rrweb-player').then(mod => {
const RRWebPlayer = mod.default;
// Clear any previous player
if (containerRef.current) {
containerRef.current.innerHTML = '';
}
playerRef.current = new RRWebPlayer({
target: containerRef.current!,
props: {
events,
width: 1024,
height: 576,
autoPlay: false,
showController: true,
speedOption: [1, 2, 4, 8],
},
});
setLoaded(true);
});
return () => {
if (playerRef.current) {
playerRef.current.$destroy?.();
playerRef.current = null;
}
};
}, [events]);
return (
<Column alignItems="center">
<div
ref={containerRef}
style={{
minWidth: 1024,
minHeight: loaded ? undefined : 576,
maxWidth: '100%',
overflow: 'hidden',
borderRadius: '8px',
border: '1px solid var(--base300)',
background: 'var(--base75)',
}}
/>
</Column>
);
}
@@ -0,0 +1,16 @@
import type { Metadata } from 'next';
import { ReplayPlayback } from './ReplayPlayback';
export default async function ({
params,
}: {
params: Promise<{ websiteId: string; sessionId: string }>;
}) {
const { websiteId, sessionId } = await params;
return <ReplayPlayback websiteId={websiteId} sessionId={sessionId} />;
}
export const metadata: Metadata = {
title: 'Session Replay',
};
@@ -0,0 +1,12 @@
import type { Metadata } from 'next';
import { ReplaysPage } from './ReplaysPage';
export default async function ({ params }: { params: Promise<{ websiteId: string }> }) {
const { websiteId } = await params;
return <ReplaysPage websiteId={websiteId} />;
}
export const metadata: Metadata = {
title: 'Replays',
};
@@ -10,9 +10,10 @@ import {
TextField,
} from '@umami/react-zen';
import { X } from 'lucide-react';
import { ReplayPlayer } from '@/app/(main)/websites/[websiteId]/replays/[sessionId]/ReplayPlayer';
import { Avatar } from '@/components/common/Avatar';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import { useMessages, useWebsiteSessionQuery } from '@/components/hooks';
import { useMessages, useReplayQuery, useWebsiteSessionQuery } from '@/components/hooks';
import { SessionActivity } from './SessionActivity';
import { SessionData } from './SessionData';
import { SessionInfo } from './SessionInfo';
@@ -28,6 +29,7 @@ export function SessionProfile({
onClose?: () => void;
}) {
const { data, isLoading, error } = useWebsiteSessionQuery(websiteId, sessionId);
const { data: replay } = useReplayQuery(websiteId, sessionId);
const { t, labels } = useMessages();
return (
@@ -63,6 +65,7 @@ export function SessionProfile({
<TabList>
<Tab id="activity">{t(labels.activity)}</Tab>
<Tab id="properties">{t(labels.properties)}</Tab>
{replay?.events?.length > 0 && <Tab id="replay">{t(labels.replay)}</Tab>}
</TabList>
<TabPanel id="activity">
<SessionActivity
@@ -75,6 +78,11 @@ export function SessionProfile({
<TabPanel id="properties">
<SessionData sessionId={sessionId} websiteId={websiteId} />
</TabPanel>
{replay?.events?.length > 0 && (
<TabPanel id="replay">
<ReplayPlayer events={replay.events} />
</TabPanel>
)}
</Tabs>
</Column>
</Column>
@@ -0,0 +1,96 @@
import {
Column,
Form,
FormButtons,
FormField,
FormSubmitButton,
Label,
Switch,
TextField,
} from '@umami/react-zen';
import { useState } from 'react';
import { useMessages, useUpdateQuery, useWebsite } from '@/components/hooks';
interface ReplayConfig {
sampleRate?: number;
maskLevel?: string;
maxDuration?: number;
blockSelector?: string;
retentionDays?: number;
}
export function WebsiteReplaySettings({ websiteId }: { websiteId: string }) {
const website = useWebsite();
const { formatMessage, labels, messages } = useMessages();
const { mutateAsync, error, touch, toast } = useUpdateQuery(`/websites/${websiteId}`);
const [enabled, setEnabled] = useState(website?.replayEnabled ?? false);
const config = (website?.replayConfig as ReplayConfig) || {};
const handleSubmit = async (data: any) => {
await mutateAsync(
{
replayEnabled: enabled,
replayConfig: {
sampleRate: parseFloat(data.sampleRate) || 1,
maskLevel: data.maskLevel || 'moderate',
maxDuration: parseInt(data.maxDuration, 10) || 600000,
blockSelector: data.blockSelector || '',
retentionDays: parseInt(data.retentionDays, 10) || 30,
},
},
{
onSuccess: async () => {
toast(formatMessage(messages.saved));
touch('websites');
touch(`website:${website.id}`);
},
},
);
};
return (
<Form
onSubmit={handleSubmit}
values={{
sampleRate: String(config.sampleRate ?? 1),
maskLevel: config.maskLevel ?? 'moderate',
maxDuration: String(config.maxDuration ?? 600000),
blockSelector: config.blockSelector ?? '',
retentionDays: String(config.retentionDays ?? 30),
}}
>
<Column gap="4">
<Label>{formatMessage(labels.replays)}</Label>
<Switch isSelected={enabled} onChange={setEnabled}>
{formatMessage(labels.replayEnabled)}
</Switch>
{enabled && (
<>
<FormField name="sampleRate" label={formatMessage(labels.sampleRate)}>
<TextField />
</FormField>
<FormField
name="maskLevel"
label={`${formatMessage(labels.maskLevel)} (strict / moderate / relaxed)`}
>
<TextField />
</FormField>
<FormField name="maxDuration" label={`${formatMessage(labels.maxDuration)} (ms)`}>
<TextField />
</FormField>
<FormField name="blockSelector" label={formatMessage(labels.blockSelector)}>
<TextField />
</FormField>
<FormField name="retentionDays" label={formatMessage(labels.retentionDays)}>
<TextField />
</FormField>
</>
)}
</Column>
<FormButtons>
<FormSubmitButton variant="primary">{formatMessage(labels.save)}</FormSubmitButton>
</FormButtons>
</Form>
);
}
@@ -2,6 +2,7 @@ import { Column } from '@umami/react-zen';
import { Panel } from '@/components/common/Panel';
import { WebsiteData } from './WebsiteData';
import { WebsiteEditForm } from './WebsiteEditForm';
import { WebsiteReplaySettings } from './WebsiteReplaySettings';
import { WebsiteShareForm } from './WebsiteShareForm';
import { WebsiteTrackingCode } from './WebsiteTrackingCode';
@@ -14,6 +15,9 @@ export function WebsiteSettings({ websiteId }: { websiteId: string; openExternal
<Panel>
<WebsiteTrackingCode websiteId={websiteId} />
</Panel>
<Panel>
<WebsiteReplaySettings websiteId={websiteId} />
</Panel>
<Panel>
<WebsiteShareForm websiteId={websiteId} />
</Panel>
@@ -1,7 +1,8 @@
import { Column, Label, Text, TextField } from '@umami/react-zen';
import { useConfig, useMessages } from '@/components/hooks';
import { useConfig, useMessages, useWebsite } from '@/components/hooks';
const SCRIPT_NAME = 'script.js';
const RECORDER_NAME = 'recorder.js';
export function WebsiteTrackingCode({
websiteId,
@@ -12,23 +13,29 @@ export function WebsiteTrackingCode({
}) {
const { t, messages, labels } = useMessages();
const config = useConfig();
const website = useWebsite();
const trackerScriptName =
config?.trackerScriptName?.split(',')?.map((n: string) => n.trim())?.[0] || SCRIPT_NAME;
const getUrl = () => {
const getUrl = (scriptName: string) => {
if (config?.cloudMode) {
return `${process.env.cloudUrl}/${trackerScriptName}`;
return `${process.env.cloudUrl}/${scriptName}`;
}
return `${hostUrl || window?.location?.origin || ''}${
process.env.basePath || ''
}/${trackerScriptName}`;
}/${scriptName}`;
};
const url = trackerScriptName?.startsWith('http') ? trackerScriptName : getUrl();
const url = trackerScriptName?.startsWith('http') ? trackerScriptName : getUrl(trackerScriptName);
const code = `<script defer src="${url}" data-website-id="${websiteId}"></script>`;
let code = `<script defer src="${url}" data-website-id="${websiteId}"></script>`;
if (website?.replayEnabled) {
const recorderUrl = getUrl(RECORDER_NAME);
code += `\n<script defer src="${recorderUrl}" data-website-id="${websiteId}"></script>`;
}
return (
<Column gap>
+104
View File
@@ -0,0 +1,104 @@
import { gzipSync } from 'node:zlib';
import { isbot } from 'isbot';
import { serializeError } from 'serialize-error';
import { z } from 'zod';
import { secret } from '@/lib/crypto';
import { getClientInfo, hasBlockedIp } from '@/lib/detect';
import { parseToken } from '@/lib/jwt';
import { parseRequest } from '@/lib/request';
import { badRequest, forbidden, json, serverError } from '@/lib/response';
import { getWebsite } from '@/queries/prisma';
import { saveReplayChunk } from '@/queries/sql';
const schema = z.object({
website: z.uuid(),
events: z.array(z.any()).max(200),
timestamp: z.coerce.number().int().optional(),
});
export async function POST(request: Request) {
try {
const { body, error } = await parseRequest(request, schema, { skipAuth: true });
if (error) {
return error();
}
const { website: websiteId, events, timestamp } = body;
if (!events?.length) {
return json({ ok: true });
}
// Parse cache token to get session info
const cacheHeader = request.headers.get('x-umami-cache');
if (!cacheHeader) {
return badRequest({ message: 'Missing session token.' });
}
const cache = await parseToken(cacheHeader, secret());
if (!cache || !cache.sessionId) {
return badRequest({ message: 'Invalid session token.' });
}
const { sessionId } = cache;
// Query directly to avoid stale Redis cache for recordingEnabled
const website = await getWebsite(websiteId);
if (!website) {
return badRequest({ message: 'Website not found.' });
}
if (!website.replayEnabled) {
return json({ ok: false, reason: 'replay_disabled' });
}
// Client info for bot/IP checks
const { ip, userAgent } = await getClientInfo(request, {});
if (!process.env.DISABLE_BOT_CHECK && isbot(userAgent)) {
return json({ beep: 'boop' });
}
if (hasBlockedIp(ip)) {
return forbidden();
}
// Compute timestamps from events
const eventTimestamps = events
.map((e: any) => e.timestamp)
.filter((t: any) => typeof t === 'number');
const startedAt = new Date(Math.min(...eventTimestamps));
const endedAt = new Date(Math.max(...eventTimestamps));
// Compress events
const eventsJson = JSON.stringify(events);
const compressed = gzipSync(Buffer.from(eventsJson, 'utf-8'));
// Use timestamp-based chunk index for ordering
const chunkIndex = timestamp || Math.floor(Date.now() / 1000);
await saveReplayChunk({
websiteId,
sessionId,
chunkIndex,
events: compressed,
eventCount: events.length,
startedAt,
endedAt,
});
return json({ ok: true });
} catch (e) {
const error = serializeError(e);
// eslint-disable-next-line no-console
console.log(error);
return serverError({ errorObject: error });
}
}
@@ -0,0 +1,41 @@
import { gunzipSync } from 'node:zlib';
import { parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { canViewWebsite } from '@/permissions';
import { getReplayChunks } from '@/queries/sql';
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string; sessionId: string }> },
) {
const { auth, error } = await parseRequest(request);
if (error) {
return error();
}
const { websiteId, sessionId } = await params;
if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}
const chunks = await getReplayChunks(websiteId, sessionId);
// Decompress and concatenate all chunks
const allEvents = chunks.flatMap(chunk => {
const decompressed = gunzipSync(Buffer.from(chunk.events));
return JSON.parse(decompressed.toString('utf-8'));
});
const startedAt = chunks.length > 0 ? chunks[0].startedAt : null;
const endedAt = chunks.length > 0 ? chunks[chunks.length - 1].endedAt : null;
return json({
events: allEvents,
startedAt,
endedAt,
eventCount: allEvents.length,
chunkCount: chunks.length,
});
}
@@ -0,0 +1,35 @@
import { z } from 'zod';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { dateRangeParams, pagingParams, searchParams } from '@/lib/schema';
import { canViewWebsite } from '@/permissions';
import { getSessionReplays } from '@/queries/sql';
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const schema = z.object({
...dateRangeParams,
...pagingParams,
...searchParams,
});
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const { websiteId } = await params;
if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}
const filters = await getQueryFilters(query, websiteId);
const data = await getSessionReplays(websiteId, filters);
return json(data);
}
+18 -2
View File
@@ -42,6 +42,17 @@ export async function POST(
name: z.string().optional(),
domain: z.string().optional(),
shareId: z.string().max(50).nullable().optional(),
replayEnabled: z.boolean().optional(),
replayConfig: z
.object({
sampleRate: z.number().min(0).max(1).optional(),
maskLevel: z.enum(['strict', 'moderate', 'relaxed']).optional(),
maxDuration: z.number().int().positive().optional(),
blockSelector: z.string().optional(),
retentionDays: z.number().int().positive().optional(),
})
.nullable()
.optional(),
});
const { auth, body, error } = await parseRequest(request, schema);
@@ -51,14 +62,19 @@ export async function POST(
}
const { websiteId } = await params;
const { name, domain, shareId } = body;
const { name, domain, shareId, replayEnabled, replayConfig } = body;
if (!(await canUpdateWebsite(auth, websiteId))) {
return unauthorized();
}
try {
const website = await updateWebsite(websiteId, { name, domain });
const website = await updateWebsite(websiteId, {
name,
domain,
...(replayEnabled !== undefined && { replayEnabled }),
...(replayConfig !== undefined && { replayConfig }),
});
if (shareId === null) {
await deleteSharesByEntityId(website.id);
+2
View File
@@ -26,6 +26,8 @@ export * from './queries/useLoginQuery';
export * from './queries/usePixelQuery';
export * from './queries/usePixelsQuery';
export * from './queries/useRealtimeQuery';
export * from './queries/useReplayQuery';
export * from './queries/useReplaysQuery';
export * from './queries/useReportQuery';
export * from './queries/useReportsQuery';
export * from './queries/useResultQuery';
@@ -0,0 +1,13 @@
import { useApi } from '../useApi';
export function useReplayQuery(websiteId: string, sessionId: string) {
const { get, useQuery } = useApi();
return useQuery({
queryKey: ['replay', { websiteId, sessionId }],
queryFn: () => {
return get(`/websites/${websiteId}/replays/${sessionId}`);
},
enabled: Boolean(websiteId && sessionId),
});
}
@@ -0,0 +1,25 @@
import { useApi } from '../useApi';
import { useDateParameters } from '../useDateParameters';
import { useModified } from '../useModified';
import { usePagedQuery } from '../usePagedQuery';
export function useReplaysQuery(websiteId: string, params?: Record<string, string | number>) {
const { get } = useApi();
const { modified } = useModified('replays');
const { startAt, endAt, unit, timezone } = useDateParameters();
return usePagedQuery({
queryKey: ['replays', { websiteId, modified, startAt, endAt, unit, timezone, ...params }],
queryFn: pageParams => {
return get(`/websites/${websiteId}/replays`, {
startAt,
endAt,
unit,
timezone,
...pageParams,
...params,
pageSize: 20,
});
},
});
}
@@ -7,6 +7,7 @@ import {
Tag,
User,
UserPlus,
Video,
} from '@/components/icons';
import { Funnel, Gauge, Lightning, Magnet, Money, Network, Path, Target } from '@/components/svg';
import { useMessages } from './useMessages';
@@ -100,6 +101,12 @@ export function useWebsiteNavItems(websiteId: string) {
icon: <Magnet />,
path: renderPath('/retention'),
},
{
id: 'replays',
label: formatMessage(labels.replays),
icon: <Video />,
path: renderPath('/replays'),
},
],
},
{
+8
View File
@@ -136,6 +136,10 @@ export async function resetWebsite(websiteId: string) {
return transaction(
async tx => {
await tx.sessionReplay.deleteMany({
where: { websiteId },
});
await tx.revenue.deleteMany({
where: { websiteId },
});
@@ -183,6 +187,10 @@ export async function deleteWebsite(websiteId: string) {
return transaction(
async tx => {
await tx.sessionReplay.deleteMany({
where: { websiteId },
});
await tx.revenue.deleteMany({
where: { websiteId },
});
+4
View File
@@ -24,6 +24,10 @@ export * from './pageviews/getPageviewMetrics';
export * from './pageviews/getPageviewStats';
export * from './performance/getPerformanceStats';
export * from './performance/savePerformance';
export * from './replays/deleteReplaysByWebsite';
export * from './replays/getReplayChunks';
export * from './replays/getSessionReplays';
export * from './replays/saveReplayChunk';
export * from './reports/getBreakdown';
export * from './reports/getFunnel';
export * from './reports/getJourney';
@@ -0,0 +1,11 @@
import prisma from '@/lib/prisma';
export async function deleteReplaysByWebsite(websiteId: string) {
return relationalQuery(websiteId);
}
async function relationalQuery(websiteId: string) {
return prisma.client.sessionReplay.deleteMany({
where: { websiteId },
});
}
@@ -0,0 +1,24 @@
import prisma from '@/lib/prisma';
export async function getReplayChunks(websiteId: string, sessionId: string) {
return relationalQuery(websiteId, sessionId);
}
async function relationalQuery(websiteId: string, sessionId: string) {
return prisma.client.sessionReplay.findMany({
where: {
websiteId,
sessionId,
},
orderBy: {
chunkIndex: 'asc',
},
select: {
events: true,
chunkIndex: true,
eventCount: true,
startedAt: true,
endedAt: true,
},
});
}
@@ -0,0 +1,67 @@
import prisma from '@/lib/prisma';
import type { QueryFilters } from '@/lib/types';
const FUNCTION_NAME = 'getSessionReplays';
export async function getSessionReplays(...args: [websiteId: string, filters: QueryFilters]) {
return relationalQuery(...args);
}
async function relationalQuery(websiteId: string, filters: QueryFilters) {
const { pagedRawQuery, parseFilters } = prisma;
const { search, startDate, endDate } = filters;
const { queryParams } = parseFilters({
...filters,
websiteId,
search: search ? `%${search}%` : undefined,
});
let dateQuery = '';
if (startDate && endDate) {
dateQuery = `and sr.created_at between {{startDate}} and {{endDate}}`;
} else if (startDate) {
dateQuery = `and sr.created_at >= {{startDate}}`;
}
const searchQuery = search
? `and (session.distinct_id ilike {{search}}
or session.city ilike {{search}}
or session.browser ilike {{search}})`
: '';
return pagedRawQuery(
`
select
sr.session_id as "id",
sr.website_id as "websiteId",
session.browser,
session.os,
session.device,
session.country,
session.city,
sum(sr.event_count) as "eventCount",
count(sr.replay_id) as "chunkCount",
min(sr.started_at) as "startedAt",
max(sr.ended_at) as "endedAt",
(extract(epoch from max(sr.ended_at) - min(sr.started_at)) * 1000)::bigint as "duration",
max(sr.created_at) as "createdAt"
from session_replay sr
left join session on session.session_id = sr.session_id
and session.website_id = sr.website_id
where sr.website_id = {{websiteId::uuid}}
${dateQuery}
${searchQuery}
group by sr.session_id,
sr.website_id,
session.browser,
session.os,
session.device,
session.country,
session.city
order by max(sr.created_at) desc
`,
queryParams,
filters,
FUNCTION_NAME,
);
}
+4
View File
@@ -0,0 +1,4 @@
export * from './deleteReplaysByWebsite';
export * from './getReplayChunks';
export * from './getSessionReplays';
export * from './saveReplayChunk';
@@ -0,0 +1,39 @@
import { uuid } from '@/lib/crypto';
import prisma from '@/lib/prisma';
export interface SaveReplayChunkArgs {
websiteId: string;
sessionId: string;
chunkIndex: number;
events: Uint8Array;
eventCount: number;
startedAt: Date;
endedAt: Date;
}
export async function saveReplayChunk(args: SaveReplayChunkArgs) {
return relationalQuery(args);
}
async function relationalQuery({
websiteId,
sessionId,
chunkIndex,
events,
eventCount,
startedAt,
endedAt,
}: SaveReplayChunkArgs) {
return prisma.client.sessionReplay.create({
data: {
id: uuid(),
websiteId,
sessionId,
chunkIndex,
events: new Uint8Array(events) as any,
eventCount,
startedAt,
endedAt,
},
});
}
+171
View File
@@ -0,0 +1,171 @@
import { record } from 'rrweb';
(window => {
const { document } = window;
const { currentScript } = document;
if (!currentScript) return;
const _data = 'data-';
const attr = currentScript.getAttribute.bind(currentScript);
const website = attr(`${_data}website-id`);
const hostUrl = attr(`${_data}host-url`);
const sampleRate = parseFloat(attr(`${_data}sample-rate`) || '1');
const maskLevel = attr(`${_data}mask-level`) || 'moderate';
const maxDuration = parseInt(attr(`${_data}max-duration`) || '600000', 10);
const blockSelector = attr(`${_data}block-selector`) || '';
if (!website) return;
// Sample rate check
if (sampleRate < 1 && Math.random() > sampleRate) return;
const host =
hostUrl || '__COLLECT_API_HOST__' || currentScript.src.split('/').slice(0, -1).join('/');
const endpoint = `${host.replace(/\/$/, '')}__COLLECT_REPLAY_ENDPOINT__`;
const FLUSH_EVENT_COUNT = 50;
const FLUSH_INTERVAL = 10000;
let eventBuffer = [];
let stopFn = null;
let flushTimer = null;
let startTime = null;
let stopped = false;
const sendEvents = (events, useKeepalive = false) => {
const session = window.umami?.getSession?.();
if (!session?.cache) return;
const body = JSON.stringify({
website,
events,
timestamp: Math.floor(Date.now() / 1000),
});
// keepalive has a 64KB body limit — only use it for small payloads on unload
const keepalive = useKeepalive && body.length < 60000;
return fetch(endpoint, {
keepalive,
method: 'POST',
body,
headers: {
'Content-Type': 'application/json',
'x-umami-cache': session.cache,
},
credentials: 'omit',
}).catch(() => {});
};
const flush = (useKeepalive = false) => {
if (!eventBuffer.length) return;
const events = eventBuffer;
eventBuffer = [];
sendEvents(events, useKeepalive);
};
const scheduleFlush = () => {
if (flushTimer) clearTimeout(flushTimer);
flushTimer = setTimeout(flush, FLUSH_INTERVAL);
};
const stop = () => {
if (stopped) return;
stopped = true;
if (flushTimer) clearTimeout(flushTimer);
flush();
if (stopFn) stopFn();
};
const getMaskConfig = level => {
switch (level) {
case 'strict':
return {
maskAllInputs: true,
maskTextContent: true,
maskAllText: true,
};
case 'relaxed':
return {
maskAllInputs: true,
maskTextContent: false,
maskAllText: false,
};
default:
return {
maskAllInputs: true,
maskTextContent: false,
maskAllText: false,
};
}
};
const waitForSession = (attempts = 0) => {
if (attempts > 50) return;
const session = window.umami?.getSession?.();
if (session?.cache) {
beginRecording();
} else {
setTimeout(() => waitForSession(attempts + 1), 100);
}
};
const beginRecording = () => {
startTime = Date.now();
const maskConfig = getMaskConfig(maskLevel);
stopFn = record({
emit(event) {
if (stopped) return;
if (Date.now() - startTime > maxDuration) {
stop();
return;
}
eventBuffer.push(event);
if (eventBuffer.length >= FLUSH_EVENT_COUNT) {
flush();
}
scheduleFlush();
},
...maskConfig,
inlineStylesheet: true,
slimDOMOptions: {
script: true,
comment: true,
headMetaDescKeywords: true,
headMetaSocial: true,
headMetaRobots: true,
headMetaHttpEquiv: true,
headMetaAuthorship: true,
headMetaVerification: true,
},
recordCanvas: false,
recordCrossOriginIframes: false,
checkoutEveryNms: 30000,
...(blockSelector && { blockSelector }),
});
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') flush(true);
});
window.addEventListener('beforeunload', () => flush(true));
};
if (document.readyState === 'complete') {
waitForSession();
} else {
document.addEventListener('readystatechange', () => {
if (document.readyState === 'complete') waitForSession();
});
}
})(window);
+1
View File
@@ -298,6 +298,7 @@
window.umami = {
track,
identify,
getSession: () => ({ cache, website }),
};
}