-
Notifications
You must be signed in to change notification settings - Fork 760
Expand file tree
/
Copy pathanalytics.ts
More file actions
93 lines (84 loc) · 2.26 KB
/
analytics.ts
File metadata and controls
93 lines (84 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { env, DEBUG_ANALYTICS } from '@codebuff/common/env'
import { createPostHogClient, type AnalyticsClient } from './analytics-core'
import { AnalyticsEvent } from './constants/analytics-events'
import type { TrackEventFn } from '@codebuff/common/types/contracts/analytics'
import type { Logger } from '@codebuff/common/types/contracts/logger'
let client: AnalyticsClient | undefined
export async function flushAnalytics(logger?: Logger) {
if (!client) {
return
}
try {
await client.flush()
} catch (error) {
// Log the error but don't throw - flushing is best-effort
logger?.warn({ error }, 'Failed to flush analytics')
// Track the flush failure event (will be queued for next successful flush)
try {
client.capture({
distinctId: 'system',
event: AnalyticsEvent.FLUSH_FAILED,
properties: {
error: error instanceof Error ? error.message : String(error),
},
})
} catch {
// Silently ignore if we can't even track the failure
}
}
}
export function withDefaultProperties(
trackEventFn: TrackEventFn,
defaultProperties: Record<string, unknown>,
): TrackEventFn {
return (params) => {
trackEventFn({
...params,
properties: { ...defaultProperties, ...params.properties },
})
}
}
export function trackEvent({
event,
userId,
properties,
logger,
}: {
event: AnalyticsEvent
userId: string
properties?: Record<string, any>
logger: Logger
}) {
// Don't track events in non-production environments
if (env.NEXT_PUBLIC_CB_ENVIRONMENT !== 'prod') {
if (DEBUG_ANALYTICS) {
logger.debug({ event, userId, properties }, `[analytics] ${event}`)
}
return
}
if (!client) {
try {
client = createPostHogClient(env.NEXT_PUBLIC_POSTHOG_API_KEY, {
host: env.NEXT_PUBLIC_POSTHOG_HOST_URL,
flushAt: 1,
flushInterval: 0,
})
} catch (error) {
logger.warn({ error }, 'Failed to initialize analytics client')
return
}
logger.info(
{ envName: env.NEXT_PUBLIC_CB_ENVIRONMENT },
'Analytics client initialized',
)
}
try {
client.capture({
distinctId: userId,
event,
properties,
})
} catch (error) {
logger.error({ error }, 'Failed to track event')
}
}