@grainql/analytics-web 1.7.2 → 2.0.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.
Files changed (116) hide show
  1. package/README.md +71 -777
  2. package/dist/cjs/index.d.ts +35 -2
  3. package/dist/cjs/index.d.ts.map +1 -1
  4. package/dist/cjs/index.js.map +1 -1
  5. package/dist/cjs/react/GrainProvider.d.ts +11 -0
  6. package/dist/cjs/react/GrainProvider.d.ts.map +1 -0
  7. package/dist/cjs/react/GrainProvider.js +79 -0
  8. package/dist/cjs/react/GrainProvider.js.map +1 -0
  9. package/dist/cjs/react/context.d.ts +11 -0
  10. package/dist/cjs/react/context.d.ts.map +1 -0
  11. package/dist/cjs/react/context.js +43 -0
  12. package/dist/cjs/react/context.js.map +1 -0
  13. package/dist/cjs/react/hooks/useAllConfigs.d.ts +8 -0
  14. package/dist/cjs/react/hooks/useAllConfigs.d.ts.map +1 -0
  15. package/dist/cjs/react/hooks/useAllConfigs.js +112 -0
  16. package/dist/cjs/react/hooks/useAllConfigs.js.map +1 -0
  17. package/dist/cjs/react/hooks/useConfig.d.ts +9 -0
  18. package/dist/cjs/react/hooks/useConfig.d.ts.map +1 -0
  19. package/dist/cjs/react/hooks/useConfig.js +116 -0
  20. package/dist/cjs/react/hooks/useConfig.js.map +1 -0
  21. package/dist/cjs/react/hooks/useGrainAnalytics.d.ts +6 -0
  22. package/dist/cjs/react/hooks/useGrainAnalytics.d.ts.map +1 -0
  23. package/dist/cjs/react/hooks/useGrainAnalytics.js +50 -0
  24. package/dist/cjs/react/hooks/useGrainAnalytics.js.map +1 -0
  25. package/dist/cjs/react/hooks/useTrack.d.ts +9 -0
  26. package/dist/cjs/react/hooks/useTrack.d.ts.map +1 -0
  27. package/dist/cjs/react/hooks/useTrack.js +53 -0
  28. package/dist/cjs/react/hooks/useTrack.js.map +1 -0
  29. package/dist/cjs/react/index.d.ts +36 -0
  30. package/dist/cjs/react/index.d.ts.map +1 -0
  31. package/dist/cjs/react/index.js +45 -0
  32. package/dist/cjs/react/index.js.map +1 -0
  33. package/dist/cjs/react/types.d.ts +33 -0
  34. package/dist/cjs/react/types.d.ts.map +1 -0
  35. package/dist/cjs/react/types.js +6 -0
  36. package/dist/cjs/react/types.js.map +1 -0
  37. package/dist/esm/index.d.ts +35 -2
  38. package/dist/esm/index.d.ts.map +1 -1
  39. package/dist/esm/index.js.map +1 -1
  40. package/dist/esm/react/GrainProvider.d.ts +11 -0
  41. package/dist/esm/react/GrainProvider.d.ts.map +1 -0
  42. package/dist/esm/react/GrainProvider.js +43 -0
  43. package/dist/esm/react/GrainProvider.js.map +1 -0
  44. package/dist/esm/react/context.d.ts +11 -0
  45. package/dist/esm/react/context.d.ts.map +1 -0
  46. package/dist/esm/react/context.js +7 -0
  47. package/dist/esm/react/context.js.map +1 -0
  48. package/dist/esm/react/hooks/useAllConfigs.d.ts +8 -0
  49. package/dist/esm/react/hooks/useAllConfigs.d.ts.map +1 -0
  50. package/dist/esm/react/hooks/useAllConfigs.js +76 -0
  51. package/dist/esm/react/hooks/useAllConfigs.js.map +1 -0
  52. package/dist/esm/react/hooks/useConfig.d.ts +9 -0
  53. package/dist/esm/react/hooks/useConfig.d.ts.map +1 -0
  54. package/dist/esm/react/hooks/useConfig.js +80 -0
  55. package/dist/esm/react/hooks/useConfig.js.map +1 -0
  56. package/dist/esm/react/hooks/useGrainAnalytics.d.ts +6 -0
  57. package/dist/esm/react/hooks/useGrainAnalytics.d.ts.map +1 -0
  58. package/dist/esm/react/hooks/useGrainAnalytics.js +14 -0
  59. package/dist/esm/react/hooks/useGrainAnalytics.js.map +1 -0
  60. package/dist/esm/react/hooks/useTrack.d.ts +9 -0
  61. package/dist/esm/react/hooks/useTrack.d.ts.map +1 -0
  62. package/dist/esm/react/hooks/useTrack.js +17 -0
  63. package/dist/esm/react/hooks/useTrack.js.map +1 -0
  64. package/dist/esm/react/index.d.ts +36 -0
  65. package/dist/esm/react/index.d.ts.map +1 -0
  66. package/dist/esm/react/index.js +37 -0
  67. package/dist/esm/react/index.js.map +1 -0
  68. package/dist/esm/react/types.d.ts +33 -0
  69. package/dist/esm/react/types.d.ts.map +1 -0
  70. package/dist/esm/react/types.js +5 -0
  71. package/dist/esm/react/types.js.map +1 -0
  72. package/dist/index.d.ts +35 -2
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.global.dev.js +124 -14
  75. package/dist/index.global.dev.js.map +2 -2
  76. package/dist/index.global.js +2 -2
  77. package/dist/index.global.js.map +3 -3
  78. package/dist/index.js +147 -15
  79. package/dist/index.mjs +147 -15
  80. package/dist/react/index.d.ts +405 -0
  81. package/dist/react/index.d.ts.map +1 -0
  82. package/dist/react/index.js +1181 -0
  83. package/dist/react/index.mjs +1176 -0
  84. package/dist/react/react/GrainProvider.d.ts +11 -0
  85. package/dist/react/react/GrainProvider.d.ts.map +1 -0
  86. package/dist/react/react/GrainProvider.js +45 -0
  87. package/dist/react/react/GrainProvider.mjs +42 -0
  88. package/dist/react/react/context.d.ts +11 -0
  89. package/dist/react/react/context.d.ts.map +1 -0
  90. package/dist/react/react/context.js +9 -0
  91. package/dist/react/react/context.mjs +6 -0
  92. package/dist/react/react/hooks/useAllConfigs.d.ts +8 -0
  93. package/dist/react/react/hooks/useAllConfigs.d.ts.map +1 -0
  94. package/dist/react/react/hooks/useAllConfigs.js +78 -0
  95. package/dist/react/react/hooks/useAllConfigs.mjs +75 -0
  96. package/dist/react/react/hooks/useConfig.d.ts +9 -0
  97. package/dist/react/react/hooks/useConfig.d.ts.map +1 -0
  98. package/dist/react/react/hooks/useConfig.js +82 -0
  99. package/dist/react/react/hooks/useConfig.mjs +79 -0
  100. package/dist/react/react/hooks/useGrainAnalytics.d.ts +6 -0
  101. package/dist/react/react/hooks/useGrainAnalytics.d.ts.map +1 -0
  102. package/dist/react/react/hooks/useGrainAnalytics.js +16 -0
  103. package/dist/react/react/hooks/useGrainAnalytics.mjs +13 -0
  104. package/dist/react/react/hooks/useTrack.d.ts +9 -0
  105. package/dist/react/react/hooks/useTrack.d.ts.map +1 -0
  106. package/dist/react/react/hooks/useTrack.js +19 -0
  107. package/dist/react/react/hooks/useTrack.mjs +16 -0
  108. package/dist/react/react/index.d.ts +36 -0
  109. package/dist/react/react/index.d.ts.map +1 -0
  110. package/dist/react/react/index.js +44 -0
  111. package/dist/react/react/index.mjs +36 -0
  112. package/dist/react/react/types.d.ts +33 -0
  113. package/dist/react/react/types.d.ts.map +1 -0
  114. package/dist/react/react/types.js +5 -0
  115. package/dist/react/react/types.mjs +4 -0
  116. package/package.json +20 -2
@@ -0,0 +1,1176 @@
1
+ /**
2
+ * Grain Analytics Web SDK
3
+ * A lightweight, dependency-free TypeScript SDK for sending analytics events to Grain's REST API
4
+ */
5
+ export class GrainAnalytics {
6
+ constructor(config) {
7
+ this.eventQueue = [];
8
+ this.flushTimer = null;
9
+ this.isDestroyed = false;
10
+ this.globalUserId = null;
11
+ this.persistentAnonymousUserId = null;
12
+ // Remote Config properties
13
+ this.configCache = null;
14
+ this.configRefreshTimer = null;
15
+ this.configChangeListeners = [];
16
+ this.configFetchPromise = null;
17
+ this.config = {
18
+ apiUrl: 'https://api.grainql.com',
19
+ authStrategy: 'NONE',
20
+ batchSize: 50,
21
+ flushInterval: 5000, // 5 seconds
22
+ retryAttempts: 3,
23
+ retryDelay: 1000, // 1 second
24
+ maxEventsPerRequest: 160, // Maximum events per API request
25
+ debug: false,
26
+ // Remote Config defaults
27
+ defaultConfigurations: {},
28
+ configCacheKey: 'grain_config',
29
+ configRefreshInterval: 300000, // 5 minutes
30
+ enableConfigCache: true,
31
+ ...config,
32
+ tenantId: config.tenantId,
33
+ };
34
+ // Set global userId if provided in config
35
+ if (config.userId) {
36
+ this.globalUserId = config.userId;
37
+ }
38
+ this.validateConfig();
39
+ this.initializePersistentAnonymousUserId();
40
+ this.setupBeforeUnload();
41
+ this.startFlushTimer();
42
+ this.initializeConfigCache();
43
+ }
44
+ validateConfig() {
45
+ if (!this.config.tenantId) {
46
+ throw new Error('Grain Analytics: tenantId is required');
47
+ }
48
+ if (this.config.authStrategy === 'SERVER_SIDE' && !this.config.secretKey) {
49
+ throw new Error('Grain Analytics: secretKey is required for SERVER_SIDE auth strategy');
50
+ }
51
+ if (this.config.authStrategy === 'JWT' && !this.config.authProvider) {
52
+ throw new Error('Grain Analytics: authProvider is required for JWT auth strategy');
53
+ }
54
+ }
55
+ /**
56
+ * Generate a UUID v4 string
57
+ */
58
+ generateUUID() {
59
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) {
60
+ return crypto.randomUUID();
61
+ }
62
+ // Fallback for environments without crypto.randomUUID
63
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
64
+ const r = Math.random() * 16 | 0;
65
+ const v = c === 'x' ? r : (r & 0x3 | 0x8);
66
+ return v.toString(16);
67
+ });
68
+ }
69
+ /**
70
+ * Generate a proper UUIDv4 identifier for anonymous user ID
71
+ */
72
+ generateAnonymousUserId() {
73
+ return this.generateUUID();
74
+ }
75
+ /**
76
+ * Initialize persistent anonymous user ID from localStorage or create new one
77
+ */
78
+ initializePersistentAnonymousUserId() {
79
+ if (typeof window === 'undefined')
80
+ return;
81
+ const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
82
+ try {
83
+ const stored = localStorage.getItem(storageKey);
84
+ if (stored) {
85
+ this.persistentAnonymousUserId = stored;
86
+ this.log('Loaded persistent anonymous user ID:', this.persistentAnonymousUserId);
87
+ }
88
+ else {
89
+ // Generate new UUIDv4 anonymous user ID
90
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
91
+ localStorage.setItem(storageKey, this.persistentAnonymousUserId);
92
+ this.log('Generated new persistent anonymous user ID:', this.persistentAnonymousUserId);
93
+ }
94
+ }
95
+ catch (error) {
96
+ this.log('Failed to initialize persistent anonymous user ID:', error);
97
+ // Fallback: generate temporary ID without persistence
98
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
99
+ }
100
+ }
101
+ /**
102
+ * Get the effective user ID (global userId or persistent anonymous ID)
103
+ */
104
+ getEffectiveUserId() {
105
+ if (this.globalUserId) {
106
+ return this.globalUserId;
107
+ }
108
+ if (this.persistentAnonymousUserId) {
109
+ return this.persistentAnonymousUserId;
110
+ }
111
+ // Generate a new UUIDv4 identifier as fallback
112
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
113
+ // Try to persist it
114
+ if (typeof window !== 'undefined') {
115
+ try {
116
+ const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
117
+ localStorage.setItem(storageKey, this.persistentAnonymousUserId);
118
+ }
119
+ catch (error) {
120
+ this.log('Failed to persist generated anonymous user ID:', error);
121
+ }
122
+ }
123
+ return this.persistentAnonymousUserId;
124
+ }
125
+ log(...args) {
126
+ if (this.config.debug) {
127
+ console.log('[Grain Analytics]', ...args);
128
+ }
129
+ }
130
+ /**
131
+ * Create error digest from events
132
+ */
133
+ createErrorDigest(events) {
134
+ const eventNames = [...new Set(events.map(e => e.eventName))];
135
+ const userIds = [...new Set(events.map(e => e.userId))];
136
+ let totalProperties = 0;
137
+ let totalSize = 0;
138
+ events.forEach(event => {
139
+ const properties = event.properties || {};
140
+ totalProperties += Object.keys(properties).length;
141
+ totalSize += JSON.stringify(event).length;
142
+ });
143
+ return {
144
+ eventCount: events.length,
145
+ totalProperties,
146
+ totalSize,
147
+ eventNames,
148
+ userIds,
149
+ };
150
+ }
151
+ /**
152
+ * Format error with beautiful structure
153
+ */
154
+ formatError(error, context, events) {
155
+ const digest = events ? this.createErrorDigest(events) : {
156
+ eventCount: 0,
157
+ totalProperties: 0,
158
+ totalSize: 0,
159
+ eventNames: [],
160
+ userIds: [],
161
+ };
162
+ let code = 'UNKNOWN_ERROR';
163
+ let message = 'An unknown error occurred';
164
+ if (error instanceof Error) {
165
+ message = error.message;
166
+ // Determine error code based on error type and message
167
+ if (message.includes('fetch failed') || message.includes('network error')) {
168
+ code = 'NETWORK_ERROR';
169
+ }
170
+ else if (message.includes('timeout')) {
171
+ code = 'TIMEOUT_ERROR';
172
+ }
173
+ else if (message.includes('HTTP 4')) {
174
+ code = 'CLIENT_ERROR';
175
+ }
176
+ else if (message.includes('HTTP 5')) {
177
+ code = 'SERVER_ERROR';
178
+ }
179
+ else if (message.includes('JSON')) {
180
+ code = 'PARSE_ERROR';
181
+ }
182
+ else if (message.includes('auth') || message.includes('unauthorized')) {
183
+ code = 'AUTH_ERROR';
184
+ }
185
+ else if (message.includes('rate limit') || message.includes('429')) {
186
+ code = 'RATE_LIMIT_ERROR';
187
+ }
188
+ else {
189
+ code = 'GENERAL_ERROR';
190
+ }
191
+ }
192
+ else if (typeof error === 'string') {
193
+ message = error;
194
+ code = 'STRING_ERROR';
195
+ }
196
+ else if (error && typeof error === 'object' && 'status' in error) {
197
+ const status = error.status;
198
+ code = `HTTP_${status}`;
199
+ message = `HTTP ${status} error`;
200
+ }
201
+ return {
202
+ code,
203
+ message,
204
+ digest,
205
+ timestamp: new Date().toISOString(),
206
+ context,
207
+ originalError: error,
208
+ };
209
+ }
210
+ /**
211
+ * Log formatted error gracefully
212
+ */
213
+ logError(formattedError) {
214
+ const { code, message, digest, timestamp, context } = formattedError;
215
+ const errorOutput = {
216
+ '🚨 Grain Analytics Error': {
217
+ 'Error Code': code,
218
+ 'Message': message,
219
+ 'Context': context,
220
+ 'Timestamp': timestamp,
221
+ 'Event Digest': {
222
+ 'Events': digest.eventCount,
223
+ 'Properties': digest.totalProperties,
224
+ 'Size (bytes)': digest.totalSize,
225
+ 'Event Names': digest.eventNames.length > 0 ? digest.eventNames.join(', ') : 'None',
226
+ 'User IDs': digest.userIds.length > 0 ? digest.userIds.slice(0, 3).join(', ') + (digest.userIds.length > 3 ? '...' : '') : 'None',
227
+ }
228
+ }
229
+ };
230
+ console.error('🚨 Grain Analytics Error:', errorOutput);
231
+ // Also log in a more compact format for debugging
232
+ if (this.config.debug) {
233
+ console.error(`[Grain Analytics] ${code}: ${message} (${context}) - Events: ${digest.eventCount}, Props: ${digest.totalProperties}, Size: ${digest.totalSize}B`);
234
+ }
235
+ }
236
+ /**
237
+ * Safely execute a function with error handling
238
+ */
239
+ async safeExecute(fn, context, events) {
240
+ try {
241
+ return await fn();
242
+ }
243
+ catch (error) {
244
+ const formattedError = this.formatError(error, context, events);
245
+ this.logError(formattedError);
246
+ return null;
247
+ }
248
+ }
249
+ formatEvent(event) {
250
+ return {
251
+ eventName: event.eventName,
252
+ userId: event.userId || this.getEffectiveUserId(),
253
+ properties: event.properties || {},
254
+ };
255
+ }
256
+ async getAuthHeaders() {
257
+ const headers = {
258
+ 'Content-Type': 'application/json',
259
+ };
260
+ switch (this.config.authStrategy) {
261
+ case 'NONE':
262
+ break;
263
+ case 'SERVER_SIDE':
264
+ headers['Authorization'] = `Chase ${this.config.secretKey}`;
265
+ break;
266
+ case 'JWT':
267
+ if (this.config.authProvider) {
268
+ const token = await this.config.authProvider.getToken();
269
+ headers['Authorization'] = `Bearer ${token}`;
270
+ }
271
+ break;
272
+ }
273
+ return headers;
274
+ }
275
+ async delay(ms) {
276
+ return new Promise(resolve => setTimeout(resolve, ms));
277
+ }
278
+ isRetriableError(error) {
279
+ if (error instanceof Error) {
280
+ // Check for specific network or fetch errors
281
+ const message = error.message.toLowerCase();
282
+ if (message.includes('fetch failed'))
283
+ return true;
284
+ if (message === 'network error')
285
+ return true; // Exact match to avoid "Non-network error"
286
+ if (message.includes('timeout'))
287
+ return true;
288
+ if (message.includes('connection'))
289
+ return true;
290
+ }
291
+ // Check for HTTP status codes that are retriable
292
+ if (typeof error === 'object' && error !== null && 'status' in error) {
293
+ const status = error.status;
294
+ return status >= 500 || status === 429; // Server errors or rate limiting
295
+ }
296
+ return false;
297
+ }
298
+ async sendEvents(events) {
299
+ if (events.length === 0)
300
+ return;
301
+ let lastError;
302
+ for (let attempt = 0; attempt <= this.config.retryAttempts; attempt++) {
303
+ try {
304
+ const headers = await this.getAuthHeaders();
305
+ const url = `${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`;
306
+ this.log(`Sending ${events.length} events to ${url} (attempt ${attempt + 1})`);
307
+ const response = await fetch(url, {
308
+ method: 'POST',
309
+ headers,
310
+ body: JSON.stringify(events),
311
+ });
312
+ if (!response.ok) {
313
+ let errorMessage = `HTTP ${response.status}`;
314
+ try {
315
+ const errorBody = await response.json();
316
+ if (errorBody?.message) {
317
+ errorMessage = errorBody.message;
318
+ }
319
+ }
320
+ catch {
321
+ const errorText = await response.text();
322
+ if (errorText) {
323
+ errorMessage = errorText;
324
+ }
325
+ }
326
+ const error = new Error(`Failed to send events: ${errorMessage}`);
327
+ error.status = response.status;
328
+ throw error;
329
+ }
330
+ this.log(`Successfully sent ${events.length} events`);
331
+ return; // Success, exit retry loop
332
+ }
333
+ catch (error) {
334
+ lastError = error;
335
+ if (attempt === this.config.retryAttempts) {
336
+ // Last attempt, don't retry - log error gracefully
337
+ const formattedError = this.formatError(error, `sendEvents (attempt ${attempt + 1}/${this.config.retryAttempts + 1})`, events);
338
+ this.logError(formattedError);
339
+ return; // Don't throw, just return gracefully
340
+ }
341
+ if (!this.isRetriableError(error)) {
342
+ // Non-retriable error, don't retry - log error gracefully
343
+ const formattedError = this.formatError(error, `sendEvents (non-retriable error)`, events);
344
+ this.logError(formattedError);
345
+ return; // Don't throw, just return gracefully
346
+ }
347
+ const delayMs = this.config.retryDelay * Math.pow(2, attempt); // Exponential backoff
348
+ this.log(`Retrying in ${delayMs}ms after error:`, error);
349
+ await this.delay(delayMs);
350
+ }
351
+ }
352
+ }
353
+ async sendEventsWithBeacon(events) {
354
+ if (events.length === 0)
355
+ return;
356
+ try {
357
+ const headers = await this.getAuthHeaders();
358
+ const url = `${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`;
359
+ const body = JSON.stringify({ events });
360
+ // Try beacon API first (more reliable for page unload)
361
+ if (typeof navigator !== 'undefined' && 'sendBeacon' in navigator) {
362
+ const blob = new Blob([body], { type: 'application/json' });
363
+ const success = navigator.sendBeacon(url, blob);
364
+ if (success) {
365
+ this.log(`Successfully sent ${events.length} events via beacon`);
366
+ return;
367
+ }
368
+ }
369
+ // Fallback to fetch with keepalive
370
+ await fetch(url, {
371
+ method: 'POST',
372
+ headers,
373
+ body,
374
+ keepalive: true,
375
+ });
376
+ this.log(`Successfully sent ${events.length} events via fetch (keepalive)`);
377
+ }
378
+ catch (error) {
379
+ // Log error gracefully for beacon failures (page unload scenarios)
380
+ const formattedError = this.formatError(error, 'sendEventsWithBeacon', events);
381
+ this.logError(formattedError);
382
+ }
383
+ }
384
+ startFlushTimer() {
385
+ if (this.flushTimer) {
386
+ clearInterval(this.flushTimer);
387
+ }
388
+ this.flushTimer = window.setInterval(() => {
389
+ if (this.eventQueue.length > 0) {
390
+ this.flush().catch((error) => {
391
+ const formattedError = this.formatError(error, 'auto-flush');
392
+ this.logError(formattedError);
393
+ });
394
+ }
395
+ }, this.config.flushInterval);
396
+ }
397
+ setupBeforeUnload() {
398
+ if (typeof window === 'undefined')
399
+ return;
400
+ const handleBeforeUnload = () => {
401
+ if (this.eventQueue.length > 0) {
402
+ // Use beacon API for reliable delivery during page unload
403
+ const eventsToSend = [...this.eventQueue];
404
+ this.eventQueue = [];
405
+ const chunks = this.chunkEvents(eventsToSend, this.config.maxEventsPerRequest);
406
+ // Send first chunk with beacon (most important for page unload)
407
+ if (chunks.length > 0) {
408
+ this.sendEventsWithBeacon(chunks[0]).catch(() => {
409
+ // Silently fail - page is unloading
410
+ });
411
+ }
412
+ }
413
+ };
414
+ // Handle page unload
415
+ window.addEventListener('beforeunload', handleBeforeUnload);
416
+ window.addEventListener('pagehide', handleBeforeUnload);
417
+ // Handle visibility change (page hidden)
418
+ document.addEventListener('visibilitychange', () => {
419
+ if (document.visibilityState === 'hidden' && this.eventQueue.length > 0) {
420
+ const eventsToSend = [...this.eventQueue];
421
+ this.eventQueue = [];
422
+ const chunks = this.chunkEvents(eventsToSend, this.config.maxEventsPerRequest);
423
+ // Send first chunk with beacon (most important for page hidden)
424
+ if (chunks.length > 0) {
425
+ this.sendEventsWithBeacon(chunks[0]).catch(() => {
426
+ // Silently fail
427
+ });
428
+ }
429
+ }
430
+ });
431
+ }
432
+ async track(eventOrName, propertiesOrOptions, options) {
433
+ try {
434
+ if (this.isDestroyed) {
435
+ const error = new Error('Grain Analytics: Client has been destroyed');
436
+ const formattedError = this.formatError(error, 'track (client destroyed)');
437
+ this.logError(formattedError);
438
+ return;
439
+ }
440
+ let event;
441
+ let opts = {};
442
+ if (typeof eventOrName === 'string') {
443
+ event = {
444
+ eventName: eventOrName,
445
+ properties: propertiesOrOptions,
446
+ };
447
+ opts = options || {};
448
+ }
449
+ else {
450
+ event = eventOrName;
451
+ opts = propertiesOrOptions || {};
452
+ }
453
+ const formattedEvent = this.formatEvent(event);
454
+ this.eventQueue.push(formattedEvent);
455
+ this.log(`Queued event: ${event.eventName}`, event.properties);
456
+ // Check if we should flush immediately
457
+ if (opts.flush || this.eventQueue.length >= this.config.batchSize) {
458
+ await this.flush();
459
+ }
460
+ }
461
+ catch (error) {
462
+ const formattedError = this.formatError(error, 'track');
463
+ this.logError(formattedError);
464
+ }
465
+ }
466
+ /**
467
+ * Identify a user (sets userId for subsequent events)
468
+ */
469
+ identify(userId) {
470
+ this.log(`Identified user: ${userId}`);
471
+ this.globalUserId = userId;
472
+ // Clear persistent anonymous user ID since we now have a real user ID
473
+ this.persistentAnonymousUserId = null;
474
+ }
475
+ /**
476
+ * Set global user ID for all subsequent events
477
+ */
478
+ setUserId(userId) {
479
+ this.log(`Set global user ID: ${userId}`);
480
+ this.globalUserId = userId;
481
+ if (userId) {
482
+ // Clear persistent anonymous user ID if setting a real user ID
483
+ this.persistentAnonymousUserId = null;
484
+ }
485
+ else {
486
+ // If clearing user ID, ensure we have a UUIDv4 identifier
487
+ if (!this.persistentAnonymousUserId) {
488
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
489
+ // Try to persist the new anonymous ID
490
+ if (typeof window !== 'undefined') {
491
+ try {
492
+ const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
493
+ localStorage.setItem(storageKey, this.persistentAnonymousUserId);
494
+ }
495
+ catch (error) {
496
+ this.log('Failed to persist new anonymous user ID:', error);
497
+ }
498
+ }
499
+ }
500
+ }
501
+ }
502
+ /**
503
+ * Get current global user ID
504
+ */
505
+ getUserId() {
506
+ return this.globalUserId;
507
+ }
508
+ /**
509
+ * Get current effective user ID (global userId or persistent anonymous ID)
510
+ */
511
+ getEffectiveUserIdPublic() {
512
+ return this.getEffectiveUserId();
513
+ }
514
+ /**
515
+ * Login with auth token or userId on the fly
516
+ *
517
+ * @example
518
+ * // Login with userId only
519
+ * client.login({ userId: 'user123' });
520
+ *
521
+ * // Login with auth token (automatically sets authStrategy to JWT)
522
+ * client.login({ authToken: 'jwt-token-here' });
523
+ *
524
+ * // Login with both userId and auth token
525
+ * client.login({ userId: 'user123', authToken: 'jwt-token-here' });
526
+ *
527
+ * // Override auth strategy
528
+ * client.login({ userId: 'user123', authStrategy: 'SERVER_SIDE' });
529
+ */
530
+ login(options) {
531
+ try {
532
+ if (this.isDestroyed) {
533
+ const error = new Error('Grain Analytics: Client has been destroyed');
534
+ const formattedError = this.formatError(error, 'login (client destroyed)');
535
+ this.logError(formattedError);
536
+ return;
537
+ }
538
+ // Set userId if provided
539
+ if (options.userId) {
540
+ this.log(`Login: Setting user ID to ${options.userId}`);
541
+ this.globalUserId = options.userId;
542
+ // Clear persistent anonymous user ID since we now have a real user ID
543
+ this.persistentAnonymousUserId = null;
544
+ }
545
+ // Handle auth token if provided
546
+ if (options.authToken) {
547
+ this.log('Login: Setting auth token');
548
+ // Update auth strategy to JWT if not already set
549
+ if (this.config.authStrategy === 'NONE') {
550
+ this.config.authStrategy = 'JWT';
551
+ }
552
+ // Create a simple auth provider that returns the provided token
553
+ this.config.authProvider = {
554
+ getToken: () => options.authToken
555
+ };
556
+ }
557
+ // Override auth strategy if provided
558
+ if (options.authStrategy) {
559
+ this.log(`Login: Setting auth strategy to ${options.authStrategy}`);
560
+ this.config.authStrategy = options.authStrategy;
561
+ }
562
+ this.log(`Login successful. Effective user ID: ${this.getEffectiveUserId()}`);
563
+ }
564
+ catch (error) {
565
+ const formattedError = this.formatError(error, 'login');
566
+ this.logError(formattedError);
567
+ }
568
+ }
569
+ /**
570
+ * Logout and clear user session, fall back to UUIDv4 identifier
571
+ *
572
+ * @example
573
+ * // Logout user and return to anonymous mode
574
+ * client.logout();
575
+ *
576
+ * // After logout, events will use the persistent UUIDv4 identifier
577
+ * client.track('page_view', { page: 'home' });
578
+ */
579
+ logout() {
580
+ try {
581
+ if (this.isDestroyed) {
582
+ const error = new Error('Grain Analytics: Client has been destroyed');
583
+ const formattedError = this.formatError(error, 'logout (client destroyed)');
584
+ this.logError(formattedError);
585
+ return;
586
+ }
587
+ this.log('Logout: Clearing user session');
588
+ // Clear global user ID
589
+ this.globalUserId = null;
590
+ // Reset auth strategy to NONE
591
+ this.config.authStrategy = 'NONE';
592
+ this.config.authProvider = undefined;
593
+ // Generate new UUIDv4 identifier if we don't have one
594
+ if (!this.persistentAnonymousUserId) {
595
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
596
+ // Try to persist the new anonymous ID
597
+ if (typeof window !== 'undefined') {
598
+ try {
599
+ const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
600
+ localStorage.setItem(storageKey, this.persistentAnonymousUserId);
601
+ }
602
+ catch (error) {
603
+ this.log('Failed to persist new anonymous user ID after logout:', error);
604
+ }
605
+ }
606
+ }
607
+ this.log(`Logout successful. Effective user ID: ${this.getEffectiveUserId()}`);
608
+ }
609
+ catch (error) {
610
+ const formattedError = this.formatError(error, 'logout');
611
+ this.logError(formattedError);
612
+ }
613
+ }
614
+ /**
615
+ * Set user properties
616
+ */
617
+ async setProperty(properties, options) {
618
+ try {
619
+ if (this.isDestroyed) {
620
+ const error = new Error('Grain Analytics: Client has been destroyed');
621
+ const formattedError = this.formatError(error, 'setProperty (client destroyed)');
622
+ this.logError(formattedError);
623
+ return;
624
+ }
625
+ const userId = options?.userId || this.getEffectiveUserId();
626
+ // Validate property count (max 4 properties)
627
+ const propertyKeys = Object.keys(properties);
628
+ if (propertyKeys.length > 4) {
629
+ const error = new Error('Grain Analytics: Maximum 4 properties allowed per request');
630
+ const formattedError = this.formatError(error, 'setProperty (validation)');
631
+ this.logError(formattedError);
632
+ return;
633
+ }
634
+ if (propertyKeys.length === 0) {
635
+ const error = new Error('Grain Analytics: At least one property is required');
636
+ const formattedError = this.formatError(error, 'setProperty (validation)');
637
+ this.logError(formattedError);
638
+ return;
639
+ }
640
+ // Serialize all values to strings
641
+ const serializedProperties = {};
642
+ for (const [key, value] of Object.entries(properties)) {
643
+ if (value === null || value === undefined) {
644
+ serializedProperties[key] = '';
645
+ }
646
+ else if (typeof value === 'string') {
647
+ serializedProperties[key] = value;
648
+ }
649
+ else {
650
+ serializedProperties[key] = JSON.stringify(value);
651
+ }
652
+ }
653
+ const payload = {
654
+ userId,
655
+ ...serializedProperties,
656
+ };
657
+ await this.sendProperties(payload);
658
+ }
659
+ catch (error) {
660
+ const formattedError = this.formatError(error, 'setProperty');
661
+ this.logError(formattedError);
662
+ }
663
+ }
664
+ /**
665
+ * Send properties to the API
666
+ */
667
+ async sendProperties(payload) {
668
+ let lastError;
669
+ for (let attempt = 0; attempt <= this.config.retryAttempts; attempt++) {
670
+ try {
671
+ const headers = await this.getAuthHeaders();
672
+ const url = `${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/properties`;
673
+ this.log(`Setting properties for user ${payload.userId} (attempt ${attempt + 1})`);
674
+ const response = await fetch(url, {
675
+ method: 'POST',
676
+ headers,
677
+ body: JSON.stringify(payload),
678
+ });
679
+ if (!response.ok) {
680
+ let errorMessage = `HTTP ${response.status}`;
681
+ try {
682
+ const errorBody = await response.json();
683
+ if (errorBody?.message) {
684
+ errorMessage = errorBody.message;
685
+ }
686
+ }
687
+ catch {
688
+ const errorText = await response.text();
689
+ if (errorText) {
690
+ errorMessage = errorText;
691
+ }
692
+ }
693
+ const error = new Error(`Failed to set properties: ${errorMessage}`);
694
+ error.status = response.status;
695
+ throw error;
696
+ }
697
+ this.log(`Successfully set properties for user ${payload.userId}`);
698
+ return; // Success, exit retry loop
699
+ }
700
+ catch (error) {
701
+ lastError = error;
702
+ if (attempt === this.config.retryAttempts) {
703
+ // Last attempt, don't retry - log error gracefully
704
+ const formattedError = this.formatError(error, `sendProperties (attempt ${attempt + 1}/${this.config.retryAttempts + 1})`);
705
+ this.logError(formattedError);
706
+ return; // Don't throw, just return gracefully
707
+ }
708
+ if (!this.isRetriableError(error)) {
709
+ // Non-retriable error, don't retry - log error gracefully
710
+ const formattedError = this.formatError(error, 'sendProperties (non-retriable error)');
711
+ this.logError(formattedError);
712
+ return; // Don't throw, just return gracefully
713
+ }
714
+ const delayMs = this.config.retryDelay * Math.pow(2, attempt); // Exponential backoff
715
+ this.log(`Retrying in ${delayMs}ms after error:`, error);
716
+ await this.delay(delayMs);
717
+ }
718
+ }
719
+ }
720
+ // Template event methods
721
+ /**
722
+ * Track user login event
723
+ */
724
+ async trackLogin(properties, options) {
725
+ try {
726
+ return await this.track('login', properties, options);
727
+ }
728
+ catch (error) {
729
+ const formattedError = this.formatError(error, 'trackLogin');
730
+ this.logError(formattedError);
731
+ }
732
+ }
733
+ /**
734
+ * Track user signup event
735
+ */
736
+ async trackSignup(properties, options) {
737
+ try {
738
+ return await this.track('signup', properties, options);
739
+ }
740
+ catch (error) {
741
+ const formattedError = this.formatError(error, 'trackSignup');
742
+ this.logError(formattedError);
743
+ }
744
+ }
745
+ /**
746
+ * Track checkout event
747
+ */
748
+ async trackCheckout(properties, options) {
749
+ try {
750
+ return await this.track('checkout', properties, options);
751
+ }
752
+ catch (error) {
753
+ const formattedError = this.formatError(error, 'trackCheckout');
754
+ this.logError(formattedError);
755
+ }
756
+ }
757
+ /**
758
+ * Track page view event
759
+ */
760
+ async trackPageView(properties, options) {
761
+ try {
762
+ return await this.track('page_view', properties, options);
763
+ }
764
+ catch (error) {
765
+ const formattedError = this.formatError(error, 'trackPageView');
766
+ this.logError(formattedError);
767
+ }
768
+ }
769
+ /**
770
+ * Track purchase event
771
+ */
772
+ async trackPurchase(properties, options) {
773
+ try {
774
+ return await this.track('purchase', properties, options);
775
+ }
776
+ catch (error) {
777
+ const formattedError = this.formatError(error, 'trackPurchase');
778
+ this.logError(formattedError);
779
+ }
780
+ }
781
+ /**
782
+ * Track search event
783
+ */
784
+ async trackSearch(properties, options) {
785
+ try {
786
+ return await this.track('search', properties, options);
787
+ }
788
+ catch (error) {
789
+ const formattedError = this.formatError(error, 'trackSearch');
790
+ this.logError(formattedError);
791
+ }
792
+ }
793
+ /**
794
+ * Track add to cart event
795
+ */
796
+ async trackAddToCart(properties, options) {
797
+ try {
798
+ return await this.track('add_to_cart', properties, options);
799
+ }
800
+ catch (error) {
801
+ const formattedError = this.formatError(error, 'trackAddToCart');
802
+ this.logError(formattedError);
803
+ }
804
+ }
805
+ /**
806
+ * Track remove from cart event
807
+ */
808
+ async trackRemoveFromCart(properties, options) {
809
+ try {
810
+ return await this.track('remove_from_cart', properties, options);
811
+ }
812
+ catch (error) {
813
+ const formattedError = this.formatError(error, 'trackRemoveFromCart');
814
+ this.logError(formattedError);
815
+ }
816
+ }
817
+ /**
818
+ * Manually flush all queued events
819
+ */
820
+ async flush() {
821
+ try {
822
+ if (this.eventQueue.length === 0)
823
+ return;
824
+ const eventsToSend = [...this.eventQueue];
825
+ this.eventQueue = [];
826
+ // Split events into chunks to respect maxEventsPerRequest limit
827
+ const chunks = this.chunkEvents(eventsToSend, this.config.maxEventsPerRequest);
828
+ // Send all chunks sequentially to maintain order
829
+ for (const chunk of chunks) {
830
+ await this.sendEvents(chunk);
831
+ }
832
+ }
833
+ catch (error) {
834
+ const formattedError = this.formatError(error, 'flush');
835
+ this.logError(formattedError);
836
+ }
837
+ }
838
+ // Remote Config Methods
839
+ /**
840
+ * Initialize configuration cache from localStorage
841
+ */
842
+ initializeConfigCache() {
843
+ if (!this.config.enableConfigCache || typeof window === 'undefined')
844
+ return;
845
+ try {
846
+ const cached = localStorage.getItem(this.config.configCacheKey);
847
+ if (cached) {
848
+ this.configCache = JSON.parse(cached);
849
+ this.log('Loaded configuration from cache:', this.configCache);
850
+ }
851
+ }
852
+ catch (error) {
853
+ this.log('Failed to load configuration cache:', error);
854
+ }
855
+ }
856
+ /**
857
+ * Save configuration cache to localStorage
858
+ */
859
+ saveConfigCache(cache) {
860
+ if (!this.config.enableConfigCache || typeof window === 'undefined')
861
+ return;
862
+ try {
863
+ localStorage.setItem(this.config.configCacheKey, JSON.stringify(cache));
864
+ this.log('Saved configuration to cache:', cache);
865
+ }
866
+ catch (error) {
867
+ this.log('Failed to save configuration cache:', error);
868
+ }
869
+ }
870
+ /**
871
+ * Get configuration value with fallback to defaults
872
+ */
873
+ getConfig(key) {
874
+ // First check cache
875
+ if (this.configCache?.configurations?.[key]) {
876
+ return this.configCache.configurations[key];
877
+ }
878
+ // Then check defaults
879
+ if (this.config.defaultConfigurations?.[key]) {
880
+ return this.config.defaultConfigurations[key];
881
+ }
882
+ return undefined;
883
+ }
884
+ /**
885
+ * Get all configurations with fallback to defaults
886
+ */
887
+ getAllConfigs() {
888
+ const configs = { ...this.config.defaultConfigurations };
889
+ if (this.configCache?.configurations) {
890
+ Object.assign(configs, this.configCache.configurations);
891
+ }
892
+ return configs;
893
+ }
894
+ /**
895
+ * Fetch configurations from API
896
+ */
897
+ async fetchConfig(options = {}) {
898
+ try {
899
+ if (this.isDestroyed) {
900
+ const error = new Error('Grain Analytics: Client has been destroyed');
901
+ const formattedError = this.formatError(error, 'fetchConfig (client destroyed)');
902
+ this.logError(formattedError);
903
+ return null;
904
+ }
905
+ const userId = options.userId || this.getEffectiveUserId();
906
+ const immediateKeys = options.immediateKeys || [];
907
+ const properties = options.properties || {};
908
+ const request = {
909
+ userId,
910
+ immediateKeys,
911
+ properties,
912
+ };
913
+ let lastError;
914
+ for (let attempt = 0; attempt <= this.config.retryAttempts; attempt++) {
915
+ try {
916
+ const headers = await this.getAuthHeaders();
917
+ const url = `${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/config/configurations`;
918
+ this.log(`Fetching configurations for user ${userId} (attempt ${attempt + 1})`);
919
+ const response = await fetch(url, {
920
+ method: 'POST',
921
+ headers,
922
+ body: JSON.stringify(request),
923
+ });
924
+ if (!response.ok) {
925
+ let errorMessage = `HTTP ${response.status}`;
926
+ try {
927
+ const errorBody = await response.json();
928
+ if (errorBody?.message) {
929
+ errorMessage = errorBody.message;
930
+ }
931
+ }
932
+ catch {
933
+ const errorText = await response.text();
934
+ if (errorText) {
935
+ errorMessage = errorText;
936
+ }
937
+ }
938
+ const error = new Error(`Failed to fetch configurations: ${errorMessage}`);
939
+ error.status = response.status;
940
+ throw error;
941
+ }
942
+ const configResponse = await response.json();
943
+ // Update cache if successful
944
+ if (configResponse.configurations) {
945
+ this.updateConfigCache(configResponse, userId);
946
+ }
947
+ this.log(`Successfully fetched configurations for user ${userId}:`, configResponse);
948
+ return configResponse;
949
+ }
950
+ catch (error) {
951
+ lastError = error;
952
+ if (attempt === this.config.retryAttempts) {
953
+ // Last attempt, don't retry - log error gracefully
954
+ const formattedError = this.formatError(error, `fetchConfig (attempt ${attempt + 1}/${this.config.retryAttempts + 1})`);
955
+ this.logError(formattedError);
956
+ return null;
957
+ }
958
+ if (!this.isRetriableError(error)) {
959
+ // Non-retriable error, don't retry - log error gracefully
960
+ const formattedError = this.formatError(error, 'fetchConfig (non-retriable error)');
961
+ this.logError(formattedError);
962
+ return null;
963
+ }
964
+ const delayMs = this.config.retryDelay * Math.pow(2, attempt);
965
+ this.log(`Retrying config fetch in ${delayMs}ms after error:`, error);
966
+ await this.delay(delayMs);
967
+ }
968
+ }
969
+ return null;
970
+ }
971
+ catch (error) {
972
+ const formattedError = this.formatError(error, 'fetchConfig');
973
+ this.logError(formattedError);
974
+ return null;
975
+ }
976
+ }
977
+ /**
978
+ * Get configuration asynchronously (cache-first with fallback to API)
979
+ */
980
+ async getConfigAsync(key, options = {}) {
981
+ try {
982
+ // Return immediately if we have it in cache and not forcing refresh
983
+ if (!options.forceRefresh && this.configCache?.configurations?.[key]) {
984
+ return this.configCache.configurations[key];
985
+ }
986
+ // Return default if available and not forcing refresh
987
+ if (!options.forceRefresh && this.config.defaultConfigurations?.[key]) {
988
+ return this.config.defaultConfigurations[key];
989
+ }
990
+ // Fetch from API
991
+ const response = await this.fetchConfig(options);
992
+ if (response) {
993
+ return response.configurations[key];
994
+ }
995
+ // Return default as fallback
996
+ return this.config.defaultConfigurations?.[key];
997
+ }
998
+ catch (error) {
999
+ const formattedError = this.formatError(error, 'getConfigAsync');
1000
+ this.logError(formattedError);
1001
+ // Return default as fallback
1002
+ return this.config.defaultConfigurations?.[key];
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Get all configurations asynchronously (cache-first with fallback to API)
1007
+ */
1008
+ async getAllConfigsAsync(options = {}) {
1009
+ try {
1010
+ // Return cache if available and not forcing refresh
1011
+ if (!options.forceRefresh && this.configCache?.configurations) {
1012
+ return { ...this.config.defaultConfigurations, ...this.configCache.configurations };
1013
+ }
1014
+ // Fetch from API
1015
+ const response = await this.fetchConfig(options);
1016
+ if (response) {
1017
+ return { ...this.config.defaultConfigurations, ...response.configurations };
1018
+ }
1019
+ // Return defaults as fallback
1020
+ return { ...this.config.defaultConfigurations };
1021
+ }
1022
+ catch (error) {
1023
+ const formattedError = this.formatError(error, 'getAllConfigsAsync');
1024
+ this.logError(formattedError);
1025
+ // Return defaults as fallback
1026
+ return { ...this.config.defaultConfigurations };
1027
+ }
1028
+ }
1029
+ /**
1030
+ * Update configuration cache and notify listeners
1031
+ */
1032
+ updateConfigCache(response, userId) {
1033
+ const newCache = {
1034
+ configurations: response.configurations,
1035
+ snapshotId: response.snapshotId,
1036
+ timestamp: response.timestamp,
1037
+ userId,
1038
+ };
1039
+ const oldConfigs = this.configCache?.configurations || {};
1040
+ this.configCache = newCache;
1041
+ this.saveConfigCache(newCache);
1042
+ // Notify listeners if configurations changed
1043
+ if (JSON.stringify(oldConfigs) !== JSON.stringify(response.configurations)) {
1044
+ this.notifyConfigChangeListeners(response.configurations);
1045
+ }
1046
+ }
1047
+ /**
1048
+ * Add configuration change listener
1049
+ */
1050
+ addConfigChangeListener(listener) {
1051
+ this.configChangeListeners.push(listener);
1052
+ }
1053
+ /**
1054
+ * Remove configuration change listener
1055
+ */
1056
+ removeConfigChangeListener(listener) {
1057
+ const index = this.configChangeListeners.indexOf(listener);
1058
+ if (index > -1) {
1059
+ this.configChangeListeners.splice(index, 1);
1060
+ }
1061
+ }
1062
+ /**
1063
+ * Notify all configuration change listeners
1064
+ */
1065
+ notifyConfigChangeListeners(configurations) {
1066
+ this.configChangeListeners.forEach(listener => {
1067
+ try {
1068
+ listener(configurations);
1069
+ }
1070
+ catch (error) {
1071
+ console.error('[Grain Analytics] Config change listener error:', error);
1072
+ }
1073
+ });
1074
+ }
1075
+ /**
1076
+ * Start automatic configuration refresh timer
1077
+ */
1078
+ startConfigRefreshTimer() {
1079
+ if (this.configRefreshTimer) {
1080
+ clearInterval(this.configRefreshTimer);
1081
+ }
1082
+ this.configRefreshTimer = window.setInterval(() => {
1083
+ if (!this.isDestroyed) {
1084
+ // Use effective userId (will be generated if not set)
1085
+ this.fetchConfig().catch((error) => {
1086
+ const formattedError = this.formatError(error, 'auto-config refresh');
1087
+ this.logError(formattedError);
1088
+ });
1089
+ }
1090
+ }, this.config.configRefreshInterval);
1091
+ }
1092
+ /**
1093
+ * Stop automatic configuration refresh timer
1094
+ */
1095
+ stopConfigRefreshTimer() {
1096
+ if (this.configRefreshTimer) {
1097
+ clearInterval(this.configRefreshTimer);
1098
+ this.configRefreshTimer = null;
1099
+ }
1100
+ }
1101
+ /**
1102
+ * Preload configurations for immediate access
1103
+ */
1104
+ async preloadConfig(immediateKeys = [], properties) {
1105
+ try {
1106
+ // Use effective userId (will be generated if not set)
1107
+ const effectiveUserId = this.getEffectiveUserId();
1108
+ this.log(`Preloading config for user: ${effectiveUserId}`);
1109
+ const response = await this.fetchConfig({ immediateKeys, properties });
1110
+ if (response) {
1111
+ this.startConfigRefreshTimer();
1112
+ }
1113
+ }
1114
+ catch (error) {
1115
+ const formattedError = this.formatError(error, 'preloadConfig');
1116
+ this.logError(formattedError);
1117
+ }
1118
+ }
1119
+ /**
1120
+ * Split events array into chunks of specified size
1121
+ */
1122
+ chunkEvents(events, chunkSize) {
1123
+ const chunks = [];
1124
+ for (let i = 0; i < events.length; i += chunkSize) {
1125
+ chunks.push(events.slice(i, i + chunkSize));
1126
+ }
1127
+ return chunks;
1128
+ }
1129
+ /**
1130
+ * Destroy the client and clean up resources
1131
+ */
1132
+ destroy() {
1133
+ this.isDestroyed = true;
1134
+ if (this.flushTimer) {
1135
+ clearInterval(this.flushTimer);
1136
+ this.flushTimer = null;
1137
+ }
1138
+ // Stop config refresh timer
1139
+ this.stopConfigRefreshTimer();
1140
+ // Clear config change listeners
1141
+ this.configChangeListeners = [];
1142
+ // Send any remaining events (in chunks if necessary)
1143
+ if (this.eventQueue.length > 0) {
1144
+ const eventsToSend = [...this.eventQueue];
1145
+ this.eventQueue = [];
1146
+ const chunks = this.chunkEvents(eventsToSend, this.config.maxEventsPerRequest);
1147
+ // Send first chunk with beacon (most important for page unload)
1148
+ if (chunks.length > 0) {
1149
+ this.sendEventsWithBeacon(chunks[0]).catch(() => {
1150
+ // Silently fail during cleanup
1151
+ });
1152
+ // If there are more chunks, try to send them with regular fetch
1153
+ for (let i = 1; i < chunks.length; i++) {
1154
+ this.sendEventsWithBeacon(chunks[i]).catch(() => {
1155
+ // Silently fail during cleanup
1156
+ });
1157
+ }
1158
+ }
1159
+ }
1160
+ }
1161
+ }
1162
+ /**
1163
+ * Create a new Grain Analytics client
1164
+ */
1165
+ export function createGrainAnalytics(config) {
1166
+ return new GrainAnalytics(config);
1167
+ }
1168
+ // Default export for convenience
1169
+ export default GrainAnalytics;
1170
+ // Auto-setup for IIFE build
1171
+ if (typeof window !== 'undefined') {
1172
+ window.Grain = {
1173
+ GrainAnalytics,
1174
+ createGrainAnalytics,
1175
+ };
1176
+ }