forked from Echo-Mirror-Butler/echomirror-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
253 lines (220 loc) · 7.82 KB
/
Copy pathclient.ts
File metadata and controls
253 lines (220 loc) · 7.82 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import { sanitizeProperties } from './privacy.js'
import {
DEFAULT_STORAGE_KEY,
defaultStorage,
readState,
type PersistedAnalyticsState,
} from './storage.js'
import type {
AIReflectionViewedProperties,
AnalyticsBatch,
AnalyticsConfig,
AnalyticsEvent,
AnalyticsEventMap,
AnalyticsEventName,
AnalyticsStorage,
EventProperties,
FriendFollowedProperties,
GiftSentProperties,
LeaderboardViewedProperties,
MoodLoggedProperties,
StreakMilestoneReachedProperties,
WalletConnectedProperties,
} from './types.js'
const DEFAULT_BATCH_SIZE = 20
const DEFAULT_FLUSH_INTERVAL_MS = 10_000
function randomId(): string {
if (typeof globalThis.crypto?.randomUUID === 'function') return globalThis.crypto.randomUUID()
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
}
export class AnalyticsClient {
private readonly config: AnalyticsConfig
private readonly storage: AnalyticsStorage
private readonly storageKey: string
private readonly batchSize: number
private readonly flushIntervalMs: number
private state: PersistedAnalyticsState
private timer?: ReturnType<typeof setInterval>
private activeFlush?: Promise<void>
constructor(config: AnalyticsConfig) {
if (!config || typeof config.transport !== 'function') {
throw new TypeError('AnalyticsClient requires a transport function')
}
this.config = config
this.storage = config.storage ?? defaultStorage()
this.storageKey = config.storageKey ?? DEFAULT_STORAGE_KEY
this.batchSize = config.batchSize ?? DEFAULT_BATCH_SIZE
this.flushIntervalMs = config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS
if (!Number.isInteger(this.batchSize) || this.batchSize <= 0) {
throw new RangeError('Analytics batchSize must be a positive integer')
}
if (!Number.isFinite(this.flushIntervalMs) || this.flushIntervalMs < 0) {
throw new RangeError('Analytics flushIntervalMs must be zero or greater')
}
const stored = this.readPersistedState()
this.state =
stored ??
({
version: 1,
anonymousId: this.newId('anon'),
sessionId: this.newId('session'),
queue: [],
} satisfies PersistedAnalyticsState)
this.persist()
this.start()
}
/** Track a built-in typed event or a custom event name. */
track<Name extends string>(
eventName: Name,
properties: Name extends AnalyticsEventName ? AnalyticsEventMap[Name] : EventProperties,
): AnalyticsEvent {
if (typeof eventName !== 'string' || eventName.trim().length === 0) {
throw new TypeError('Analytics eventName must be a non-empty string')
}
return this.enqueue(eventName, properties as Record<string, unknown>)
}
trackMoodLogged(properties: MoodLoggedProperties): AnalyticsEvent {
return this.track('mood_logged', properties)
}
trackStreakMilestoneReached(
properties: StreakMilestoneReachedProperties,
): AnalyticsEvent {
return this.track('streak_milestone_reached', properties)
}
trackGiftSent(properties: GiftSentProperties): AnalyticsEvent {
return this.track('gift_sent', properties)
}
trackWalletConnected(properties: WalletConnectedProperties): AnalyticsEvent {
return this.track('wallet_connected', properties)
}
trackAIReflectionViewed(properties: AIReflectionViewedProperties): AnalyticsEvent {
return this.track('ai_reflection_viewed', properties)
}
trackFriendFollowed(properties: FriendFollowedProperties = {}): AnalyticsEvent {
return this.track('friend_followed', properties)
}
trackLeaderboardViewed(properties: LeaderboardViewedProperties): AnalyticsEvent {
return this.track('leaderboard_viewed', properties)
}
/**
* Associates both queued anonymous events and future events with a signed-in user.
* A stitch event also lets a server alias anonymous events that were already delivered.
*/
identify(userId: string): void {
const normalizedUserId = userId.trim()
if (!normalizedUserId) throw new TypeError('Analytics userId must be a non-empty string')
if (this.state.userId === normalizedUserId) return
const previousAnonymousId = this.state.anonymousId
this.state.userId = normalizedUserId
this.state.queue = this.state.queue.map((event) => ({
...event,
userId: normalizedUserId,
}))
this.persist()
this.enqueue('identity_stitched', { previousAnonymousId })
}
/** Clears authenticated identity while retaining the stable anonymous device ID. */
resetUser(): void {
delete this.state.userId
this.state.sessionId = this.newId('session')
this.persist()
}
/** Starts timed flushing. Calling this more than once is safe. */
start(): void {
if (this.timer || this.flushIntervalMs === 0) return
this.timer = setInterval(() => {
void this.flush().catch((error: unknown) => this.reportError(error))
}, this.flushIntervalMs)
const nodeTimer = this.timer as ReturnType<typeof setInterval> & { unref?: () => void }
nodeTimer.unref?.()
}
/** Stops timed flushing without discarding the persistent queue. */
stop(): void {
if (!this.timer) return
clearInterval(this.timer)
this.timer = undefined
}
/** Flushes all currently queued batches. Failed batches remain persisted for retry. */
flush(): Promise<void> {
if (this.activeFlush) return this.activeFlush
this.activeFlush = this.flushQueue().finally(() => {
this.activeFlush = undefined
})
return this.activeFlush
}
/** Returns a snapshot suitable for queue counters and debugging. */
getPendingEvents(): AnalyticsEvent[] {
return this.state.queue.map((event) => ({
...event,
properties: { ...event.properties },
}))
}
getIdentity(): { anonymousId: string; sessionId: string; userId?: string } {
return {
anonymousId: this.state.anonymousId,
sessionId: this.state.sessionId,
...(this.state.userId ? { userId: this.state.userId } : {}),
}
}
private enqueue(eventName: string, properties: Record<string, unknown>): AnalyticsEvent {
const event: AnalyticsEvent = {
id: this.newId('event'),
name: eventName,
timestamp: this.now().toISOString(),
anonymousId: this.state.anonymousId,
sessionId: this.state.sessionId,
...(this.state.userId ? { userId: this.state.userId } : {}),
properties: sanitizeProperties(
eventName,
properties,
this.config.privacy?.allowSensitiveProperties === true,
),
}
this.state.queue.push(event)
this.persist()
if (this.state.queue.length >= this.batchSize) {
void this.flush().catch((error: unknown) => this.reportError(error))
}
return event
}
private async flushQueue(): Promise<void> {
while (this.state.queue.length > 0) {
const events = this.state.queue.slice(0, this.batchSize)
const eventIds = new Set(events.map((event) => event.id))
const batch: AnalyticsBatch = {
schemaVersion: 1,
batchId: `batch_${events.map((event) => event.id).join('_')}`,
sentAt: this.now().toISOString(),
events,
}
await this.config.transport(batch)
this.state.queue = this.state.queue.filter((event) => !eventIds.has(event.id))
this.persist()
}
}
private readPersistedState(): PersistedAnalyticsState | undefined {
try {
return readState(this.storage, this.storageKey)
} catch (error) {
this.reportError(error)
return undefined
}
}
private persist(): void {
try {
this.storage.setItem(this.storageKey, JSON.stringify(this.state))
} catch (error) {
this.reportError(error)
}
}
private now(): Date {
return this.config.now?.() ?? new Date()
}
private newId(prefix: string): string {
const value = this.config.generateId?.() ?? randomId()
return `${prefix}_${value}`
}
private reportError(error: unknown): void {
this.config.onError?.(error)
}
}