11import { PostHog } from 'posthog-node'
22import { env } from '@sourcebot/shared'
3+ import { env as clientEnv } from '@sourcebot/shared/client' ;
34import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies' ;
45import * as Sentry from "@sentry/nextjs" ;
56import { PosthogEvent , PosthogEventMap } from './posthogEvents' ;
6- import { cookies } from 'next/headers' ;
7+ import { cookies , headers } from 'next/headers' ;
8+ import { auth } from '@/auth' ;
9+ import { getVerifiedApiObject } from '@/withAuthV2' ;
710
811/**
912 * @note : This is a subset of the properties stored in the
@@ -47,13 +50,40 @@ const getPostHogCookie = (cookieStore: Pick<RequestCookies, 'get'>): PostHogCook
4750 return undefined ;
4851}
4952
53+ /**
54+ * Attempts to retrieve the distinct id of the current user.
55+ */
56+ const tryGetDistinctId = async ( ) => {
57+ // First, attempt to retrieve the distinct id from the cookie.
58+ const cookieStore = await cookies ( ) ;
59+ const cookie = getPostHogCookie ( cookieStore ) ;
60+ if ( cookie ) {
61+ return cookie . distinct_id ;
62+ }
63+
64+ // Next, from the session.
65+ const session = await auth ( ) ;
66+ if ( session ) {
67+ return session . user . id ;
68+ }
69+
70+ // Finally, from the api key.
71+ const headersList = await headers ( ) ;
72+ const apiKeyString = headersList . get ( "X-Sourcebot-Api-Key" ) ?? undefined ;
73+ if ( ! apiKeyString ) {
74+ return undefined ;
75+ }
76+
77+ const apiKey = await getVerifiedApiObject ( apiKeyString ) ;
78+ return apiKey ?. createdById ;
79+ }
80+
5081export async function captureEvent < E extends PosthogEvent > ( event : E , properties : PosthogEventMap [ E ] ) {
5182 if ( env . SOURCEBOT_TELEMETRY_DISABLED === 'true' ) {
5283 return ;
5384 }
5485
55- const cookieStore = await cookies ( ) ;
56- const cookie = getPostHogCookie ( cookieStore ) ;
86+ const distinctId = await tryGetDistinctId ( ) ;
5787
5888 const posthog = new PostHog ( env . POSTHOG_PAPIK , {
5989 host : 'https://us.i.posthog.com' ,
@@ -63,7 +93,11 @@ export async function captureEvent<E extends PosthogEvent>(event: E, properties:
6393
6494 posthog . capture ( {
6595 event,
66- properties,
67- distinctId : cookie ?. distinct_id ?? '' ,
96+ properties : {
97+ ...properties ,
98+ sourcebot_version : clientEnv . NEXT_PUBLIC_SOURCEBOT_VERSION ,
99+ install_id : env . SOURCEBOT_INSTALL_ID ,
100+ } ,
101+ distinctId,
68102 } ) ;
69103}
0 commit comments