final fixes

This commit is contained in:
Carl-Gerhard Lindesvärd
2026-02-26 10:19:29 +01:00
parent b193ccb7d0
commit d5513d8a47
21 changed files with 388 additions and 370 deletions

View File

@@ -1,26 +1,25 @@
import type { FastifyReply, FastifyRequest } from 'fastify';
import { generateDeviceId, parseUserAgent } from '@openpanel/common/server';
import { getSalts } from '@openpanel/db';
import { getEventsGroupQueueShard } from '@openpanel/queue';
import { generateId, slug } from '@openpanel/common'; import { generateId, slug } from '@openpanel/common';
import { parseUserAgent } from '@openpanel/common/server';
import { getSalts } from '@openpanel/db';
import { getGeoLocation } from '@openpanel/geo'; import { getGeoLocation } from '@openpanel/geo';
import { getEventsGroupQueueShard } from '@openpanel/queue';
import type { DeprecatedPostEventPayload } from '@openpanel/validation'; import type { DeprecatedPostEventPayload } from '@openpanel/validation';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { getStringHeaders, getTimestamp } from './track.controller'; import { getStringHeaders, getTimestamp } from './track.controller';
import { getDeviceId } from '@/utils/ids';
export async function postEvent( export async function postEvent(
request: FastifyRequest<{ request: FastifyRequest<{
Body: DeprecatedPostEventPayload; Body: DeprecatedPostEventPayload;
}>, }>,
reply: FastifyReply, reply: FastifyReply
) { ) {
const { timestamp, isTimestampFromThePast } = getTimestamp( const { timestamp, isTimestampFromThePast } = getTimestamp(
request.timestamp, request.timestamp,
request.body, request.body
); );
const ip = request.clientIp; const ip = request.clientIp;
const ua = request.headers['user-agent']; const ua = request.headers['user-agent'] ?? 'unknown/1.0';
const projectId = request.client?.projectId; const projectId = request.client?.projectId;
const headers = getStringHeaders(request.headers); const headers = getStringHeaders(request.headers);
@@ -30,34 +29,22 @@ export async function postEvent(
} }
const [salts, geo] = await Promise.all([getSalts(), getGeoLocation(ip)]); const [salts, geo] = await Promise.all([getSalts(), getGeoLocation(ip)]);
const currentDeviceId = ua const { deviceId, sessionId } = await getDeviceId({
? generateDeviceId({ projectId,
salt: salts.current, ip,
origin: projectId, ua,
ip, salts,
ua, });
})
: '';
const previousDeviceId = ua
? generateDeviceId({
salt: salts.previous,
origin: projectId,
ip,
ua,
})
: '';
const uaInfo = parseUserAgent(ua, request.body?.properties); const uaInfo = parseUserAgent(ua, request.body?.properties);
const groupId = uaInfo.isServer const groupId = uaInfo.isServer
? request.body?.profileId ? `${projectId}:${request.body?.profileId ?? generateId()}`
? `${projectId}:${request.body?.profileId}` : deviceId;
: `${projectId}:${generateId()}`
: currentDeviceId;
const jobId = [ const jobId = [
slug(request.body.name), slug(request.body.name),
timestamp, timestamp,
projectId, projectId,
currentDeviceId, deviceId,
groupId, groupId,
] ]
.filter(Boolean) .filter(Boolean)
@@ -74,9 +61,10 @@ export async function postEvent(
}, },
uaInfo, uaInfo,
geo, geo,
currentDeviceId, currentDeviceId: '',
previousDeviceId, previousDeviceId: '',
deviceId: '', deviceId,
sessionId: sessionId ?? '',
}, },
groupId, groupId,
jobId, jobId,

View File

@@ -1,7 +1,3 @@
import type { FastifyReply, FastifyRequest } from 'fastify';
import { assocPath, pathOr, pick } from 'ramda';
import { HttpError } from '@/utils/errors';
import { generateId, slug } from '@openpanel/common'; import { generateId, slug } from '@openpanel/common';
import { generateDeviceId, parseUserAgent } from '@openpanel/common/server'; import { generateDeviceId, parseUserAgent } from '@openpanel/common/server';
import { import {
@@ -13,8 +9,6 @@ import {
import { type GeoLocation, getGeoLocation } from '@openpanel/geo'; import { type GeoLocation, getGeoLocation } from '@openpanel/geo';
import { getEventsGroupQueueShard } from '@openpanel/queue'; import { getEventsGroupQueueShard } from '@openpanel/queue';
import { getRedisCache } from '@openpanel/redis'; import { getRedisCache } from '@openpanel/redis';
import { getDeviceId } from '@/utils/ids';
import { import {
type IDecrementPayload, type IDecrementPayload,
type IIdentifyPayload, type IIdentifyPayload,
@@ -24,6 +18,10 @@ import {
type ITrackPayload, type ITrackPayload,
zTrackHandlerPayload, zTrackHandlerPayload,
} from '@openpanel/validation'; } from '@openpanel/validation';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { assocPath, pathOr, pick } from 'ramda';
import { HttpError } from '@/utils/errors';
import { getDeviceId } from '@/utils/ids';
export function getStringHeaders(headers: FastifyRequest['headers']) { export function getStringHeaders(headers: FastifyRequest['headers']) {
return Object.entries( return Object.entries(
@@ -35,14 +33,14 @@ export function getStringHeaders(headers: FastifyRequest['headers']) {
'openpanel-client-id', 'openpanel-client-id',
'request-id', 'request-id',
], ],
headers, headers
), )
).reduce( ).reduce(
(acc, [key, value]) => ({ (acc, [key, value]) => ({
...acc, ...acc,
[key]: value ? String(value) : undefined, [key]: value ? String(value) : undefined,
}), }),
{}, {}
); );
} }
@@ -68,7 +66,7 @@ function getIdentity(body: ITrackHandlerPayload): IIdentifyPayload | undefined {
export function getTimestamp( export function getTimestamp(
timestamp: FastifyRequest['timestamp'], timestamp: FastifyRequest['timestamp'],
payload: ITrackHandlerPayload['payload'], payload: ITrackHandlerPayload['payload']
) { ) {
const safeTimestamp = timestamp || Date.now(); const safeTimestamp = timestamp || Date.now();
const userDefinedTimestamp = const userDefinedTimestamp =
@@ -121,7 +119,7 @@ async function buildContext(
request: FastifyRequest<{ request: FastifyRequest<{
Body: ITrackHandlerPayload; Body: ITrackHandlerPayload;
}>, }>,
validatedBody: ITrackHandlerPayload, validatedBody: ITrackHandlerPayload
): Promise<TrackContext> { ): Promise<TrackContext> {
const projectId = request.client?.projectId; const projectId = request.client?.projectId;
if (!projectId) { if (!projectId) {
@@ -176,7 +174,7 @@ async function buildContext(
async function handleTrack( async function handleTrack(
payload: ITrackPayload, payload: ITrackPayload,
context: TrackContext, context: TrackContext
): Promise<void> { ): Promise<void> {
const { projectId, deviceId, geo, headers, timestamp, sessionId } = context; const { projectId, deviceId, geo, headers, timestamp, sessionId } = context;
@@ -224,7 +222,7 @@ async function handleTrack(
}, },
groupId, groupId,
jobId, jobId,
}), })
); );
await Promise.all(promises); await Promise.all(promises);
@@ -232,7 +230,7 @@ async function handleTrack(
async function handleIdentify( async function handleIdentify(
payload: IIdentifyPayload, payload: IIdentifyPayload,
context: TrackContext, context: TrackContext
): Promise<void> { ): Promise<void> {
const { projectId, geo, ua } = context; const { projectId, geo, ua } = context;
const uaInfo = parseUserAgent(ua, payload.properties); const uaInfo = parseUserAgent(ua, payload.properties);
@@ -262,7 +260,7 @@ async function handleIdentify(
async function adjustProfileProperty( async function adjustProfileProperty(
payload: IIncrementPayload | IDecrementPayload, payload: IIncrementPayload | IDecrementPayload,
projectId: string, projectId: string,
direction: 1 | -1, direction: 1 | -1
): Promise<void> { ): Promise<void> {
const { profileId, property, value } = payload; const { profileId, property, value } = payload;
const profile = await getProfileById(profileId, projectId); const profile = await getProfileById(profileId, projectId);
@@ -272,7 +270,7 @@ async function adjustProfileProperty(
const parsed = Number.parseInt( const parsed = Number.parseInt(
pathOr<string>('0', property.split('.'), profile.properties), pathOr<string>('0', property.split('.'), profile.properties),
10, 10
); );
if (Number.isNaN(parsed)) { if (Number.isNaN(parsed)) {
@@ -282,7 +280,7 @@ async function adjustProfileProperty(
profile.properties = assocPath( profile.properties = assocPath(
property.split('.'), property.split('.'),
parsed + direction * (value || 1), parsed + direction * (value || 1),
profile.properties, profile.properties
); );
await upsertProfile({ await upsertProfile({
@@ -295,21 +293,21 @@ async function adjustProfileProperty(
async function handleIncrement( async function handleIncrement(
payload: IIncrementPayload, payload: IIncrementPayload,
context: TrackContext, context: TrackContext
): Promise<void> { ): Promise<void> {
await adjustProfileProperty(payload, context.projectId, 1); await adjustProfileProperty(payload, context.projectId, 1);
} }
async function handleDecrement( async function handleDecrement(
payload: IDecrementPayload, payload: IDecrementPayload,
context: TrackContext, context: TrackContext
): Promise<void> { ): Promise<void> {
await adjustProfileProperty(payload, context.projectId, -1); await adjustProfileProperty(payload, context.projectId, -1);
} }
async function handleReplay( async function handleReplay(
payload: IReplayPayload, payload: IReplayPayload,
context: TrackContext, context: TrackContext
): Promise<void> { ): Promise<void> {
if (!context.sessionId) { if (!context.sessionId) {
throw new HttpError('Session ID is required for replay', { status: 400 }); throw new HttpError('Session ID is required for replay', { status: 400 });
@@ -318,7 +316,6 @@ async function handleReplay(
const row = { const row = {
project_id: context.projectId, project_id: context.projectId,
session_id: context.sessionId, session_id: context.sessionId,
profile_id: '', // TODO: remove
chunk_index: payload.chunk_index, chunk_index: payload.chunk_index,
started_at: payload.started_at, started_at: payload.started_at,
ended_at: payload.ended_at, ended_at: payload.ended_at,
@@ -333,7 +330,7 @@ export async function handler(
request: FastifyRequest<{ request: FastifyRequest<{
Body: ITrackHandlerPayload; Body: ITrackHandlerPayload;
}>, }>,
reply: FastifyReply, reply: FastifyReply
) { ) {
// Validate request body with Zod // Validate request body with Zod
const validationResult = zTrackHandlerPayload.safeParse(request.body); const validationResult = zTrackHandlerPayload.safeParse(request.body);
@@ -393,7 +390,7 @@ export async function handler(
export async function fetchDeviceId( export async function fetchDeviceId(
request: FastifyRequest, request: FastifyRequest,
reply: FastifyReply, reply: FastifyReply
) { ) {
const salts = await getSalts(); const salts = await getSalts();
const projectId = request.client?.projectId; const projectId = request.client?.projectId;
@@ -428,11 +425,11 @@ export async function fetchDeviceId(
const multi = getRedisCache().multi(); const multi = getRedisCache().multi();
multi.hget( multi.hget(
`bull:sessions:sessionEnd:${projectId}:${currentDeviceId}`, `bull:sessions:sessionEnd:${projectId}:${currentDeviceId}`,
'data', 'data'
); );
multi.hget( multi.hget(
`bull:sessions:sessionEnd:${projectId}:${previousDeviceId}`, `bull:sessions:sessionEnd:${projectId}:${previousDeviceId}`,
'data', 'data'
); );
const res = await multi.exec(); const res = await multi.exec();
if (res?.[0]?.[1]) { if (res?.[0]?.[1]) {

View File

@@ -14,7 +14,8 @@ export async function duplicateHook(
const ip = req.clientIp; const ip = req.clientIp;
const origin = req.headers.origin; const origin = req.headers.origin;
const clientId = req.headers['openpanel-client-id']; const clientId = req.headers['openpanel-client-id'];
const shouldCheck = ip && origin && clientId && req.body.type !== 'replay'; const isReplay = 'type' in req.body && req.body.type === 'replay';
const shouldCheck = ip && origin && clientId && !isReplay;
const isDuplicate = shouldCheck const isDuplicate = shouldCheck
? await isDuplicatedEvent({ ? await isDuplicatedEvent({
@@ -25,7 +26,6 @@ export async function duplicateHook(
}) })
: false; : false;
console.log('Duplicate event', isDuplicate);
if (isDuplicate) { if (isDuplicate) {
return reply.status(200).send('Duplicate event'); return reply.status(200).send('Duplicate event');
} }

View File

@@ -41,7 +41,6 @@ export async function requestLoggingHook(
['openpanel-client-id', 'openpanel-sdk-name', 'openpanel-sdk-version'], ['openpanel-client-id', 'openpanel-sdk-name', 'openpanel-sdk-version'],
request.headers request.headers
), ),
// body: request.body,
}); });
} }
} }

View File

@@ -116,7 +116,7 @@ const startServer = async () => {
return callback(null, { return callback(null, {
origin: '*', origin: '*',
maxAge: 86_400 * 7, // cache preflight for 24h maxAge: 86_400 * 7, // cache preflight for 7 days
}); });
}; };
}); });
@@ -125,11 +125,6 @@ const startServer = async () => {
global: false, global: false,
}); });
fastify.addHook('onRequest', async (req) => {
if (req.method === 'POST') {
console.log('Incoming req', req.method, req.url);
}
});
fastify.addHook('onRequest', requestIdHook); fastify.addHook('onRequest', requestIdHook);
fastify.addHook('onRequest', timestampHook); fastify.addHook('onRequest', timestampHook);
fastify.addHook('onRequest', ipHook); fastify.addHook('onRequest', ipHook);

View File

@@ -54,7 +54,8 @@ import { OpenPanelComponent } from '@openpanel/astro';
##### Astro options ##### Astro options
- `profileId` - If you have a user id, you can pass it here to identify the user - `profileId` - If you have a user id, you can pass it here to identify the user
- `cdnUrl` - The url to the OpenPanel SDK (default: `https://openpanel.dev/op1.js`) - `cdnUrl` (deprecated) - The url to the OpenPanel SDK (default: `https://openpanel.dev/op1.js`)
- `scriptUrl` - The url to the OpenPanel SDK (default: `https://openpanel.dev/op1.js`)
- `filter` - This is a function that will be called before tracking an event. If it returns false the event will not be tracked. [Read more](#filter) - `filter` - This is a function that will be called before tracking an event. If it returns false the event will not be tracked. [Read more](#filter)
- `globalProperties` - This is an object of properties that will be sent with every event. - `globalProperties` - This is an object of properties that will be sent with every event.

View File

@@ -62,7 +62,8 @@ export default function RootLayout({ children }) {
##### NextJS options ##### NextJS options
- `profileId` - If you have a user id, you can pass it here to identify the user - `profileId` - If you have a user id, you can pass it here to identify the user
- `cdnUrl` - The url to the OpenPanel SDK (default: `https://openpanel.dev/op1.js`) - `cdnUrl` (deprecated) - The url to the OpenPanel SDK (default: `https://openpanel.dev/op1.js`)
- `scriptUrl` - The url to the OpenPanel SDK (default: `https://openpanel.dev/op1.js`)
- `filter` - This is a function that will be called before tracking an event. If it returns false the event will not be tracked. [Read more](#filter) - `filter` - This is a function that will be called before tracking an event. If it returns false the event will not be tracked. [Read more](#filter)
- `globalProperties` - This is an object of properties that will be sent with every event. - `globalProperties` - This is an object of properties that will be sent with every event.
@@ -286,12 +287,12 @@ import { createRouteHandler } from '@openpanel/nextjs/server';
export const { GET, POST } = createRouteHandler(); export const { GET, POST } = createRouteHandler();
``` ```
Remember to change the `apiUrl` and `cdnUrl` in the `OpenPanelComponent` to your own server. Remember to change the `apiUrl` and `scriptUrl` in the `OpenPanelComponent` to your own server.
```tsx ```tsx
<OpenPanelComponent <OpenPanelComponent
apiUrl="/api/op" // [!code highlight] apiUrl="/api/op" // [!code highlight]
cdnUrl="/api/op/op1.js" // [!code highlight] scriptUrl="/api/op/op1.js" // [!code highlight]
clientId="your-client-id" clientId="your-client-id"
trackScreenViews={true} trackScreenViews={true}
/> />

View File

@@ -225,7 +225,7 @@ Then update your OpenPanelComponent to use the proxy endpoint.
```tsx ```tsx
<OpenPanelComponent <OpenPanelComponent
apiUrl="/api/op" apiUrl="/api/op"
cdnUrl="/api/op/op1.js" scriptUrl="/api/op/op1.js"
clientId="your-client-id" clientId="your-client-id"
trackScreenViews={true} trackScreenViews={true}
/> />

View File

@@ -4,6 +4,7 @@ import { Maximize2, Minimize2 } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { BrowserChrome } from './browser-chrome'; import { BrowserChrome } from './browser-chrome';
import { ReplayTime } from './replay-controls'; import { ReplayTime } from './replay-controls';
import { ReplayTimeline } from './replay-timeline';
import { getEventOffsetMs } from './replay-utils'; import { getEventOffsetMs } from './replay-utils';
import { import {
ReplayProvider, ReplayProvider,
@@ -12,7 +13,6 @@ import {
} from '@/components/sessions/replay/replay-context'; } from '@/components/sessions/replay/replay-context';
import { ReplayEventFeed } from '@/components/sessions/replay/replay-event-feed'; import { ReplayEventFeed } from '@/components/sessions/replay/replay-event-feed';
import { ReplayPlayer } from '@/components/sessions/replay/replay-player'; import { ReplayPlayer } from '@/components/sessions/replay/replay-player';
import { ReplayTimeline } from '@/components/sessions/replay/replay-timeline';
import { useTRPC } from '@/integrations/trpc/react'; import { useTRPC } from '@/integrations/trpc/react';
function BrowserUrlBar({ events }: { events: IServiceEvent[] }) { function BrowserUrlBar({ events }: { events: IServiceEvent[] }) {
@@ -32,7 +32,7 @@ function BrowserUrlBar({ events }: { events: IServiceEvent[] }) {
.filter(({ offsetMs }) => offsetMs >= -10_000 && offsetMs <= currentTime) .filter(({ offsetMs }) => offsetMs >= -10_000 && offsetMs <= currentTime)
.sort((a, b) => a.offsetMs - b.offsetMs); .sort((a, b) => a.offsetMs - b.offsetMs);
const latest = withOffset[withOffset.length - 1]; const latest = withOffset.at(-1);
if (!latest) { if (!latest) {
return ''; return '';
} }
@@ -74,7 +74,7 @@ function ReplayChunkLoader({
) )
.then((res) => { .then((res) => {
res.data.forEach((row) => { res.data.forEach((row) => {
row.events.forEach((event) => { row?.events?.forEach((event) => {
addEvent(event); addEvent(event);
}); });
}); });
@@ -82,6 +82,9 @@ function ReplayChunkLoader({
if (res.hasMore) { if (res.hasMore) {
recursive(fromIndex + res.data.length); recursive(fromIndex + res.data.length);
} }
})
.catch(() => {
// chunk loading failed — replay may be incomplete
}); });
} }
@@ -160,10 +163,30 @@ function ReplayContent({
); );
const events = eventsData?.data ?? []; const events = eventsData?.data ?? [];
const playerEvents = firstBatch?.data.flatMap((row) => row.events) ?? []; const playerEvents =
firstBatch?.data.flatMap((row) => row?.events ?? []) ?? [];
const hasMore = firstBatch?.hasMore ?? false; const hasMore = firstBatch?.hasMore ?? false;
const hasReplay = playerEvents.length !== 0; const hasReplay = playerEvents.length !== 0;
function renderReplay() {
if (replayLoading) {
return (
<div className="col h-[320px] items-center justify-center gap-4 bg-background">
<div className="h-8 w-8 animate-pulse rounded-full bg-muted" />
<div>Loading session replay</div>
</div>
);
}
if (hasReplay) {
return <ReplayPlayer events={playerEvents} />;
}
return (
<div className="flex h-[320px] items-center justify-center bg-background text-muted-foreground text-sm">
No replay data available for this session.
</div>
);
}
return ( return (
<ReplayProvider> <ReplayProvider>
<div <div
@@ -187,18 +210,7 @@ function ReplayContent({
) )
} }
> >
{replayLoading ? ( {renderReplay()}
<div className="col h-[320px] items-center justify-center gap-4 bg-background">
<div className="h-8 w-8 animate-pulse rounded-full bg-muted" />
<div>Loading session replay</div>
</div>
) : hasReplay ? (
<ReplayPlayer events={playerEvents} />
) : (
<div className="flex h-[320px] items-center justify-center bg-background text-muted-foreground text-sm">
No replay data available for this session.
</div>
)}
{hasReplay && <ReplayTimeline events={events} />} {hasReplay && <ReplayTimeline events={events} />}
</BrowserChrome> </BrowserChrome>
</div> </div>

View File

@@ -1,14 +1,12 @@
import { ProjectLink } from '@/components/links';
import { SerieIcon } from '@/components/report-chart/common/serie-icon';
import { formatDateTime, formatTimeAgoOrDateTime } from '@/utils/date';
import type { ColumnDef } from '@tanstack/react-table';
import { Video } from 'lucide-react';
import { ColumnCreatedAt } from '@/components/column-created-at';
import { ProfileAvatar } from '@/components/profiles/profile-avatar';
import { getProfileName } from '@/utils/getters';
import { round } from '@openpanel/common'; import { round } from '@openpanel/common';
import type { IServiceSession } from '@openpanel/db'; import type { IServiceSession } from '@openpanel/db';
import type { ColumnDef } from '@tanstack/react-table';
import { Video } from 'lucide-react';
import { ColumnCreatedAt } from '@/components/column-created-at';
import { ProjectLink } from '@/components/links';
import { ProfileAvatar } from '@/components/profiles/profile-avatar';
import { SerieIcon } from '@/components/report-chart/common/serie-icon';
import { getProfileName } from '@/utils/getters';
function formatDuration(milliseconds: number): string { function formatDuration(milliseconds: number): string {
const seconds = milliseconds / 1000; const seconds = milliseconds / 1000;
@@ -45,20 +43,20 @@ export function useColumns() {
cell: ({ row }) => { cell: ({ row }) => {
const session = row.original; const session = row.original;
return ( return (
<div className="row gap-2 items-center"> <div className="row items-center gap-2">
<ProjectLink <ProjectLink
href={`/sessions/${session.id}`}
className="font-medium" className="font-medium"
href={`/sessions/${session.id}`}
title={session.id} title={session.id}
> >
{session.id.slice(0, 8)}... {session.id.slice(0, 8)}...
</ProjectLink> </ProjectLink>
{session.hasReplay && ( {session.hasReplay && (
<ProjectLink <ProjectLink
href={`/sessions/${session.id}#replay`}
className="text-muted-foreground hover:text-foreground"
title="View replay"
aria-label="View replay" aria-label="View replay"
className="text-muted-foreground hover:text-foreground"
href={`/sessions/${session.id}#replay`}
title="View replay"
> >
<Video className="size-4" /> <Video className="size-4" />
</ProjectLink> </ProjectLink>
@@ -76,8 +74,8 @@ export function useColumns() {
if (session.profile) { if (session.profile) {
return ( return (
<ProjectLink <ProjectLink
className="row items-center gap-2 font-medium"
href={`/profiles/${encodeURIComponent(session.profile.id)}`} href={`/profiles/${encodeURIComponent(session.profile.id)}`}
className="font-medium row gap-2 items-center"
> >
<ProfileAvatar size="sm" {...session.profile} /> <ProfileAvatar size="sm" {...session.profile} />
{getProfileName(session.profile)} {getProfileName(session.profile)}
@@ -86,8 +84,8 @@ export function useColumns() {
} }
return ( return (
<ProjectLink <ProjectLink
className="font-medium font-mono"
href={`/profiles/${encodeURIComponent(session.profileId)}`} href={`/profiles/${encodeURIComponent(session.profileId)}`}
className="font-mono font-medium"
> >
{session.profileId} {session.profileId}
</ProjectLink> </ProjectLink>

View File

@@ -1,22 +1,3 @@
import { ReportChartShortcut } from '@/components/report-chart/shortcut';
import {
useEventQueryFilters,
useEventQueryNamesFilter,
} from '@/hooks/use-event-query-filters';
import { ProjectLink } from '@/components/links';
import {
WidgetButtons,
WidgetHead,
} from '@/components/overview/overview-widget';
import { SerieIcon } from '@/components/report-chart/common/serie-icon';
import { Button } from '@/components/ui/button';
import { FieldValue, KeyValueGrid } from '@/components/ui/key-value-grid';
import { Widget, WidgetBody } from '@/components/widget';
import { fancyMinutes } from '@/hooks/use-numer-formatter';
import { useTRPC } from '@/integrations/trpc/react';
import { cn } from '@/utils/cn';
import { getProfileName } from '@/utils/getters';
import type { IClickhouseEvent, IServiceEvent } from '@openpanel/db'; import type { IClickhouseEvent, IServiceEvent } from '@openpanel/db';
import { useSuspenseQuery } from '@tanstack/react-query'; import { useSuspenseQuery } from '@tanstack/react-query';
import { FilterIcon, XIcon } from 'lucide-react'; import { FilterIcon, XIcon } from 'lucide-react';
@@ -24,6 +5,24 @@ import { omit } from 'ramda';
import { Suspense, useState } from 'react'; import { Suspense, useState } from 'react';
import { popModal } from '.'; import { popModal } from '.';
import { ModalContent } from './Modal/Container'; import { ModalContent } from './Modal/Container';
import { ProjectLink } from '@/components/links';
import {
WidgetButtons,
WidgetHead,
} from '@/components/overview/overview-widget';
import { SerieIcon } from '@/components/report-chart/common/serie-icon';
import { ReportChartShortcut } from '@/components/report-chart/shortcut';
import { Button } from '@/components/ui/button';
import { FieldValue, KeyValueGrid } from '@/components/ui/key-value-grid';
import { Widget, WidgetBody } from '@/components/widget';
import {
useEventQueryFilters,
useEventQueryNamesFilter,
} from '@/hooks/use-event-query-filters';
import { fancyMinutes } from '@/hooks/use-numer-formatter';
import { useTRPC } from '@/integrations/trpc/react';
import { cn } from '@/utils/cn';
import { getProfileName } from '@/utils/getters';
interface Props { interface Props {
id: string; id: string;
@@ -55,7 +54,7 @@ const filterable: Partial<Record<keyof IServiceEvent, keyof IClickhouseEvent>> =
export default function EventDetails(props: Props) { export default function EventDetails(props: Props) {
return ( return (
<ModalContent className="!p-0"> <ModalContent className="!p-0">
<Widget className="bg-transparent border-0 min-w-0"> <Widget className="min-w-0 border-0 bg-transparent">
<Suspense fallback={<EventDetailsSkeleton />}> <Suspense fallback={<EventDetailsSkeleton />}>
<EventDetailsContent {...props} /> <EventDetailsContent {...props} />
</Suspense> </Suspense>
@@ -84,7 +83,7 @@ function EventDetailsContent({ id, createdAt, projectId }: Props) {
id, id,
projectId, projectId,
createdAt, createdAt,
}), })
); );
const { event, session } = query.data; const { event, session } = query.data;
@@ -158,7 +157,7 @@ function EventDetailsContent({ id, createdAt, projectId }: Props) {
event, event,
}); });
} }
}, }
); );
} }
@@ -209,7 +208,7 @@ function EventDetailsContent({ id, createdAt, projectId }: Props) {
> >
<ArrowRightIcon className="size-4" /> <ArrowRightIcon className="size-4" />
</Button> */} </Button> */}
<Button size="icon" variant={'ghost'} onClick={() => popModal()}> <Button onClick={() => popModal()} size="icon" variant={'ghost'}>
<XIcon className="size-4" /> <XIcon className="size-4" />
</Button> </Button>
</div> </div>
@@ -218,10 +217,10 @@ function EventDetailsContent({ id, createdAt, projectId }: Props) {
<WidgetButtons> <WidgetButtons>
{Object.entries(TABS).map(([, tab]) => ( {Object.entries(TABS).map(([, tab]) => (
<button <button
key={tab.id}
type="button"
onClick={() => setWidget(tab)}
className={cn(tab.id === widget.id && 'active')} className={cn(tab.id === widget.id && 'active')}
key={tab.id}
onClick={() => setWidget(tab)}
type="button"
> >
{tab.title} {tab.title}
</button> </button>
@@ -231,29 +230,29 @@ function EventDetailsContent({ id, createdAt, projectId }: Props) {
<WidgetBody className="col gap-4 bg-def-100"> <WidgetBody className="col gap-4 bg-def-100">
{profile && ( {profile && (
<ProjectLink <ProjectLink
onClick={() => popModal()} className="card col gap-2 p-4 py-2 hover:bg-def-100"
href={`/profiles/${encodeURIComponent(profile.id)}`} href={`/profiles/${encodeURIComponent(profile.id)}`}
className="card p-4 py-2 col gap-2 hover:bg-def-100" onClick={() => popModal()}
> >
<div className="row items-center gap-2 justify-between"> <div className="row items-center justify-between gap-2">
<div className="row items-center gap-2 min-w-0"> <div className="row min-w-0 items-center gap-2">
{profile.avatar && ( {profile.avatar && (
<img <img
className="size-4 bg-border rounded-full" className="size-4 rounded-full bg-border"
src={profile.avatar} src={profile.avatar}
/> />
)} )}
<div className="font-medium truncate"> <div className="truncate font-medium">
{getProfileName(profile, false)} {getProfileName(profile, false)}
</div> </div>
</div> </div>
<div className="row items-center gap-2 shrink-0"> <div className="row shrink-0 items-center gap-2">
<div className="row gap-1 items-center"> <div className="row items-center gap-1">
<SerieIcon name={event.country} /> <SerieIcon name={event.country} />
<SerieIcon name={event.os} /> <SerieIcon name={event.os} />
<SerieIcon name={event.browser} /> <SerieIcon name={event.browser} />
</div> </div>
<div className="text-muted-foreground truncate max-w-40"> <div className="max-w-40 truncate text-muted-foreground">
{event.referrerName || event.referrer} {event.referrerName || event.referrer}
</div> </div>
</div> </div>
@@ -276,16 +275,16 @@ function EventDetailsContent({ id, createdAt, projectId }: Props) {
<KeyValueGrid <KeyValueGrid
columns={1} columns={1}
data={properties} data={properties}
onItemClick={(item) => {
popModal();
setFilter(`properties.${item.name}`, item.value as any);
}}
renderValue={(item) => ( renderValue={(item) => (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="font-mono">{String(item.value)}</span> <span className="font-mono">{String(item.value)}</span>
<FilterIcon className="size-3 shrink-0" /> <FilterIcon className="size-3 shrink-0" />
</div> </div>
)} )}
onItemClick={(item) => {
popModal();
setFilter(`properties.${item.name}`, item.value as any);
}}
/> />
</section> </section>
)} )}
@@ -296,25 +295,6 @@ function EventDetailsContent({ id, createdAt, projectId }: Props) {
<KeyValueGrid <KeyValueGrid
columns={1} columns={1}
data={data} data={data}
renderValue={(item) => {
const isFilterable = item.value && (filterable as any)[item.name];
if (isFilterable) {
return (
<div className="flex items-center gap-2">
<FieldValue
name={item.name}
value={item.value}
event={event}
/>
<FilterIcon className="size-3 shrink-0" />
</div>
);
}
return (
<FieldValue name={item.name} value={item.value} event={event} />
);
}}
onItemClick={(item) => { onItemClick={(item) => {
const isFilterable = item.value && (filterable as any)[item.name]; const isFilterable = item.value && (filterable as any)[item.name];
if (isFilterable) { if (isFilterable) {
@@ -322,26 +302,45 @@ function EventDetailsContent({ id, createdAt, projectId }: Props) {
setFilter(item.name as keyof IServiceEvent, item.value); setFilter(item.name as keyof IServiceEvent, item.value);
} }
}} }}
renderValue={(item) => {
const isFilterable = item.value && (filterable as any)[item.name];
if (isFilterable) {
return (
<div className="flex items-center gap-2">
<FieldValue
event={event}
name={item.name}
value={item.value}
/>
<FilterIcon className="size-3 shrink-0" />
</div>
);
}
return (
<FieldValue event={event} name={item.name} value={item.value} />
);
}}
/> />
</section> </section>
<section> <section>
<div className="mb-2 flex justify-between font-medium"> <div className="mb-2 flex justify-between font-medium">
<div>All events for {event.name}</div> <div>All events for {event.name}</div>
<button <button
type="button"
className="text-muted-foreground hover:underline" className="text-muted-foreground hover:underline"
onClick={() => { onClick={() => {
setEvents([event.name]); setEvents([event.name]);
popModal(); popModal();
}} }}
type="button"
> >
Show all Show all
</button> </button>
</div> </div>
<div className="card p-4"> <div className="card p-4">
<ReportChartShortcut <ReportChartShortcut
projectId={event.projectId}
chartType="linear" chartType="linear"
projectId={event.projectId}
series={[ series={[
{ {
id: 'A', id: 'A',
@@ -365,52 +364,52 @@ function EventDetailsSkeleton() {
<> <>
<WidgetHead> <WidgetHead>
<div className="row items-center justify-between"> <div className="row items-center justify-between">
<div className="h-6 w-32 bg-muted animate-pulse rounded" /> <div className="h-6 w-32 animate-pulse rounded bg-muted" />
<div className="row items-center gap-2 pr-2"> <div className="row items-center gap-2 pr-2">
<div className="h-8 w-8 bg-muted animate-pulse rounded" /> <div className="h-8 w-8 animate-pulse rounded bg-muted" />
<div className="h-8 w-8 bg-muted animate-pulse rounded" /> <div className="h-8 w-8 animate-pulse rounded bg-muted" />
<div className="h-8 w-8 bg-muted animate-pulse rounded" /> <div className="h-8 w-8 animate-pulse rounded bg-muted" />
</div> </div>
</div> </div>
<WidgetButtons> <WidgetButtons>
<div className="h-8 w-20 bg-muted animate-pulse rounded" /> <div className="h-8 w-20 animate-pulse rounded bg-muted" />
<div className="h-8 w-20 bg-muted animate-pulse rounded" /> <div className="h-8 w-20 animate-pulse rounded bg-muted" />
</WidgetButtons> </WidgetButtons>
</WidgetHead> </WidgetHead>
<WidgetBody className="col gap-4 bg-def-100"> <WidgetBody className="col gap-4 bg-def-100">
{/* Profile skeleton */} {/* Profile skeleton */}
<div className="card p-4 py-2 col gap-2"> <div className="card col gap-2 p-4 py-2">
<div className="row items-center gap-2 justify-between"> <div className="row items-center justify-between gap-2">
<div className="row items-center gap-2 min-w-0"> <div className="row min-w-0 items-center gap-2">
<div className="size-4 bg-muted animate-pulse rounded-full" /> <div className="size-4 animate-pulse rounded-full bg-muted" />
<div className="h-4 w-24 bg-muted animate-pulse rounded" /> <div className="h-4 w-24 animate-pulse rounded bg-muted" />
</div> </div>
<div className="row items-center gap-2 shrink-0"> <div className="row shrink-0 items-center gap-2">
<div className="row gap-1 items-center"> <div className="row items-center gap-1">
<div className="size-4 bg-muted animate-pulse rounded" /> <div className="size-4 animate-pulse rounded bg-muted" />
<div className="size-4 bg-muted animate-pulse rounded" /> <div className="size-4 animate-pulse rounded bg-muted" />
<div className="size-4 bg-muted animate-pulse rounded" /> <div className="size-4 animate-pulse rounded bg-muted" />
</div> </div>
<div className="h-4 w-32 bg-muted animate-pulse rounded" /> <div className="h-4 w-32 animate-pulse rounded bg-muted" />
</div> </div>
</div> </div>
<div className="h-4 w-64 bg-muted animate-pulse rounded" /> <div className="h-4 w-64 animate-pulse rounded bg-muted" />
</div> </div>
{/* Properties skeleton */} {/* Properties skeleton */}
<section> <section>
<div className="mb-2 flex justify-between font-medium"> <div className="mb-2 flex justify-between font-medium">
<div className="h-5 w-20 bg-muted animate-pulse rounded" /> <div className="h-5 w-20 animate-pulse rounded bg-muted" />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
{Array.from({ length: 3 }).map((_, i) => ( {Array.from({ length: 3 }).map((_, i) => (
<div <div
className="flex items-center justify-between rounded bg-muted/50 p-3"
key={i.toString()} key={i.toString()}
className="flex items-center justify-between p-3 bg-muted/50 rounded"
> >
<div className="h-4 w-24 bg-muted animate-pulse rounded" /> <div className="h-4 w-24 animate-pulse rounded bg-muted" />
<div className="h-4 w-32 bg-muted animate-pulse rounded" /> <div className="h-4 w-32 animate-pulse rounded bg-muted" />
</div> </div>
))} ))}
</div> </div>
@@ -419,16 +418,16 @@ function EventDetailsSkeleton() {
{/* Information skeleton */} {/* Information skeleton */}
<section> <section>
<div className="mb-2 flex justify-between font-medium"> <div className="mb-2 flex justify-between font-medium">
<div className="h-5 w-24 bg-muted animate-pulse rounded" /> <div className="h-5 w-24 animate-pulse rounded bg-muted" />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
{Array.from({ length: 6 }).map((_, i) => ( {Array.from({ length: 6 }).map((_, i) => (
<div <div
className="flex items-center justify-between rounded bg-muted/50 p-3"
key={i.toString()} key={i.toString()}
className="flex items-center justify-between p-3 bg-muted/50 rounded"
> >
<div className="h-4 w-20 bg-muted animate-pulse rounded" /> <div className="h-4 w-20 animate-pulse rounded bg-muted" />
<div className="h-4 w-28 bg-muted animate-pulse rounded" /> <div className="h-4 w-28 animate-pulse rounded bg-muted" />
</div> </div>
))} ))}
</div> </div>
@@ -437,11 +436,11 @@ function EventDetailsSkeleton() {
{/* Chart skeleton */} {/* Chart skeleton */}
<section> <section>
<div className="mb-2 flex justify-between font-medium"> <div className="mb-2 flex justify-between font-medium">
<div className="h-5 w-40 bg-muted animate-pulse rounded" /> <div className="h-5 w-40 animate-pulse rounded bg-muted" />
<div className="h-4 w-16 bg-muted animate-pulse rounded" /> <div className="h-4 w-16 animate-pulse rounded bg-muted" />
</div> </div>
<div className="card p-4"> <div className="card p-4">
<div className="h-32 w-full bg-muted animate-pulse rounded" /> <div className="h-32 w-full animate-pulse rounded bg-muted" />
</div> </div>
</section> </section>
</WidgetBody> </WidgetBody>

View File

@@ -1,3 +1,6 @@
import type { IServiceEvent, IServiceSession } from '@openpanel/db';
import { useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute, Link } from '@tanstack/react-router';
import { EventIcon } from '@/components/events/event-icon'; import { EventIcon } from '@/components/events/event-icon';
import FullPageLoadingState from '@/components/full-page-loading-state'; import FullPageLoadingState from '@/components/full-page-loading-state';
import { PageContainer } from '@/components/page-container'; import { PageContainer } from '@/components/page-container';
@@ -6,18 +9,20 @@ import { ProfileAvatar } from '@/components/profiles/profile-avatar';
import { SerieIcon } from '@/components/report-chart/common/serie-icon'; import { SerieIcon } from '@/components/report-chart/common/serie-icon';
import { ReplayShell } from '@/components/sessions/replay'; import { ReplayShell } from '@/components/sessions/replay';
import { KeyValueGrid } from '@/components/ui/key-value-grid'; import { KeyValueGrid } from '@/components/ui/key-value-grid';
import { Widget, WidgetBody, WidgetHead, WidgetTitle } from '@/components/widget'; import {
Widget,
WidgetBody,
WidgetHead,
WidgetTitle,
} from '@/components/widget';
import { useNumber } from '@/hooks/use-numer-formatter';
import { useTRPC } from '@/integrations/trpc/react'; import { useTRPC } from '@/integrations/trpc/react';
import { formatDateTime } from '@/utils/date'; import { formatDateTime } from '@/utils/date';
import { getProfileName } from '@/utils/getters'; import { getProfileName } from '@/utils/getters';
import { useNumber } from '@/hooks/use-numer-formatter';
import { createProjectTitle } from '@/utils/title'; import { createProjectTitle } from '@/utils/title';
import { useSuspenseQuery } from '@tanstack/react-query';
import { Link, createFileRoute } from '@tanstack/react-router';
import type { IServiceEvent, IServiceSession } from '@openpanel/db';
export const Route = createFileRoute( export const Route = createFileRoute(
'/_app/$organizationId/$projectId/sessions_/$sessionId', '/_app/$organizationId/$projectId/sessions_/$sessionId'
)({ )({
component: Component, component: Component,
loader: async ({ context, params }) => { loader: async ({ context, params }) => {
@@ -26,7 +31,7 @@ export const Route = createFileRoute(
context.trpc.session.byId.queryOptions({ context.trpc.session.byId.queryOptions({
sessionId: params.sessionId, sessionId: params.sessionId,
projectId: params.projectId, projectId: params.projectId,
}), })
), ),
context.queryClient.prefetchQuery( context.queryClient.prefetchQuery(
context.trpc.event.events.queryOptions({ context.trpc.event.events.queryOptions({
@@ -34,7 +39,7 @@ export const Route = createFileRoute(
sessionId: params.sessionId, sessionId: params.sessionId,
filters: [], filters: [],
columnVisibility: {}, columnVisibility: {},
}), })
), ),
]); ]);
}, },
@@ -45,7 +50,19 @@ export const Route = createFileRoute(
}); });
function sessionToFakeEvent(session: IServiceSession): IServiceEvent { function sessionToFakeEvent(session: IServiceSession): IServiceEvent {
return session as unknown as IServiceEvent; return {
...session,
name: 'screen_view',
sessionId: session.id,
properties: {},
path: session.exitPath,
origin: session.exitOrigin,
importedAt: undefined,
meta: undefined,
sdkName: undefined,
sdkVersion: undefined,
profile: undefined,
};
} }
function VisitedRoutes({ paths }: { paths: string[] }) { function VisitedRoutes({ paths }: { paths: string[] }) {
@@ -56,7 +73,9 @@ function VisitedRoutes({ paths }: { paths: string[] }) {
const sorted = Object.entries(counted).sort((a, b) => b[1] - a[1]); const sorted = Object.entries(counted).sort((a, b) => b[1] - a[1]);
const max = sorted[0]?.[1] ?? 1; const max = sorted[0]?.[1] ?? 1;
if (sorted.length === 0) return null; if (sorted.length === 0) {
return null;
}
return ( return (
<Widget className="w-full"> <Widget className="w-full">
@@ -65,14 +84,14 @@ function VisitedRoutes({ paths }: { paths: string[] }) {
</WidgetHead> </WidgetHead>
<div className="flex flex-col gap-1 p-1"> <div className="flex flex-col gap-1 p-1">
{sorted.map(([path, count]) => ( {sorted.map(([path, count]) => (
<div key={path} className="relative px-3 py-2 group"> <div className="group relative px-3 py-2" key={path}>
<div <div
className="absolute bottom-0 left-0 top-0 rounded bg-def-200 group-hover:bg-def-300" className="absolute top-0 bottom-0 left-0 rounded bg-def-200 group-hover:bg-def-300"
style={{ width: `${(count / max) * 100}%` }} style={{ width: `${(count / max) * 100}%` }}
/> />
<div className="relative flex justify-between gap-2 min-w-0"> <div className="relative flex min-w-0 justify-between gap-2">
<span className="truncate text-sm">{path}</span> <span className="truncate text-sm">{path}</span>
<span className="shrink-0 text-sm font-medium">{count}</span> <span className="shrink-0 font-medium text-sm">{count}</span>
</div> </div>
</div> </div>
))} ))}
@@ -89,7 +108,9 @@ function EventDistribution({ events }: { events: IServiceEvent[] }) {
const sorted = Object.entries(counted).sort((a, b) => b[1] - a[1]); const sorted = Object.entries(counted).sort((a, b) => b[1] - a[1]);
const max = sorted[0]?.[1] ?? 1; const max = sorted[0]?.[1] ?? 1;
if (sorted.length === 0) return null; if (sorted.length === 0) {
return null;
}
return ( return (
<Widget className="w-full"> <Widget className="w-full">
@@ -98,14 +119,14 @@ function EventDistribution({ events }: { events: IServiceEvent[] }) {
</WidgetHead> </WidgetHead>
<div className="flex flex-col gap-1 p-1"> <div className="flex flex-col gap-1 p-1">
{sorted.map(([name, count]) => ( {sorted.map(([name, count]) => (
<div key={name} className="relative px-3 py-2 group"> <div className="group relative px-3 py-2" key={name}>
<div <div
className="absolute bottom-0 left-0 top-0 rounded bg-def-200 group-hover:bg-def-300" className="absolute top-0 bottom-0 left-0 rounded bg-def-200 group-hover:bg-def-300"
style={{ width: `${(count / max) * 100}%` }} style={{ width: `${(count / max) * 100}%` }}
/> />
<div className="relative flex justify-between gap-2"> <div className="relative flex justify-between gap-2">
<span className="text-sm">{name.replace(/_/g, ' ')}</span> <span className="text-sm">{name.replace(/_/g, ' ')}</span>
<span className="shrink-0 text-sm font-medium">{count}</span> <span className="shrink-0 font-medium text-sm">{count}</span>
</div> </div>
</div> </div>
))} ))}
@@ -117,10 +138,10 @@ function EventDistribution({ events }: { events: IServiceEvent[] }) {
function Component() { function Component() {
const { projectId, sessionId, organizationId } = Route.useParams(); const { projectId, sessionId, organizationId } = Route.useParams();
const trpc = useTRPC(); const trpc = useTRPC();
const number = useNumber() const number = useNumber();
const { data: session } = useSuspenseQuery( const { data: session } = useSuspenseQuery(
trpc.session.byId.queryOptions({ sessionId, projectId }), trpc.session.byId.queryOptions({ sessionId, projectId })
); );
const { data: eventsData } = useSuspenseQuery( const { data: eventsData } = useSuspenseQuery(
@@ -129,7 +150,7 @@ function Component() {
sessionId, sessionId,
filters: [], filters: [],
columnVisibility: {}, columnVisibility: {},
}), })
); );
const events = eventsData?.data ?? []; const events = eventsData?.data ?? [];
@@ -141,83 +162,54 @@ function Component() {
trpc.profile.byId.queryOptions({ trpc.profile.byId.queryOptions({
profileId: session.profileId, profileId: session.profileId,
projectId, projectId,
}), })
); );
const fakeEvent = sessionToFakeEvent(session); const fakeEvent = sessionToFakeEvent(session);
return ( return (
<PageContainer className="col gap-8"> <PageContainer className="col gap-8">
<PageHeader <PageHeader title={`Session: ${session.id}`}>
title={`Session: ${session.id}`} <div className="row mb-6 gap-4">
> {session.country && (
<div className="row gap-4 mb-6"> <div className="row items-center gap-2">
{session.country && ( <SerieIcon name={session.country} />
<div className="row gap-2 items-center"> <span>
<SerieIcon name={session.country} /> {session.country}
<span> {session.city && ` / ${session.city}`}
{session.country} </span>
{session.city && ` / ${session.city}`}
</span>
</div>
)}
{session.device && (
<div className="row gap-2 items-center">
<SerieIcon name={session.device} />
<span className="capitalize">{session.device}</span>
</div>
)}
{session.os && (
<div className="row gap-2 items-center">
<SerieIcon name={session.os} />
<span>{session.os}</span>
</div>
)}
{session.model && (
<div className="row gap-2 items-center">
<SerieIcon name={session.model} />
<span>{session.model}</span>
</div>
)}
{session.browser && (
<div className="row gap-2 items-center">
<SerieIcon name={session.browser} />
<span>{session.browser}</span>
</div> </div>
)} )}
{session.device && (
<div className="row items-center gap-2">
<SerieIcon name={session.device} />
<span className="capitalize">{session.device}</span>
</div> </div>
)}
{session.os && (
<div className="row items-center gap-2">
<SerieIcon name={session.os} />
<span>{session.os}</span>
</div>
)}
{session.model && (
<div className="row items-center gap-2">
<SerieIcon name={session.model} />
<span>{session.model}</span>
</div>
)}
{session.browser && (
<div className="row items-center gap-2">
<SerieIcon name={session.browser} />
<span>{session.browser}</span>
</div>
)}
</div>
</PageHeader> </PageHeader>
{session.hasReplay && <ReplayShell sessionId={sessionId} projectId={projectId} />} {session.hasReplay && (
<ReplayShell projectId={projectId} sessionId={sessionId} />
)}
<div className="grid grid-cols-1 gap-6 lg:grid-cols-[340px_minmax(0,1fr)]"> <div className="grid grid-cols-1 gap-6 lg:grid-cols-[340px_minmax(0,1fr)]">
{/* Left column */} {/* Left column */}
@@ -232,7 +224,10 @@ function Component() {
columns={1} columns={1}
copyable copyable
data={[ data={[
{ name: 'duration', value: number.formatWithUnit(session.duration/1000, 'min') }, {
name: 'duration',
value: number.formatWithUnit(session.duration / 1000, 'min'),
},
{ name: 'createdAt', value: session.createdAt }, { name: 'createdAt', value: session.createdAt },
{ name: 'endedAt', value: session.endedAt }, { name: 'endedAt', value: session.endedAt },
{ name: 'screenViews', value: session.screenViewCount }, { name: 'screenViews', value: session.screenViewCount },
@@ -305,13 +300,13 @@ function Component() {
</WidgetHead> </WidgetHead>
<WidgetBody className="p-0"> <WidgetBody className="p-0">
<Link <Link
to="/$organizationId/$projectId/profiles/$profileId" className="row items-center gap-3 p-4 transition-colors hover:bg-accent"
params={{ params={{
organizationId, organizationId,
projectId, projectId,
profileId: session.profileId, profileId: session.profileId,
}} }}
className="row items-center gap-3 p-4 transition-colors hover:bg-accent" to="/$organizationId/$projectId/profiles/$profileId"
> >
<ProfileAvatar {...profile} size="lg" /> <ProfileAvatar {...profile} size="lg" />
<div className="col min-w-0 gap-0.5"> <div className="col min-w-0 gap-0.5">
@@ -319,7 +314,7 @@ function Component() {
{getProfileName(profile, false) ?? session.profileId} {getProfileName(profile, false) ?? session.profileId}
</span> </span>
{profile.email && ( {profile.email && (
<span className="truncate text-sm text-muted-foreground"> <span className="truncate text-muted-foreground text-sm">
{profile.email} {profile.email}
</span> </span>
)} )}
@@ -350,24 +345,24 @@ function Component() {
<div className="divide-y"> <div className="divide-y">
{events.map((event) => ( {events.map((event) => (
<div <div
key={event.id}
className="row items-center gap-3 px-4 py-2" className="row items-center gap-3 px-4 py-2"
key={event.id}
> >
<EventIcon name={event.name} meta={event.meta} size="sm" /> <EventIcon meta={event.meta} name={event.name} size="sm" />
<div className="col min-w-0 flex-1"> <div className="col min-w-0 flex-1">
<span className="truncate text-sm font-medium"> <span className="truncate font-medium text-sm">
{event.name === 'screen_view' && event.path {event.name === 'screen_view' && event.path
? event.path ? event.path
: event.name.replace(/_/g, ' ')} : event.name.replace(/_/g, ' ')}
</span> </span>
</div> </div>
<span className="shrink-0 text-xs tabular-nums text-muted-foreground"> <span className="shrink-0 text-muted-foreground text-xs tabular-nums">
{formatDateTime(event.createdAt)} {formatDateTime(event.createdAt)}
</span> </span>
</div> </div>
))} ))}
{events.length === 0 && ( {events.length === 0 && (
<div className="py-8 text-center text-sm text-muted-foreground"> <div className="py-8 text-center text-muted-foreground text-sm">
No events found No events found
</div> </div>
)} )}

View File

@@ -52,7 +52,7 @@ async function createEventAndNotify(
logger.info('Creating event', { event: payload }); logger.info('Creating event', { event: payload });
const [event] = await Promise.all([ const [event] = await Promise.all([
createEvent(payload), createEvent(payload),
checkNotificationRulesForEvent(payload).catch(() => {}), checkNotificationRulesForEvent(payload).catch(() => null),
]); ]);
return event; return event;

View File

@@ -32,6 +32,8 @@ const SESSION_TIMEOUT = 30 * 60 * 1000;
const projectId = 'test-project'; const projectId = 'test-project';
const currentDeviceId = 'device-123'; const currentDeviceId = 'device-123';
const previousDeviceId = 'device-456'; const previousDeviceId = 'device-456';
// Valid UUID used when creating a new session in tests
const newSessionId = 'a1b2c3d4-e5f6-4789-a012-345678901234';
const geo = { const geo = {
country: 'US', country: 'US',
city: 'New York', city: 'New York',
@@ -67,7 +69,7 @@ describe('incomingEvent', () => {
vi.clearAllMocks(); vi.clearAllMocks();
}); });
it.only('should create a session start and an event', async () => { it('should create a session start and an event', async () => {
const spySessionsQueueAdd = vi.spyOn(sessionsQueue, 'add'); const spySessionsQueueAdd = vi.spyOn(sessionsQueue, 'add');
const timestamp = new Date(); const timestamp = new Date();
// Mock job data // Mock job data
@@ -90,12 +92,15 @@ describe('incomingEvent', () => {
projectId, projectId,
currentDeviceId, currentDeviceId,
previousDeviceId, previousDeviceId,
deviceId: currentDeviceId,
sessionId: newSessionId,
}; };
const event = { const event = {
name: 'test_event', name: 'test_event',
deviceId: currentDeviceId, deviceId: currentDeviceId,
profileId: '', profileId: '',
sessionId: expect.stringMatching( sessionId: expect.stringMatching(
// biome-ignore lint/performance/useTopLevelRegex: test
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
), ),
projectId, projectId,
@@ -182,6 +187,8 @@ describe('incomingEvent', () => {
projectId, projectId,
currentDeviceId, currentDeviceId,
previousDeviceId, previousDeviceId,
deviceId: currentDeviceId,
sessionId: 'session-123',
}; };
const changeDelay = vi.fn(); const changeDelay = vi.fn();
@@ -263,6 +270,8 @@ describe('incomingEvent', () => {
projectId, projectId,
currentDeviceId: '', currentDeviceId: '',
previousDeviceId: '', previousDeviceId: '',
deviceId: '',
sessionId: '',
uaInfo: uaInfoServer, uaInfo: uaInfoServer,
}; };
@@ -367,6 +376,8 @@ describe('incomingEvent', () => {
projectId, projectId,
currentDeviceId: '', currentDeviceId: '',
previousDeviceId: '', previousDeviceId: '',
deviceId: '',
sessionId: '',
uaInfo: uaInfoServer, uaInfo: uaInfoServer,
}; };

View File

@@ -1,8 +1,7 @@
import { type Redis, getRedisCache } from '@openpanel/redis';
import { getSafeJson } from '@openpanel/json'; import { getSafeJson } from '@openpanel/json';
import { getRedisCache, type Redis } from '@openpanel/redis';
import { assocPath, clone } from 'ramda'; import { assocPath, clone } from 'ramda';
import { TABLE_NAMES, ch } from '../clickhouse/client'; import { ch, TABLE_NAMES } from '../clickhouse/client';
import type { IClickhouseEvent } from '../services/event.service'; import type { IClickhouseEvent } from '../services/event.service';
import type { IClickhouseSession } from '../services/session.service'; import type { IClickhouseSession } from '../services/session.service';
import { BaseBuffer } from './base-buffer'; import { BaseBuffer } from './base-buffer';
@@ -35,14 +34,14 @@ export class SessionBuffer extends BaseBuffer {
| { | {
projectId: string; projectId: string;
profileId: string; profileId: string;
}, }
) { ) {
let hit: string | null = null; let hit: string | null = null;
if ('sessionId' in options) { if ('sessionId' in options) {
hit = await this.redis.get(`session:${options.sessionId}`); hit = await this.redis.get(`session:${options.sessionId}`);
} else { } else {
hit = await this.redis.get( hit = await this.redis.get(
`session:${options.projectId}:${options.profileId}`, `session:${options.projectId}:${options.profileId}`
); );
} }
@@ -54,7 +53,7 @@ export class SessionBuffer extends BaseBuffer {
} }
async getSession( async getSession(
event: IClickhouseEvent, event: IClickhouseEvent
): Promise<[IClickhouseSession] | [IClickhouseSession, IClickhouseSession]> { ): Promise<[IClickhouseSession] | [IClickhouseSession, IClickhouseSession]> {
const existingSession = await this.getExistingSession({ const existingSession = await this.getExistingSession({
sessionId: event.session_id, sessionId: event.session_id,
@@ -186,14 +185,14 @@ export class SessionBuffer extends BaseBuffer {
`session:${newSession.id}`, `session:${newSession.id}`,
JSON.stringify(newSession), JSON.stringify(newSession),
'EX', 'EX',
60 * 60, 60 * 60
); );
if (newSession.profile_id) { if (newSession.profile_id) {
multi.set( multi.set(
`session:${newSession.project_id}:${newSession.profile_id}`, `session:${newSession.project_id}:${newSession.profile_id}`,
JSON.stringify(newSession), JSON.stringify(newSession),
'EX', 'EX',
60 * 60, 60 * 60
); );
} }
for (const session of sessions) { for (const session of sessions) {
@@ -220,10 +219,12 @@ export class SessionBuffer extends BaseBuffer {
const events = await this.redis.lrange( const events = await this.redis.lrange(
this.redisKey, this.redisKey,
0, 0,
this.batchSize - 1, this.batchSize - 1
); );
if (events.length === 0) return; if (events.length === 0) {
return;
}
const sessions = events const sessions = events
.map((e) => getSafeJson<IClickhouseSession>(e)) .map((e) => getSafeJson<IClickhouseSession>(e))
@@ -258,7 +259,7 @@ export class SessionBuffer extends BaseBuffer {
} }
} }
async getBufferSize() { getBufferSize() {
return this.getBufferSizeWithCounter(() => this.redis.llen(this.redisKey)); return this.getBufferSizeWithCounter(() => this.redis.llen(this.redisKey));
} }
} }

View File

@@ -1,3 +1,4 @@
import { getSafeJson } from '@openpanel/json';
import { cacheable } from '@openpanel/redis'; import { cacheable } from '@openpanel/redis';
import type { IChartEventFilter } from '@openpanel/validation'; import type { IChartEventFilter } from '@openpanel/validation';
import sqlstring from 'sqlstring'; import sqlstring from 'sqlstring';
@@ -14,7 +15,7 @@ import { getEventFiltersWhereClause } from './chart.service';
import { getOrganizationByProjectIdCached } from './organization.service'; import { getOrganizationByProjectIdCached } from './organization.service';
import { getProfilesCached, type IServiceProfile } from './profile.service'; import { getProfilesCached, type IServiceProfile } from './profile.service';
export type IClickhouseSession = { export interface IClickhouseSession {
id: string; id: string;
profile_id: string; profile_id: string;
event_count: number; event_count: number;
@@ -53,8 +54,9 @@ export type IClickhouseSession = {
revenue: number; revenue: number;
sign: 1 | 0; sign: 1 | 0;
version: number; version: number;
has_replay: boolean; // Dynamically added
}; has_replay?: boolean;
}
export interface IServiceSession { export interface IServiceSession {
id: string; id: string;
@@ -92,8 +94,8 @@ export interface IServiceSession {
utmContent: string; utmContent: string;
utmTerm: string; utmTerm: string;
revenue: number; revenue: number;
hasReplay: boolean;
profile?: IServiceProfile; profile?: IServiceProfile;
hasReplay?: boolean;
} }
export interface GetSessionListOptions { export interface GetSessionListOptions {
@@ -144,21 +146,19 @@ export function transformSession(session: IClickhouseSession): IServiceSession {
utmContent: session.utm_content, utmContent: session.utm_content,
utmTerm: session.utm_term, utmTerm: session.utm_term,
revenue: session.revenue, revenue: session.revenue,
hasReplay: session.has_replay,
profile: undefined, profile: undefined,
hasReplay: session.has_replay,
}; };
} }
type Direction = 'initial' | 'next' | 'prev'; interface PageInfo {
type PageInfo = {
next?: Cursor; // use last row next?: Cursor; // use last row
}; }
type Cursor = { interface Cursor {
createdAt: string; // ISO 8601 with ms createdAt: string; // ISO 8601 with ms
id: string; id: string;
}; }
export async function getSessionList({ export async function getSessionList({
cursor, cursor,
@@ -238,13 +238,14 @@ export async function getSessionList({
sb.select[column] = column; sb.select[column] = column;
}); });
sb.select.has_replay = `toBool(src.session_id != '') as has_replay`; sb.select.has_replay = `toBool(src.session_id != '') as hasReplay`;
sb.joins.has_replay = `LEFT JOIN (SELECT DISTINCT session_id FROM ${TABLE_NAMES.session_replay_chunks} WHERE project_id = ${sqlstring.escape(projectId)} AND started_at > now() - INTERVAL ${dateIntervalInDays} DAY) AS src ON src.session_id = id`; sb.joins.has_replay = `LEFT JOIN (SELECT DISTINCT session_id FROM ${TABLE_NAMES.session_replay_chunks} WHERE project_id = ${sqlstring.escape(projectId)} AND started_at > now() - INTERVAL ${dateIntervalInDays} DAY) AS src ON src.session_id = id`;
const sql = getSql(); const sql = getSql();
const data = await chQuery< const data = await chQuery<
IClickhouseSession & { IClickhouseSession & {
latestCreatedAt: string; latestCreatedAt: string;
hasReplay: boolean;
} }
>(sql); >(sql);
@@ -347,20 +348,24 @@ export async function getSessionReplayChunksFrom(
FROM ${TABLE_NAMES.session_replay_chunks} FROM ${TABLE_NAMES.session_replay_chunks}
WHERE session_id = ${sqlstring.escape(sessionId)} WHERE session_id = ${sqlstring.escape(sessionId)}
AND project_id = ${sqlstring.escape(projectId)} AND project_id = ${sqlstring.escape(projectId)}
ORDER BY started_at, ended_at ORDER BY started_at, ended_at, chunk_index
LIMIT ${REPLAY_CHUNKS_PAGE_SIZE + 1} LIMIT ${REPLAY_CHUNKS_PAGE_SIZE + 1}
OFFSET ${fromIndex}` OFFSET ${fromIndex}`
); );
return { return {
data: rows.slice(0, REPLAY_CHUNKS_PAGE_SIZE).map((row, index) => ({ data: rows
chunkIndex: index + fromIndex, .slice(0, REPLAY_CHUNKS_PAGE_SIZE)
events: JSON.parse(row.payload) as { .map((row, index) => {
type: number; const events = getSafeJson<
data: unknown; { type: number; data: unknown; timestamp: number }[]
timestamp: number; >(row.payload);
}[], if (!events) {
})), return null;
}
return { chunkIndex: index + fromIndex, events };
})
.filter(Boolean),
hasMore: rows.length > REPLAY_CHUNKS_PAGE_SIZE, hasMore: rows.length > REPLAY_CHUNKS_PAGE_SIZE,
}; };
} }
@@ -369,19 +374,33 @@ class SessionService {
constructor(private client: typeof ch) {} constructor(private client: typeof ch) {}
async byId(sessionId: string, projectId: string) { async byId(sessionId: string, projectId: string) {
const result = await clix(this.client) const [sessionRows, hasReplayRows] = await Promise.all([
.select<IClickhouseSession>(['*']) clix(this.client)
.from(TABLE_NAMES.sessions) .select<IClickhouseSession>(['*'])
.where('id', '=', sessionId) .from(TABLE_NAMES.sessions, true)
.where('project_id', '=', projectId) .where('id', '=', sessionId)
.where('sign', '=', 1) .where('project_id', '=', projectId)
.execute(); .where('sign', '=', 1)
.execute(),
chQuery<{ n: number }>(
`SELECT 1 AS n
FROM ${TABLE_NAMES.session_replay_chunks}
WHERE session_id = ${sqlstring.escape(sessionId)}
AND project_id = ${sqlstring.escape(projectId)}
LIMIT 1`
),
]);
if (!result[0]) { if (!sessionRows[0]) {
throw new Error('Session not found'); throw new Error('Session not found');
} }
return transformSession(result[0]); const session = transformSession(sessionRows[0]);
return {
...session,
hasReplay: hasReplayRows.length > 0,
};
} }
} }

View File

@@ -4,12 +4,14 @@ import { getInitSnippet } from '@openpanel/web';
type Props = Omit<OpenPanelOptions, 'filter'> & { type Props = Omit<OpenPanelOptions, 'filter'> & {
profileId?: string; profileId?: string;
/** @deprecated Use `scriptUrl` instead. */
cdnUrl?: string; cdnUrl?: string;
scriptUrl?: string;
filter?: string; filter?: string;
globalProperties?: Record<string, unknown>; globalProperties?: Record<string, unknown>;
}; };
const { profileId, cdnUrl, globalProperties, ...options } = Astro.props; const { profileId, cdnUrl, scriptUrl, globalProperties, ...options } = Astro.props;
const CDN_URL = 'https://openpanel.dev/op1.js'; const CDN_URL = 'https://openpanel.dev/op1.js';
@@ -60,5 +62,5 @@ ${methods
.join('\n')}`; .join('\n')}`;
--- ---
<script src={cdnUrl ?? CDN_URL} async defer /> <script src={scriptUrl ?? cdnUrl ?? CDN_URL} async defer />
<script is:inline set:html={scriptContent} /> <script is:inline set:html={scriptContent} />

View File

@@ -1,8 +1,3 @@
// adding .js next/script import fixes an issues
// with esm and nextjs (when using pages dir)
import Script from 'next/script.js';
import React from 'react';
import type { import type {
DecrementPayload, DecrementPayload,
IdentifyPayload, IdentifyPayload,
@@ -12,6 +7,11 @@ import type {
TrackProperties, TrackProperties,
} from '@openpanel/web'; } from '@openpanel/web';
import { getInitSnippet } from '@openpanel/web'; import { getInitSnippet } from '@openpanel/web';
// adding .js next/script import fixes an issues
// with esm and nextjs (when using pages dir)
import Script from 'next/script.js';
// biome-ignore lint/correctness/noUnusedImports: nextjs requires this
import React from 'react';
export * from '@openpanel/web'; export * from '@openpanel/web';
@@ -19,7 +19,9 @@ const CDN_URL = 'https://openpanel.dev/op1.js';
type OpenPanelComponentProps = Omit<OpenPanelOptions, 'filter'> & { type OpenPanelComponentProps = Omit<OpenPanelOptions, 'filter'> & {
profileId?: string; profileId?: string;
/** @deprecated Use `scriptUrl` instead. */
cdnUrl?: string; cdnUrl?: string;
scriptUrl?: string;
filter?: string; filter?: string;
globalProperties?: Record<string, unknown>; globalProperties?: Record<string, unknown>;
strategy?: 'beforeInteractive' | 'afterInteractive' | 'lazyOnload' | 'worker'; strategy?: 'beforeInteractive' | 'afterInteractive' | 'lazyOnload' | 'worker';
@@ -42,6 +44,7 @@ const stringify = (obj: unknown) => {
export function OpenPanelComponent({ export function OpenPanelComponent({
profileId, profileId,
cdnUrl, cdnUrl,
scriptUrl,
globalProperties, globalProperties,
strategy = 'afterInteractive', strategy = 'afterInteractive',
...options ...options
@@ -80,10 +83,8 @@ export function OpenPanelComponent({
return ( return (
<> <>
<Script src={appendVersion(cdnUrl || CDN_URL)} async defer /> <Script async defer src={appendVersion(scriptUrl || cdnUrl || CDN_URL)} />
<Script <Script
id="openpanel-init"
strategy={strategy}
dangerouslySetInnerHTML={{ dangerouslySetInnerHTML={{
__html: `${getInitSnippet()} __html: `${getInitSnippet()}
${methods ${methods
@@ -92,6 +93,8 @@ export function OpenPanelComponent({
}) })
.join('\n')}`, .join('\n')}`,
}} }}
id="openpanel-init"
strategy={strategy}
/> />
</> </>
); );
@@ -101,25 +104,21 @@ type IdentifyComponentProps = IdentifyPayload;
export function IdentifyComponent(props: IdentifyComponentProps) { export function IdentifyComponent(props: IdentifyComponentProps) {
return ( return (
<> <Script
<Script dangerouslySetInnerHTML={{
dangerouslySetInnerHTML={{ __html: `window.op('identify', ${JSON.stringify(props)});`,
__html: `window.op('identify', ${JSON.stringify(props)});`, }}
}} />
/>
</>
); );
} }
export function SetGlobalPropertiesComponent(props: Record<string, unknown>) { export function SetGlobalPropertiesComponent(props: Record<string, unknown>) {
return ( return (
<> <Script
<Script dangerouslySetInnerHTML={{
dangerouslySetInnerHTML={{ __html: `window.op('setGlobalProperties', ${JSON.stringify(props)});`,
__html: `window.op('setGlobalProperties', ${JSON.stringify(props)});`, }}
}} />
/>
</>
); );
} }
@@ -152,7 +151,7 @@ function screenView(properties?: TrackProperties): void;
function screenView(path: string, properties?: TrackProperties): void; function screenView(path: string, properties?: TrackProperties): void;
function screenView( function screenView(
pathOrProperties?: string | TrackProperties, pathOrProperties?: string | TrackProperties,
propertiesOrUndefined?: TrackProperties, propertiesOrUndefined?: TrackProperties
) { ) {
window.op?.('screenView', pathOrProperties, propertiesOrUndefined); window.op?.('screenView', pathOrProperties, propertiesOrUndefined);
} }

View File

@@ -176,7 +176,7 @@ export class OpenPanel {
async revenue( async revenue(
amount: number, amount: number,
properties?: TrackProperties & { deviceId?: string }, properties?: TrackProperties & { deviceId?: string }
) { ) {
const deviceId = properties?.deviceId; const deviceId = properties?.deviceId;
delete properties?.deviceId; delete properties?.deviceId;
@@ -195,7 +195,10 @@ export class OpenPanel {
return this.sessionId ?? ''; return this.sessionId ?? '';
} }
async fetchDeviceId(): Promise<string> { /**
* @deprecated Use `getDeviceId()` instead. This async method is no longer needed.
*/
fetchDeviceId(): Promise<string> {
return Promise.resolve(this.deviceId ?? ''); return Promise.resolve(this.deviceId ?? '');
} }

View File

@@ -1,12 +1,10 @@
import { z } from 'zod';
import { import {
getSessionList, getSessionList,
getSessionReplayChunksFrom, getSessionReplayChunksFrom,
sessionService, sessionService,
} from '@openpanel/db'; } from '@openpanel/db';
import { zChartEventFilter } from '@openpanel/validation'; import { zChartEventFilter } from '@openpanel/validation';
import { z } from 'zod';
import { createTRPCRouter, protectedProcedure } from '../trpc'; import { createTRPCRouter, protectedProcedure } from '../trpc';
export function encodeCursor(cursor: { export function encodeCursor(cursor: {
@@ -18,7 +16,7 @@ export function encodeCursor(cursor: {
} }
export function decodeCursor( export function decodeCursor(
encoded: string, encoded: string
): { createdAt: string; id: string } | null { ): { createdAt: string; id: string } | null {
try { try {
const json = Buffer.from(encoded, 'base64url').toString('utf8'); const json = Buffer.from(encoded, 'base64url').toString('utf8');
@@ -44,7 +42,7 @@ export const sessionRouter = createTRPCRouter({
endDate: z.date().optional(), endDate: z.date().optional(),
search: z.string().optional(), search: z.string().optional(),
take: z.number().default(50), take: z.number().default(50),
}), })
) )
.query(async ({ input }) => { .query(async ({ input }) => {
const cursor = input.cursor ? decodeCursor(input.cursor) : null; const cursor = input.cursor ? decodeCursor(input.cursor) : null;
@@ -62,7 +60,7 @@ export const sessionRouter = createTRPCRouter({
byId: protectedProcedure byId: protectedProcedure
.input(z.object({ sessionId: z.string(), projectId: z.string() })) .input(z.object({ sessionId: z.string(), projectId: z.string() }))
.query(async ({ input: { sessionId, projectId } }) => { .query(({ input: { sessionId, projectId } }) => {
return sessionService.byId(sessionId, projectId); return sessionService.byId(sessionId, projectId);
}), }),
@@ -72,9 +70,9 @@ export const sessionRouter = createTRPCRouter({
sessionId: z.string(), sessionId: z.string(),
projectId: z.string(), projectId: z.string(),
fromIndex: z.number().int().min(0).default(0), fromIndex: z.number().int().min(0).default(0),
}), })
) )
.query(async ({ input: { sessionId, projectId, fromIndex } }) => { .query(({ input: { sessionId, projectId, fromIndex } }) => {
return getSessionReplayChunksFrom(sessionId, projectId, fromIndex); return getSessionReplayChunksFrom(sessionId, projectId, fromIndex);
}), }),
}); });

View File

@@ -67,9 +67,9 @@ export const zReplayPayload = z.object({
chunk_index: z.number().int().min(0).max(65_535), chunk_index: z.number().int().min(0).max(65_535),
events_count: z.number().int().min(1), events_count: z.number().int().min(1),
is_full_snapshot: z.boolean(), is_full_snapshot: z.boolean(),
started_at: z.string(), started_at: z.string().datetime(),
ended_at: z.string(), ended_at: z.string().datetime(),
payload: z.string().max(1_048_576 * 2), // 1MB max payload: z.string().max(1_048_576 * 2), // 2MB max
}); });
export const zTrackHandlerPayload = z.discriminatedUnion('type', [ export const zTrackHandlerPayload = z.discriminatedUnion('type', [