@cherrydotfun/collector-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,225 @@
1
+ /** Supported event types. */
2
+ type EventType = 'error' | 'log' | 'analytics';
3
+ /** Log severity levels accepted by the backend. */
4
+ type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug';
5
+ /** Well-known analytics event names (extensible with any string). */
6
+ type AnalyticsLevel = 'screen_view' | 'button_click' | 'feature_usage' | string;
7
+ /** Configuration options for {@link CollectorClient}. */
8
+ interface CollectorConfig {
9
+ /** Base URL of the Collector backend (e.g. `https://collector.cherry.fun`). */
10
+ baseUrl: string;
11
+ /** Project API key obtained from the admin panel. */
12
+ apiKey: string;
13
+ /** Client platform identifier (e.g. `ios`, `android`, `web`, `server`). */
14
+ platform?: string;
15
+ /** Application version string (e.g. `2.1.0`). */
16
+ version?: string;
17
+ /** Number of events per batch (default: 10). */
18
+ batchSize?: number;
19
+ /** Interval in ms between automatic batch flushes (default: 5000). */
20
+ flushIntervalMs?: number;
21
+ /** Interval in seconds between config refreshes from server (default: 300). */
22
+ configRefreshSec?: number;
23
+ /** Enable debug logging to `console.debug` (default: false). */
24
+ debug?: boolean;
25
+ /**
26
+ * Called when a network or API error occurs.
27
+ * @param error The error that occurred.
28
+ * @param context Where the error happened (e.g. `'sendBatch'`, `'metric'`, `'refreshConfig'`).
29
+ */
30
+ onError?: (error: Error, context: string) => void;
31
+ }
32
+ /** Event payload sent to the backend. */
33
+ interface CollectorEvent {
34
+ type: EventType;
35
+ /** Severity level. Required for `error` and `log` types; optional for `analytics`. */
36
+ level?: LogLevel;
37
+ /** Arbitrary event name (e.g. `screen_view`, `button_click`). Used primarily for analytics. */
38
+ event?: string;
39
+ /** Human-readable event message. */
40
+ message: string;
41
+ /** Arbitrary key-value parameters attached to the event. */
42
+ params?: Record<string, unknown>;
43
+ /** Stack trace information (for error events). */
44
+ stackTrace?: {
45
+ frames?: unknown[];
46
+ raw?: string;
47
+ };
48
+ /** Logical module that produced the event (e.g. `messaging`, `websocket`). */
49
+ module?: string;
50
+ /** Unique device identifier. */
51
+ deviceId?: string;
52
+ /** Client platform (e.g. `ios`, `android`). */
53
+ platform?: string;
54
+ /** Application version. */
55
+ version?: string;
56
+ /** User identifier. */
57
+ userId?: string;
58
+ /** Session identifier. */
59
+ sessionId?: string;
60
+ /** ISO-8601 timestamp. Defaults to current time if omitted. */
61
+ timestamp?: string;
62
+ }
63
+ /** Response from `GET /api/config`. */
64
+ interface ConfigResponse {
65
+ projectId: string;
66
+ disabled: string[];
67
+ sampleRates: Record<string, number>;
68
+ refreshIntervalSec: number;
69
+ }
70
+ /** Response from `POST /api/collect` (single event). */
71
+ interface IngestResponse {
72
+ ok: boolean;
73
+ id?: string;
74
+ error?: string;
75
+ pattern?: string;
76
+ }
77
+ /** Response from `POST /api/collect/batch`. */
78
+ interface BatchIngestResponse {
79
+ ok: boolean;
80
+ accepted: number;
81
+ rejected: number;
82
+ errors: Array<{
83
+ index: number;
84
+ reason: string;
85
+ }>;
86
+ }
87
+ /** A single metric key-value pair for batch operations. */
88
+ interface MetricOp {
89
+ /** Metric key (e.g. `ws_connections`, `active_rooms`). */
90
+ key: string;
91
+ /** Numeric value to set. */
92
+ value: number;
93
+ }
94
+ /** SDK telemetry counters returned by {@link CollectorClient.getStats}. */
95
+ interface CollectorStats {
96
+ /** Number of events successfully sent to the backend. */
97
+ sent: number;
98
+ /** Number of events dropped due to disabled filters. */
99
+ dropped: number;
100
+ /** Number of events that failed to send (network/API errors). */
101
+ failed: number;
102
+ /** Current number of events waiting in the batch queue. */
103
+ queueSize: number;
104
+ }
105
+
106
+ declare class CollectorClient {
107
+ private config;
108
+ private queue;
109
+ private disabledPatterns;
110
+ private configRefreshTimer;
111
+ private initialized;
112
+ private _lastConfig;
113
+ private _dropped;
114
+ private _userId;
115
+ private _sessionId;
116
+ private _module;
117
+ private _deviceId;
118
+ constructor(config: CollectorConfig);
119
+ /**
120
+ * Initialize the client: fetches filter configuration from the server
121
+ * and starts the periodic config refresh timer.
122
+ * Must be called before sending events.
123
+ */
124
+ init(): Promise<void>;
125
+ /**
126
+ * Flush all queued events to the server immediately.
127
+ * Returns when the send completes (or fails silently).
128
+ */
129
+ flush(): Promise<void>;
130
+ /**
131
+ * Stop all timers and flush remaining events.
132
+ * Call before application exit or when the client is no longer needed.
133
+ */
134
+ destroy(): void;
135
+ /** Set the user ID attached to all subsequent events. */
136
+ setUser(userId: string): void;
137
+ /** Set the session ID attached to all subsequent events. */
138
+ setSession(sessionId: string): void;
139
+ /** Set the default module name attached to all subsequent events. */
140
+ setModule(module: string): void;
141
+ /** Set the device ID attached to all subsequent events. */
142
+ setDevice(deviceId: string): void;
143
+ /**
144
+ * Send an error event.
145
+ * @param message Error description.
146
+ * @param params Optional parameters. The special `stackTrace` key is extracted
147
+ * and sent as the structured `stackTrace.raw` field.
148
+ */
149
+ error(message: string, params?: Record<string, unknown> & {
150
+ stackTrace?: string;
151
+ }): void;
152
+ /**
153
+ * Send a log event with an explicit level.
154
+ * @param level Severity: `fatal`, `error`, `warn`, `info`, or `debug`.
155
+ * @param message Log message.
156
+ * @param params Optional key-value parameters.
157
+ */
158
+ log(level: LogLevel, message: string, params?: Record<string, unknown>): void;
159
+ /** Shorthand for `log('fatal', message, params)`. */
160
+ fatal(message: string, params?: Record<string, unknown>): void;
161
+ /** Shorthand for `log('warn', message, params)`. */
162
+ warn(message: string, params?: Record<string, unknown>): void;
163
+ /** Shorthand for `log('info', message, params)`. */
164
+ info(message: string, params?: Record<string, unknown>): void;
165
+ /** Shorthand for `log('debug', message, params)`. */
166
+ debug(message: string, params?: Record<string, unknown>): void;
167
+ /**
168
+ * Send an analytics event.
169
+ * @param event Event name (e.g. `screen_view`, `button_click`).
170
+ * @param message Human-readable description (e.g. screen name or action label).
171
+ * @param params Optional key-value parameters.
172
+ */
173
+ analytics(event: string, message: string, params?: Record<string, unknown>): void;
174
+ /**
175
+ * Set a single metric value. Sent immediately (not batched).
176
+ * @param key Metric key (e.g. `ws_connections`).
177
+ * @param value Numeric value.
178
+ */
179
+ metric(key: string, value: number): Promise<void>;
180
+ /**
181
+ * Set multiple metric values in one request. Sent immediately (not batched).
182
+ * Backend accepts up to 100 operations per call.
183
+ * @param ops Array of `{ key, value }` pairs.
184
+ */
185
+ metricBatch(ops: MetricOp[]): Promise<void>;
186
+ /**
187
+ * Send a single event immediately via `POST /api/collect`, bypassing the batch queue.
188
+ * Useful for critical events that must not be delayed.
189
+ *
190
+ * The event is enriched with context (userId, sessionId, platform, etc.)
191
+ * and filtered against disabled patterns, same as queued events.
192
+ *
193
+ * @param event Partial event data. `type` and `message` are required.
194
+ */
195
+ send(event: Partial<CollectorEvent> & {
196
+ type: CollectorEvent['type'];
197
+ message: string;
198
+ }): Promise<void>;
199
+ /**
200
+ * Force-refresh the filter configuration from the server.
201
+ * Normally called automatically on the configured interval.
202
+ */
203
+ refreshConfig(): Promise<void>;
204
+ /**
205
+ * Returns the last successfully fetched server configuration,
206
+ * or `null` if no config has been loaded yet.
207
+ */
208
+ getConfig(): ConfigResponse | null;
209
+ /**
210
+ * Returns SDK telemetry counters: events sent, dropped (filtered), failed,
211
+ * and current queue size.
212
+ */
213
+ getStats(): CollectorStats;
214
+ /** Whether {@link init} has been called and completed successfully. */
215
+ get isInitialized(): boolean;
216
+ private buildEvent;
217
+ private enqueue;
218
+ private isDisabled;
219
+ private sendBatch;
220
+ private doFetch;
221
+ private handleError;
222
+ private log_debug;
223
+ }
224
+
225
+ export { type AnalyticsLevel, type BatchIngestResponse, CollectorClient, type CollectorConfig, type CollectorEvent, type CollectorStats, type ConfigResponse, type EventType, type IngestResponse, type LogLevel, type MetricOp };
@@ -0,0 +1,225 @@
1
+ /** Supported event types. */
2
+ type EventType = 'error' | 'log' | 'analytics';
3
+ /** Log severity levels accepted by the backend. */
4
+ type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug';
5
+ /** Well-known analytics event names (extensible with any string). */
6
+ type AnalyticsLevel = 'screen_view' | 'button_click' | 'feature_usage' | string;
7
+ /** Configuration options for {@link CollectorClient}. */
8
+ interface CollectorConfig {
9
+ /** Base URL of the Collector backend (e.g. `https://collector.cherry.fun`). */
10
+ baseUrl: string;
11
+ /** Project API key obtained from the admin panel. */
12
+ apiKey: string;
13
+ /** Client platform identifier (e.g. `ios`, `android`, `web`, `server`). */
14
+ platform?: string;
15
+ /** Application version string (e.g. `2.1.0`). */
16
+ version?: string;
17
+ /** Number of events per batch (default: 10). */
18
+ batchSize?: number;
19
+ /** Interval in ms between automatic batch flushes (default: 5000). */
20
+ flushIntervalMs?: number;
21
+ /** Interval in seconds between config refreshes from server (default: 300). */
22
+ configRefreshSec?: number;
23
+ /** Enable debug logging to `console.debug` (default: false). */
24
+ debug?: boolean;
25
+ /**
26
+ * Called when a network or API error occurs.
27
+ * @param error The error that occurred.
28
+ * @param context Where the error happened (e.g. `'sendBatch'`, `'metric'`, `'refreshConfig'`).
29
+ */
30
+ onError?: (error: Error, context: string) => void;
31
+ }
32
+ /** Event payload sent to the backend. */
33
+ interface CollectorEvent {
34
+ type: EventType;
35
+ /** Severity level. Required for `error` and `log` types; optional for `analytics`. */
36
+ level?: LogLevel;
37
+ /** Arbitrary event name (e.g. `screen_view`, `button_click`). Used primarily for analytics. */
38
+ event?: string;
39
+ /** Human-readable event message. */
40
+ message: string;
41
+ /** Arbitrary key-value parameters attached to the event. */
42
+ params?: Record<string, unknown>;
43
+ /** Stack trace information (for error events). */
44
+ stackTrace?: {
45
+ frames?: unknown[];
46
+ raw?: string;
47
+ };
48
+ /** Logical module that produced the event (e.g. `messaging`, `websocket`). */
49
+ module?: string;
50
+ /** Unique device identifier. */
51
+ deviceId?: string;
52
+ /** Client platform (e.g. `ios`, `android`). */
53
+ platform?: string;
54
+ /** Application version. */
55
+ version?: string;
56
+ /** User identifier. */
57
+ userId?: string;
58
+ /** Session identifier. */
59
+ sessionId?: string;
60
+ /** ISO-8601 timestamp. Defaults to current time if omitted. */
61
+ timestamp?: string;
62
+ }
63
+ /** Response from `GET /api/config`. */
64
+ interface ConfigResponse {
65
+ projectId: string;
66
+ disabled: string[];
67
+ sampleRates: Record<string, number>;
68
+ refreshIntervalSec: number;
69
+ }
70
+ /** Response from `POST /api/collect` (single event). */
71
+ interface IngestResponse {
72
+ ok: boolean;
73
+ id?: string;
74
+ error?: string;
75
+ pattern?: string;
76
+ }
77
+ /** Response from `POST /api/collect/batch`. */
78
+ interface BatchIngestResponse {
79
+ ok: boolean;
80
+ accepted: number;
81
+ rejected: number;
82
+ errors: Array<{
83
+ index: number;
84
+ reason: string;
85
+ }>;
86
+ }
87
+ /** A single metric key-value pair for batch operations. */
88
+ interface MetricOp {
89
+ /** Metric key (e.g. `ws_connections`, `active_rooms`). */
90
+ key: string;
91
+ /** Numeric value to set. */
92
+ value: number;
93
+ }
94
+ /** SDK telemetry counters returned by {@link CollectorClient.getStats}. */
95
+ interface CollectorStats {
96
+ /** Number of events successfully sent to the backend. */
97
+ sent: number;
98
+ /** Number of events dropped due to disabled filters. */
99
+ dropped: number;
100
+ /** Number of events that failed to send (network/API errors). */
101
+ failed: number;
102
+ /** Current number of events waiting in the batch queue. */
103
+ queueSize: number;
104
+ }
105
+
106
+ declare class CollectorClient {
107
+ private config;
108
+ private queue;
109
+ private disabledPatterns;
110
+ private configRefreshTimer;
111
+ private initialized;
112
+ private _lastConfig;
113
+ private _dropped;
114
+ private _userId;
115
+ private _sessionId;
116
+ private _module;
117
+ private _deviceId;
118
+ constructor(config: CollectorConfig);
119
+ /**
120
+ * Initialize the client: fetches filter configuration from the server
121
+ * and starts the periodic config refresh timer.
122
+ * Must be called before sending events.
123
+ */
124
+ init(): Promise<void>;
125
+ /**
126
+ * Flush all queued events to the server immediately.
127
+ * Returns when the send completes (or fails silently).
128
+ */
129
+ flush(): Promise<void>;
130
+ /**
131
+ * Stop all timers and flush remaining events.
132
+ * Call before application exit or when the client is no longer needed.
133
+ */
134
+ destroy(): void;
135
+ /** Set the user ID attached to all subsequent events. */
136
+ setUser(userId: string): void;
137
+ /** Set the session ID attached to all subsequent events. */
138
+ setSession(sessionId: string): void;
139
+ /** Set the default module name attached to all subsequent events. */
140
+ setModule(module: string): void;
141
+ /** Set the device ID attached to all subsequent events. */
142
+ setDevice(deviceId: string): void;
143
+ /**
144
+ * Send an error event.
145
+ * @param message Error description.
146
+ * @param params Optional parameters. The special `stackTrace` key is extracted
147
+ * and sent as the structured `stackTrace.raw` field.
148
+ */
149
+ error(message: string, params?: Record<string, unknown> & {
150
+ stackTrace?: string;
151
+ }): void;
152
+ /**
153
+ * Send a log event with an explicit level.
154
+ * @param level Severity: `fatal`, `error`, `warn`, `info`, or `debug`.
155
+ * @param message Log message.
156
+ * @param params Optional key-value parameters.
157
+ */
158
+ log(level: LogLevel, message: string, params?: Record<string, unknown>): void;
159
+ /** Shorthand for `log('fatal', message, params)`. */
160
+ fatal(message: string, params?: Record<string, unknown>): void;
161
+ /** Shorthand for `log('warn', message, params)`. */
162
+ warn(message: string, params?: Record<string, unknown>): void;
163
+ /** Shorthand for `log('info', message, params)`. */
164
+ info(message: string, params?: Record<string, unknown>): void;
165
+ /** Shorthand for `log('debug', message, params)`. */
166
+ debug(message: string, params?: Record<string, unknown>): void;
167
+ /**
168
+ * Send an analytics event.
169
+ * @param event Event name (e.g. `screen_view`, `button_click`).
170
+ * @param message Human-readable description (e.g. screen name or action label).
171
+ * @param params Optional key-value parameters.
172
+ */
173
+ analytics(event: string, message: string, params?: Record<string, unknown>): void;
174
+ /**
175
+ * Set a single metric value. Sent immediately (not batched).
176
+ * @param key Metric key (e.g. `ws_connections`).
177
+ * @param value Numeric value.
178
+ */
179
+ metric(key: string, value: number): Promise<void>;
180
+ /**
181
+ * Set multiple metric values in one request. Sent immediately (not batched).
182
+ * Backend accepts up to 100 operations per call.
183
+ * @param ops Array of `{ key, value }` pairs.
184
+ */
185
+ metricBatch(ops: MetricOp[]): Promise<void>;
186
+ /**
187
+ * Send a single event immediately via `POST /api/collect`, bypassing the batch queue.
188
+ * Useful for critical events that must not be delayed.
189
+ *
190
+ * The event is enriched with context (userId, sessionId, platform, etc.)
191
+ * and filtered against disabled patterns, same as queued events.
192
+ *
193
+ * @param event Partial event data. `type` and `message` are required.
194
+ */
195
+ send(event: Partial<CollectorEvent> & {
196
+ type: CollectorEvent['type'];
197
+ message: string;
198
+ }): Promise<void>;
199
+ /**
200
+ * Force-refresh the filter configuration from the server.
201
+ * Normally called automatically on the configured interval.
202
+ */
203
+ refreshConfig(): Promise<void>;
204
+ /**
205
+ * Returns the last successfully fetched server configuration,
206
+ * or `null` if no config has been loaded yet.
207
+ */
208
+ getConfig(): ConfigResponse | null;
209
+ /**
210
+ * Returns SDK telemetry counters: events sent, dropped (filtered), failed,
211
+ * and current queue size.
212
+ */
213
+ getStats(): CollectorStats;
214
+ /** Whether {@link init} has been called and completed successfully. */
215
+ get isInitialized(): boolean;
216
+ private buildEvent;
217
+ private enqueue;
218
+ private isDisabled;
219
+ private sendBatch;
220
+ private doFetch;
221
+ private handleError;
222
+ private log_debug;
223
+ }
224
+
225
+ export { type AnalyticsLevel, type BatchIngestResponse, CollectorClient, type CollectorConfig, type CollectorEvent, type CollectorStats, type ConfigResponse, type EventType, type IngestResponse, type LogLevel, type MetricOp };