@grainql/analytics-web 2.1.3 → 2.2.1

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 (106) hide show
  1. package/dist/cjs/consent.d.ts +4 -0
  2. package/dist/cjs/consent.d.ts.map +1 -1
  3. package/dist/cjs/consent.js +5 -0
  4. package/dist/cjs/consent.js.map +1 -1
  5. package/dist/cjs/index.d.ts +20 -0
  6. package/dist/cjs/index.d.ts.map +1 -1
  7. package/dist/cjs/index.js.map +1 -1
  8. package/dist/consent.d.ts +4 -0
  9. package/dist/consent.d.ts.map +1 -1
  10. package/dist/consent.js +5 -0
  11. package/dist/esm/consent.d.ts +4 -0
  12. package/dist/esm/consent.d.ts.map +1 -1
  13. package/dist/esm/consent.js +5 -0
  14. package/dist/esm/consent.js.map +1 -1
  15. package/dist/esm/index.d.ts +20 -0
  16. package/dist/esm/index.d.ts.map +1 -1
  17. package/dist/esm/index.js.map +1 -1
  18. package/dist/index.d.ts +20 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.global.dev.js +45 -17
  21. package/dist/index.global.dev.js.map +2 -2
  22. package/dist/index.global.js +2 -2
  23. package/dist/index.global.js.map +3 -3
  24. package/dist/index.js +48 -22
  25. package/dist/index.mjs +48 -22
  26. package/dist/react/index.d.ts +44 -499
  27. package/dist/react/index.d.ts.map +1 -1
  28. package/dist/react/index.js +54 -1491
  29. package/dist/react/index.mjs +42 -1488
  30. package/package.json +1 -1
  31. package/dist/react/activity.d.ts +0 -59
  32. package/dist/react/activity.d.ts.map +0 -1
  33. package/dist/react/activity.js +0 -130
  34. package/dist/react/activity.mjs +0 -126
  35. package/dist/react/consent.d.ts +0 -68
  36. package/dist/react/consent.d.ts.map +0 -1
  37. package/dist/react/consent.js +0 -190
  38. package/dist/react/consent.mjs +0 -186
  39. package/dist/react/cookies.d.ts +0 -28
  40. package/dist/react/cookies.d.ts.map +0 -1
  41. package/dist/react/cookies.js +0 -94
  42. package/dist/react/cookies.mjs +0 -88
  43. package/dist/react/heartbeat.d.ts +0 -47
  44. package/dist/react/heartbeat.d.ts.map +0 -1
  45. package/dist/react/heartbeat.js +0 -119
  46. package/dist/react/heartbeat.mjs +0 -115
  47. package/dist/react/page-tracking.d.ts +0 -60
  48. package/dist/react/page-tracking.d.ts.map +0 -1
  49. package/dist/react/page-tracking.js +0 -179
  50. package/dist/react/page-tracking.mjs +0 -175
  51. package/dist/react/react/index.d.ts +0 -47
  52. package/dist/react/react/index.d.ts.map +0 -1
  53. package/dist/react/react/index.js +0 -58
  54. package/dist/react/react/index.mjs +0 -44
  55. /package/dist/react/{react/GrainProvider.d.ts → GrainProvider.d.ts} +0 -0
  56. /package/dist/react/{react/GrainProvider.d.ts.map → GrainProvider.d.ts.map} +0 -0
  57. /package/dist/react/{react/GrainProvider.js → GrainProvider.js} +0 -0
  58. /package/dist/react/{react/GrainProvider.mjs → GrainProvider.mjs} +0 -0
  59. /package/dist/react/{react/components → components}/ConsentBanner.d.ts +0 -0
  60. /package/dist/react/{react/components → components}/ConsentBanner.d.ts.map +0 -0
  61. /package/dist/react/{react/components → components}/ConsentBanner.js +0 -0
  62. /package/dist/react/{react/components → components}/ConsentBanner.mjs +0 -0
  63. /package/dist/react/{react/components → components}/CookieNotice.d.ts +0 -0
  64. /package/dist/react/{react/components → components}/CookieNotice.d.ts.map +0 -0
  65. /package/dist/react/{react/components → components}/CookieNotice.js +0 -0
  66. /package/dist/react/{react/components → components}/CookieNotice.mjs +0 -0
  67. /package/dist/react/{react/components → components}/PrivacyPreferenceCenter.d.ts +0 -0
  68. /package/dist/react/{react/components → components}/PrivacyPreferenceCenter.d.ts.map +0 -0
  69. /package/dist/react/{react/components → components}/PrivacyPreferenceCenter.js +0 -0
  70. /package/dist/react/{react/components → components}/PrivacyPreferenceCenter.mjs +0 -0
  71. /package/dist/react/{react/context.d.ts → context.d.ts} +0 -0
  72. /package/dist/react/{react/context.d.ts.map → context.d.ts.map} +0 -0
  73. /package/dist/react/{react/context.js → context.js} +0 -0
  74. /package/dist/react/{react/context.mjs → context.mjs} +0 -0
  75. /package/dist/react/{react/hooks → hooks}/useAllConfigs.d.ts +0 -0
  76. /package/dist/react/{react/hooks → hooks}/useAllConfigs.d.ts.map +0 -0
  77. /package/dist/react/{react/hooks → hooks}/useAllConfigs.js +0 -0
  78. /package/dist/react/{react/hooks → hooks}/useAllConfigs.mjs +0 -0
  79. /package/dist/react/{react/hooks → hooks}/useConfig.d.ts +0 -0
  80. /package/dist/react/{react/hooks → hooks}/useConfig.d.ts.map +0 -0
  81. /package/dist/react/{react/hooks → hooks}/useConfig.js +0 -0
  82. /package/dist/react/{react/hooks → hooks}/useConfig.mjs +0 -0
  83. /package/dist/react/{react/hooks → hooks}/useConsent.d.ts +0 -0
  84. /package/dist/react/{react/hooks → hooks}/useConsent.d.ts.map +0 -0
  85. /package/dist/react/{react/hooks → hooks}/useConsent.js +0 -0
  86. /package/dist/react/{react/hooks → hooks}/useConsent.mjs +0 -0
  87. /package/dist/react/{react/hooks → hooks}/useDataDeletion.d.ts +0 -0
  88. /package/dist/react/{react/hooks → hooks}/useDataDeletion.d.ts.map +0 -0
  89. /package/dist/react/{react/hooks → hooks}/useDataDeletion.js +0 -0
  90. /package/dist/react/{react/hooks → hooks}/useDataDeletion.mjs +0 -0
  91. /package/dist/react/{react/hooks → hooks}/useGrainAnalytics.d.ts +0 -0
  92. /package/dist/react/{react/hooks → hooks}/useGrainAnalytics.d.ts.map +0 -0
  93. /package/dist/react/{react/hooks → hooks}/useGrainAnalytics.js +0 -0
  94. /package/dist/react/{react/hooks → hooks}/useGrainAnalytics.mjs +0 -0
  95. /package/dist/react/{react/hooks → hooks}/usePrivacyPreferences.d.ts +0 -0
  96. /package/dist/react/{react/hooks → hooks}/usePrivacyPreferences.d.ts.map +0 -0
  97. /package/dist/react/{react/hooks → hooks}/usePrivacyPreferences.js +0 -0
  98. /package/dist/react/{react/hooks → hooks}/usePrivacyPreferences.mjs +0 -0
  99. /package/dist/react/{react/hooks → hooks}/useTrack.d.ts +0 -0
  100. /package/dist/react/{react/hooks → hooks}/useTrack.d.ts.map +0 -0
  101. /package/dist/react/{react/hooks → hooks}/useTrack.js +0 -0
  102. /package/dist/react/{react/hooks → hooks}/useTrack.mjs +0 -0
  103. /package/dist/react/{react/types.d.ts → types.d.ts} +0 -0
  104. /package/dist/react/{react/types.d.ts.map → types.d.ts.map} +0 -0
  105. /package/dist/react/{react/types.js → types.js} +0 -0
  106. /package/dist/react/{react/types.mjs → types.mjs} +0 -0
@@ -1,1490 +1,44 @@
1
1
  /**
2
- * Grain Analytics Web SDK
3
- * A lightweight, dependency-free TypeScript SDK for sending analytics events to Grain's REST API
2
+ * Grain Analytics React Hooks
3
+ *
4
+ * React integration for @grainql/analytics-web
5
+ *
6
+ * @example
7
+ * ```tsx
8
+ * import { GrainProvider, useConfig, useTrack } from '@grainql/analytics-web/react';
9
+ *
10
+ * // Pattern 1: Provider-managed client
11
+ * <GrainProvider config={{ tenantId: 'xxx' }}>
12
+ * <App />
13
+ * </GrainProvider>
14
+ *
15
+ * // Pattern 2: External client
16
+ * const grain = new GrainAnalytics({ tenantId: 'xxx' });
17
+ * <GrainProvider client={grain}>
18
+ * <App />
19
+ * </GrainProvider>
20
+ *
21
+ * // Use hooks in components
22
+ * function MyComponent() {
23
+ * const { value } = useConfig('hero_variant');
24
+ * const track = useTrack();
25
+ *
26
+ * return <button onClick={() => track('clicked')}>Click</button>;
27
+ * }
28
+ * ```
4
29
  */
5
- import { ConsentManager } from './consent';
6
- import { setCookie, getCookie, areCookiesEnabled } from './cookies';
7
- import { ActivityDetector } from './activity';
8
- import { HeartbeatManager } from './heartbeat';
9
- import { PageTrackingManager } from './page-tracking';
10
- export class GrainAnalytics {
11
- constructor(config) {
12
- this.eventQueue = [];
13
- this.waitingForConsentQueue = [];
14
- this.flushTimer = null;
15
- this.isDestroyed = false;
16
- this.globalUserId = null;
17
- this.persistentAnonymousUserId = null;
18
- // Remote Config properties
19
- this.configCache = null;
20
- this.configRefreshTimer = null;
21
- this.configChangeListeners = [];
22
- this.configFetchPromise = null;
23
- this.cookiesEnabled = false;
24
- // Automatic Tracking properties
25
- this.activityDetector = null;
26
- this.heartbeatManager = null;
27
- this.pageTrackingManager = null;
28
- this.ephemeralSessionId = null;
29
- this.eventCountSinceLastHeartbeat = 0;
30
- this.config = {
31
- apiUrl: 'https://api.grainql.com',
32
- authStrategy: 'NONE',
33
- batchSize: 50,
34
- flushInterval: 5000, // 5 seconds
35
- retryAttempts: 3,
36
- retryDelay: 1000, // 1 second
37
- maxEventsPerRequest: 160, // Maximum events per API request
38
- debug: false,
39
- // Remote Config defaults
40
- defaultConfigurations: {},
41
- configCacheKey: 'grain_config',
42
- configRefreshInterval: 300000, // 5 minutes
43
- enableConfigCache: true,
44
- // Privacy defaults
45
- consentMode: 'opt-out',
46
- waitForConsent: false,
47
- enableCookies: false,
48
- anonymizeIP: false,
49
- disableAutoProperties: false,
50
- // Automatic Tracking defaults
51
- enableHeartbeat: true,
52
- heartbeatActiveInterval: 120000, // 2 minutes
53
- heartbeatInactiveInterval: 300000, // 5 minutes
54
- enableAutoPageView: true,
55
- stripQueryParams: true,
56
- ...config,
57
- tenantId: config.tenantId,
58
- };
59
- // Initialize consent manager
60
- this.consentManager = new ConsentManager(this.config.tenantId, this.config.consentMode);
61
- // Check if cookies are enabled
62
- if (this.config.enableCookies) {
63
- this.cookiesEnabled = areCookiesEnabled();
64
- if (!this.cookiesEnabled && this.config.debug) {
65
- console.warn('[Grain Analytics] Cookies are not available, falling back to localStorage');
66
- }
67
- }
68
- // Set global userId if provided in config
69
- if (config.userId) {
70
- this.globalUserId = config.userId;
71
- }
72
- this.validateConfig();
73
- this.initializePersistentAnonymousUserId();
74
- this.setupBeforeUnload();
75
- this.startFlushTimer();
76
- this.initializeConfigCache();
77
- // Initialize ephemeral session ID (memory-only, not persisted)
78
- this.ephemeralSessionId = this.generateUUID();
79
- // Initialize automatic tracking (browser only)
80
- if (typeof window !== 'undefined') {
81
- this.initializeAutomaticTracking();
82
- }
83
- // Set up consent change listener to flush waiting events and handle consent upgrade
84
- this.consentManager.addListener((state) => {
85
- if (state.granted) {
86
- this.handleConsentGranted();
87
- }
88
- });
89
- }
90
- validateConfig() {
91
- if (!this.config.tenantId) {
92
- throw new Error('Grain Analytics: tenantId is required');
93
- }
94
- if (this.config.authStrategy === 'SERVER_SIDE' && !this.config.secretKey) {
95
- throw new Error('Grain Analytics: secretKey is required for SERVER_SIDE auth strategy');
96
- }
97
- if (this.config.authStrategy === 'JWT' && !this.config.authProvider) {
98
- throw new Error('Grain Analytics: authProvider is required for JWT auth strategy');
99
- }
100
- }
101
- /**
102
- * Generate a UUID v4 string
103
- */
104
- generateUUID() {
105
- if (typeof crypto !== 'undefined' && crypto.randomUUID) {
106
- return crypto.randomUUID();
107
- }
108
- // Fallback for environments without crypto.randomUUID
109
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
110
- const r = Math.random() * 16 | 0;
111
- const v = c === 'x' ? r : (r & 0x3 | 0x8);
112
- return v.toString(16);
113
- });
114
- }
115
- /**
116
- * Generate a proper UUIDv4 identifier for anonymous user ID
117
- */
118
- generateAnonymousUserId() {
119
- return this.generateUUID();
120
- }
121
- /**
122
- * Initialize persistent anonymous user ID from cookies or localStorage
123
- * Priority: Cookie → localStorage → generate new
124
- */
125
- initializePersistentAnonymousUserId() {
126
- if (typeof window === 'undefined')
127
- return;
128
- const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
129
- const cookieName = '_grain_uid';
130
- try {
131
- // Try to load from cookie first if enabled
132
- if (this.cookiesEnabled) {
133
- const cookieValue = getCookie(cookieName);
134
- if (cookieValue) {
135
- this.persistentAnonymousUserId = cookieValue;
136
- this.log('Loaded persistent anonymous user ID from cookie:', this.persistentAnonymousUserId);
137
- return;
138
- }
139
- }
140
- // Fallback to localStorage
141
- const stored = localStorage.getItem(storageKey);
142
- if (stored) {
143
- this.persistentAnonymousUserId = stored;
144
- this.log('Loaded persistent anonymous user ID from localStorage:', this.persistentAnonymousUserId);
145
- // Migrate to cookie if enabled
146
- if (this.cookiesEnabled) {
147
- this.savePersistentAnonymousUserId(stored);
148
- }
149
- }
150
- else {
151
- // Generate new UUIDv4 anonymous user ID
152
- this.persistentAnonymousUserId = this.generateAnonymousUserId();
153
- this.savePersistentAnonymousUserId(this.persistentAnonymousUserId);
154
- this.log('Generated new persistent anonymous user ID:', this.persistentAnonymousUserId);
155
- }
156
- }
157
- catch (error) {
158
- this.log('Failed to initialize persistent anonymous user ID:', error);
159
- // Fallback: generate temporary ID without persistence
160
- this.persistentAnonymousUserId = this.generateAnonymousUserId();
161
- }
162
- }
163
- /**
164
- * Save persistent anonymous user ID to cookie and/or localStorage
165
- */
166
- savePersistentAnonymousUserId(userId) {
167
- if (typeof window === 'undefined')
168
- return;
169
- const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
170
- const cookieName = '_grain_uid';
171
- try {
172
- // Save to cookie if enabled
173
- if (this.cookiesEnabled) {
174
- const cookieOptions = {
175
- maxAge: 365 * 24 * 60 * 60, // 365 days
176
- sameSite: 'lax',
177
- secure: typeof window !== 'undefined' && window.location.protocol === 'https:',
178
- ...this.config.cookieOptions,
179
- };
180
- setCookie(cookieName, userId, cookieOptions);
181
- }
182
- // Always save to localStorage as fallback
183
- localStorage.setItem(storageKey, userId);
184
- }
185
- catch (error) {
186
- this.log('Failed to save persistent anonymous user ID:', error);
187
- }
188
- }
189
- /**
190
- * Get the effective user ID (global userId or persistent anonymous ID)
191
- */
192
- getEffectiveUserIdInternal() {
193
- if (this.globalUserId) {
194
- return this.globalUserId;
195
- }
196
- if (this.persistentAnonymousUserId) {
197
- return this.persistentAnonymousUserId;
198
- }
199
- // Generate a new UUIDv4 identifier as fallback
200
- this.persistentAnonymousUserId = this.generateAnonymousUserId();
201
- // Try to persist it
202
- if (typeof window !== 'undefined') {
203
- try {
204
- const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
205
- localStorage.setItem(storageKey, this.persistentAnonymousUserId);
206
- }
207
- catch (error) {
208
- this.log('Failed to persist generated anonymous user ID:', error);
209
- }
210
- }
211
- return this.persistentAnonymousUserId;
212
- }
213
- log(...args) {
214
- if (this.config.debug) {
215
- console.log('[Grain Analytics]', ...args);
216
- }
217
- }
218
- /**
219
- * Create error digest from events
220
- */
221
- createErrorDigest(events) {
222
- const eventNames = [...new Set(events.map(e => e.eventName))];
223
- const userIds = [...new Set(events.map(e => e.userId))];
224
- let totalProperties = 0;
225
- let totalSize = 0;
226
- events.forEach(event => {
227
- const properties = event.properties || {};
228
- totalProperties += Object.keys(properties).length;
229
- totalSize += JSON.stringify(event).length;
230
- });
231
- return {
232
- eventCount: events.length,
233
- totalProperties,
234
- totalSize,
235
- eventNames,
236
- userIds,
237
- };
238
- }
239
- /**
240
- * Format error with beautiful structure
241
- */
242
- formatError(error, context, events) {
243
- const digest = events ? this.createErrorDigest(events) : {
244
- eventCount: 0,
245
- totalProperties: 0,
246
- totalSize: 0,
247
- eventNames: [],
248
- userIds: [],
249
- };
250
- let code = 'UNKNOWN_ERROR';
251
- let message = 'An unknown error occurred';
252
- if (error instanceof Error) {
253
- message = error.message;
254
- // Determine error code based on error type and message
255
- if (message.includes('fetch failed') || message.includes('network error')) {
256
- code = 'NETWORK_ERROR';
257
- }
258
- else if (message.includes('timeout')) {
259
- code = 'TIMEOUT_ERROR';
260
- }
261
- else if (message.includes('HTTP 4')) {
262
- code = 'CLIENT_ERROR';
263
- }
264
- else if (message.includes('HTTP 5')) {
265
- code = 'SERVER_ERROR';
266
- }
267
- else if (message.includes('JSON')) {
268
- code = 'PARSE_ERROR';
269
- }
270
- else if (message.includes('auth') || message.includes('unauthorized')) {
271
- code = 'AUTH_ERROR';
272
- }
273
- else if (message.includes('rate limit') || message.includes('429')) {
274
- code = 'RATE_LIMIT_ERROR';
275
- }
276
- else {
277
- code = 'GENERAL_ERROR';
278
- }
279
- }
280
- else if (typeof error === 'string') {
281
- message = error;
282
- code = 'STRING_ERROR';
283
- }
284
- else if (error && typeof error === 'object' && 'status' in error) {
285
- const status = error.status;
286
- code = `HTTP_${status}`;
287
- message = `HTTP ${status} error`;
288
- }
289
- return {
290
- code,
291
- message,
292
- digest,
293
- timestamp: new Date().toISOString(),
294
- context,
295
- originalError: error,
296
- };
297
- }
298
- /**
299
- * Log formatted error gracefully
300
- */
301
- logError(formattedError) {
302
- const { code, message, digest, timestamp, context } = formattedError;
303
- const errorOutput = {
304
- '🚨 Grain Analytics Error': {
305
- 'Error Code': code,
306
- 'Message': message,
307
- 'Context': context,
308
- 'Timestamp': timestamp,
309
- 'Event Digest': {
310
- 'Events': digest.eventCount,
311
- 'Properties': digest.totalProperties,
312
- 'Size (bytes)': digest.totalSize,
313
- 'Event Names': digest.eventNames.length > 0 ? digest.eventNames.join(', ') : 'None',
314
- 'User IDs': digest.userIds.length > 0 ? digest.userIds.slice(0, 3).join(', ') + (digest.userIds.length > 3 ? '...' : '') : 'None',
315
- }
316
- }
317
- };
318
- console.error('🚨 Grain Analytics Error:', errorOutput);
319
- // Also log in a more compact format for debugging
320
- if (this.config.debug) {
321
- console.error(`[Grain Analytics] ${code}: ${message} (${context}) - Events: ${digest.eventCount}, Props: ${digest.totalProperties}, Size: ${digest.totalSize}B`);
322
- }
323
- }
324
- /**
325
- * Safely execute a function with error handling
326
- */
327
- async safeExecute(fn, context, events) {
328
- try {
329
- return await fn();
330
- }
331
- catch (error) {
332
- const formattedError = this.formatError(error, context, events);
333
- this.logError(formattedError);
334
- return null;
335
- }
336
- }
337
- formatEvent(event) {
338
- return {
339
- eventName: event.eventName,
340
- userId: event.userId || this.getEffectiveUserIdInternal(),
341
- properties: event.properties || {},
342
- };
343
- }
344
- async getAuthHeaders() {
345
- const headers = {
346
- 'Content-Type': 'application/json',
347
- };
348
- switch (this.config.authStrategy) {
349
- case 'NONE':
350
- break;
351
- case 'SERVER_SIDE':
352
- headers['Authorization'] = `Chase ${this.config.secretKey}`;
353
- break;
354
- case 'JWT':
355
- if (this.config.authProvider) {
356
- const token = await this.config.authProvider.getToken();
357
- headers['Authorization'] = `Bearer ${token}`;
358
- }
359
- break;
360
- }
361
- return headers;
362
- }
363
- async delay(ms) {
364
- return new Promise(resolve => setTimeout(resolve, ms));
365
- }
366
- isRetriableError(error) {
367
- if (error instanceof Error) {
368
- // Check for specific network or fetch errors
369
- const message = error.message.toLowerCase();
370
- if (message.includes('fetch failed'))
371
- return true;
372
- if (message === 'network error')
373
- return true; // Exact match to avoid "Non-network error"
374
- if (message.includes('timeout'))
375
- return true;
376
- if (message.includes('connection'))
377
- return true;
378
- }
379
- // Check for HTTP status codes that are retriable
380
- if (typeof error === 'object' && error !== null && 'status' in error) {
381
- const status = error.status;
382
- return status >= 500 || status === 429; // Server errors or rate limiting
383
- }
384
- return false;
385
- }
386
- async sendEvents(events) {
387
- if (events.length === 0)
388
- return;
389
- let lastError;
390
- for (let attempt = 0; attempt <= this.config.retryAttempts; attempt++) {
391
- try {
392
- const headers = await this.getAuthHeaders();
393
- const url = `${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`;
394
- this.log(`Sending ${events.length} events to ${url} (attempt ${attempt + 1})`);
395
- const response = await fetch(url, {
396
- method: 'POST',
397
- headers,
398
- body: JSON.stringify(events),
399
- });
400
- if (!response.ok) {
401
- let errorMessage = `HTTP ${response.status}`;
402
- try {
403
- const errorBody = await response.json();
404
- if (errorBody?.message) {
405
- errorMessage = errorBody.message;
406
- }
407
- }
408
- catch {
409
- const errorText = await response.text();
410
- if (errorText) {
411
- errorMessage = errorText;
412
- }
413
- }
414
- const error = new Error(`Failed to send events: ${errorMessage}`);
415
- error.status = response.status;
416
- throw error;
417
- }
418
- this.log(`Successfully sent ${events.length} events`);
419
- return; // Success, exit retry loop
420
- }
421
- catch (error) {
422
- lastError = error;
423
- if (attempt === this.config.retryAttempts) {
424
- // Last attempt, don't retry - log error gracefully
425
- const formattedError = this.formatError(error, `sendEvents (attempt ${attempt + 1}/${this.config.retryAttempts + 1})`, events);
426
- this.logError(formattedError);
427
- return; // Don't throw, just return gracefully
428
- }
429
- if (!this.isRetriableError(error)) {
430
- // Non-retriable error, don't retry - log error gracefully
431
- const formattedError = this.formatError(error, `sendEvents (non-retriable error)`, events);
432
- this.logError(formattedError);
433
- return; // Don't throw, just return gracefully
434
- }
435
- const delayMs = this.config.retryDelay * Math.pow(2, attempt); // Exponential backoff
436
- this.log(`Retrying in ${delayMs}ms after error:`, error);
437
- await this.delay(delayMs);
438
- }
439
- }
440
- }
441
- async sendEventsWithBeacon(events) {
442
- if (events.length === 0)
443
- return;
444
- try {
445
- const headers = await this.getAuthHeaders();
446
- const url = `${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`;
447
- const body = JSON.stringify({ events });
448
- // Try beacon API first (more reliable for page unload)
449
- if (typeof navigator !== 'undefined' && 'sendBeacon' in navigator) {
450
- const blob = new Blob([body], { type: 'application/json' });
451
- const success = navigator.sendBeacon(url, blob);
452
- if (success) {
453
- this.log(`Successfully sent ${events.length} events via beacon`);
454
- return;
455
- }
456
- }
457
- // Fallback to fetch with keepalive
458
- await fetch(url, {
459
- method: 'POST',
460
- headers,
461
- body,
462
- keepalive: true,
463
- });
464
- this.log(`Successfully sent ${events.length} events via fetch (keepalive)`);
465
- }
466
- catch (error) {
467
- // Log error gracefully for beacon failures (page unload scenarios)
468
- const formattedError = this.formatError(error, 'sendEventsWithBeacon', events);
469
- this.logError(formattedError);
470
- }
471
- }
472
- startFlushTimer() {
473
- if (typeof window === 'undefined')
474
- return;
475
- if (this.flushTimer) {
476
- clearInterval(this.flushTimer);
477
- }
478
- this.flushTimer = window.setInterval(() => {
479
- if (this.eventQueue.length > 0) {
480
- this.flush().catch((error) => {
481
- const formattedError = this.formatError(error, 'auto-flush');
482
- this.logError(formattedError);
483
- });
484
- }
485
- }, this.config.flushInterval);
486
- }
487
- setupBeforeUnload() {
488
- if (typeof window === 'undefined')
489
- return;
490
- const handleBeforeUnload = () => {
491
- if (this.eventQueue.length > 0) {
492
- // Use beacon API for reliable delivery during page unload
493
- const eventsToSend = [...this.eventQueue];
494
- this.eventQueue = [];
495
- const chunks = this.chunkEvents(eventsToSend, this.config.maxEventsPerRequest);
496
- // Send first chunk with beacon (most important for page unload)
497
- if (chunks.length > 0) {
498
- this.sendEventsWithBeacon(chunks[0]).catch(() => {
499
- // Silently fail - page is unloading
500
- });
501
- }
502
- }
503
- };
504
- // Handle page unload
505
- window.addEventListener('beforeunload', handleBeforeUnload);
506
- window.addEventListener('pagehide', handleBeforeUnload);
507
- // Handle visibility change (page hidden)
508
- document.addEventListener('visibilitychange', () => {
509
- if (document.visibilityState === 'hidden' && this.eventQueue.length > 0) {
510
- const eventsToSend = [...this.eventQueue];
511
- this.eventQueue = [];
512
- const chunks = this.chunkEvents(eventsToSend, this.config.maxEventsPerRequest);
513
- // Send first chunk with beacon (most important for page hidden)
514
- if (chunks.length > 0) {
515
- this.sendEventsWithBeacon(chunks[0]).catch(() => {
516
- // Silently fail
517
- });
518
- }
519
- }
520
- });
521
- }
522
- /**
523
- * Initialize automatic tracking (heartbeat and page views)
524
- */
525
- initializeAutomaticTracking() {
526
- if (this.config.enableHeartbeat) {
527
- try {
528
- this.activityDetector = new ActivityDetector();
529
- this.heartbeatManager = new HeartbeatManager(this, this.activityDetector, {
530
- activeInterval: this.config.heartbeatActiveInterval,
531
- inactiveInterval: this.config.heartbeatInactiveInterval,
532
- debug: this.config.debug,
533
- });
534
- this.log('Heartbeat tracking initialized');
535
- }
536
- catch (error) {
537
- this.log('Failed to initialize heartbeat tracking:', error);
538
- }
539
- }
540
- if (this.config.enableAutoPageView) {
541
- try {
542
- this.pageTrackingManager = new PageTrackingManager(this, {
543
- stripQueryParams: this.config.stripQueryParams,
544
- debug: this.config.debug,
545
- });
546
- this.log('Auto page view tracking initialized');
547
- }
548
- catch (error) {
549
- this.log('Failed to initialize page view tracking:', error);
550
- }
551
- }
552
- }
553
- /**
554
- * Handle consent granted - upgrade ephemeral session to persistent user
555
- */
556
- handleConsentGranted() {
557
- this.flushWaitingForConsentQueue();
558
- // Track consent granted event with mapping
559
- if (this.ephemeralSessionId) {
560
- this.trackSystemEvent('_grain_consent_granted', {
561
- previous_session_id: this.ephemeralSessionId,
562
- new_user_id: this.getEffectiveUserId(),
563
- timestamp: Date.now(),
564
- });
565
- }
566
- }
567
- /**
568
- * Track system events that bypass consent checks (for necessary/functional tracking)
569
- */
570
- trackSystemEvent(eventName, properties) {
571
- if (this.isDestroyed)
572
- return;
573
- const hasConsent = this.consentManager.hasConsent('analytics');
574
- // Create event with appropriate user ID
575
- const event = {
576
- eventName,
577
- userId: hasConsent ? this.getEffectiveUserId() : this.getEphemeralSessionId(),
578
- properties: {
579
- ...properties,
580
- _minimal: !hasConsent, // Flag to indicate minimal tracking
581
- _consent_status: hasConsent ? 'granted' : 'pending',
582
- },
583
- };
584
- // Bypass consent check for necessary system events
585
- this.eventQueue.push(event);
586
- this.eventCountSinceLastHeartbeat++;
587
- this.log(`Queued system event: ${eventName}`, properties);
588
- // Consider flushing
589
- if (this.eventQueue.length >= this.config.batchSize) {
590
- this.flush().catch((error) => {
591
- const formattedError = this.formatError(error, 'flush system event');
592
- this.logError(formattedError);
593
- });
594
- }
595
- }
596
- /**
597
- * Get ephemeral session ID (memory-only, not persisted)
598
- */
599
- getEphemeralSessionId() {
600
- if (!this.ephemeralSessionId) {
601
- this.ephemeralSessionId = this.generateUUID();
602
- }
603
- return this.ephemeralSessionId;
604
- }
605
- /**
606
- * Get the current page path from page tracker
607
- */
608
- getCurrentPage() {
609
- return this.pageTrackingManager?.getCurrentPage() || null;
610
- }
611
- /**
612
- * Get event count since last heartbeat
613
- */
614
- getEventCountSinceLastHeartbeat() {
615
- return this.eventCountSinceLastHeartbeat;
616
- }
617
- /**
618
- * Reset event count since last heartbeat
619
- */
620
- resetEventCountSinceLastHeartbeat() {
621
- this.eventCountSinceLastHeartbeat = 0;
622
- }
623
- /**
624
- * Get the effective user ID (public method)
625
- */
626
- getEffectiveUserId() {
627
- return this.getEffectiveUserIdInternal();
628
- }
629
- /**
630
- * Get the session ID (ephemeral or persistent based on consent)
631
- */
632
- getSessionId() {
633
- const hasConsent = this.consentManager.hasConsent('analytics');
634
- return hasConsent ? this.getEffectiveUserId() : this.getEphemeralSessionId();
635
- }
636
- async track(eventOrName, propertiesOrOptions, options) {
637
- try {
638
- if (this.isDestroyed) {
639
- const error = new Error('Grain Analytics: Client has been destroyed');
640
- const formattedError = this.formatError(error, 'track (client destroyed)');
641
- this.logError(formattedError);
642
- return;
643
- }
644
- let event;
645
- let opts = {};
646
- if (typeof eventOrName === 'string') {
647
- event = {
648
- eventName: eventOrName,
649
- properties: propertiesOrOptions,
650
- };
651
- opts = options || {};
652
- }
653
- else {
654
- event = eventOrName;
655
- opts = propertiesOrOptions || {};
656
- }
657
- // Filter properties if whitelist is enabled
658
- if (this.config.allowedProperties && event.properties) {
659
- const filtered = {};
660
- for (const key of this.config.allowedProperties) {
661
- if (key in event.properties) {
662
- filtered[key] = event.properties[key];
663
- }
664
- }
665
- event.properties = filtered;
666
- }
667
- const formattedEvent = this.formatEvent(event);
668
- // Check consent before tracking
669
- if (this.consentManager.shouldWaitForConsent() && this.config.waitForConsent) {
670
- // Queue event until consent is granted
671
- this.waitingForConsentQueue.push(formattedEvent);
672
- this.log(`Event waiting for consent: ${event.eventName}`, event.properties);
673
- return;
674
- }
675
- if (!this.consentManager.hasConsent('analytics')) {
676
- this.log(`Event blocked by consent: ${event.eventName}`);
677
- return;
678
- }
679
- this.eventQueue.push(formattedEvent);
680
- this.eventCountSinceLastHeartbeat++;
681
- this.log(`Queued event: ${event.eventName}`, event.properties);
682
- // Check if we should flush immediately
683
- if (opts.flush || this.eventQueue.length >= this.config.batchSize) {
684
- await this.flush();
685
- }
686
- }
687
- catch (error) {
688
- const formattedError = this.formatError(error, 'track');
689
- this.logError(formattedError);
690
- }
691
- }
692
- /**
693
- * Flush events that were waiting for consent
694
- */
695
- flushWaitingForConsentQueue() {
696
- if (this.waitingForConsentQueue.length === 0)
697
- return;
698
- this.log(`Flushing ${this.waitingForConsentQueue.length} events waiting for consent`);
699
- // Move waiting events to main queue
700
- this.eventQueue.push(...this.waitingForConsentQueue);
701
- this.waitingForConsentQueue = [];
702
- // Flush immediately
703
- this.flush().catch((error) => {
704
- const formattedError = this.formatError(error, 'flush waiting for consent queue');
705
- this.logError(formattedError);
706
- });
707
- }
708
- /**
709
- * Identify a user (sets userId for subsequent events)
710
- */
711
- identify(userId) {
712
- this.log(`Identified user: ${userId}`);
713
- this.globalUserId = userId;
714
- // Clear persistent anonymous user ID since we now have a real user ID
715
- this.persistentAnonymousUserId = null;
716
- }
717
- /**
718
- * Set global user ID for all subsequent events
719
- */
720
- setUserId(userId) {
721
- this.log(`Set global user ID: ${userId}`);
722
- this.globalUserId = userId;
723
- if (userId) {
724
- // Clear persistent anonymous user ID if setting a real user ID
725
- this.persistentAnonymousUserId = null;
726
- }
727
- else {
728
- // If clearing user ID, ensure we have a UUIDv4 identifier
729
- if (!this.persistentAnonymousUserId) {
730
- this.persistentAnonymousUserId = this.generateAnonymousUserId();
731
- // Try to persist the new anonymous ID
732
- if (typeof window !== 'undefined') {
733
- try {
734
- const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
735
- localStorage.setItem(storageKey, this.persistentAnonymousUserId);
736
- }
737
- catch (error) {
738
- this.log('Failed to persist new anonymous user ID:', error);
739
- }
740
- }
741
- }
742
- }
743
- }
744
- /**
745
- * Get current global user ID
746
- */
747
- getUserId() {
748
- return this.globalUserId;
749
- }
750
- /**
751
- * Get current effective user ID (global userId or persistent anonymous ID)
752
- */
753
- getEffectiveUserIdPublic() {
754
- return this.getEffectiveUserIdInternal();
755
- }
756
- /**
757
- * Login with auth token or userId on the fly
758
- *
759
- * @example
760
- * // Login with userId only
761
- * client.login({ userId: 'user123' });
762
- *
763
- * // Login with auth token (automatically sets authStrategy to JWT)
764
- * client.login({ authToken: 'jwt-token-here' });
765
- *
766
- * // Login with both userId and auth token
767
- * client.login({ userId: 'user123', authToken: 'jwt-token-here' });
768
- *
769
- * // Override auth strategy
770
- * client.login({ userId: 'user123', authStrategy: 'SERVER_SIDE' });
771
- */
772
- login(options) {
773
- try {
774
- if (this.isDestroyed) {
775
- const error = new Error('Grain Analytics: Client has been destroyed');
776
- const formattedError = this.formatError(error, 'login (client destroyed)');
777
- this.logError(formattedError);
778
- return;
779
- }
780
- // Set userId if provided
781
- if (options.userId) {
782
- this.log(`Login: Setting user ID to ${options.userId}`);
783
- this.globalUserId = options.userId;
784
- // Clear persistent anonymous user ID since we now have a real user ID
785
- this.persistentAnonymousUserId = null;
786
- }
787
- // Handle auth token if provided
788
- if (options.authToken) {
789
- this.log('Login: Setting auth token');
790
- // Update auth strategy to JWT if not already set
791
- if (this.config.authStrategy === 'NONE') {
792
- this.config.authStrategy = 'JWT';
793
- }
794
- // Create a simple auth provider that returns the provided token
795
- this.config.authProvider = {
796
- getToken: () => options.authToken
797
- };
798
- }
799
- // Override auth strategy if provided
800
- if (options.authStrategy) {
801
- this.log(`Login: Setting auth strategy to ${options.authStrategy}`);
802
- this.config.authStrategy = options.authStrategy;
803
- }
804
- this.log(`Login successful. Effective user ID: ${this.getEffectiveUserIdInternal()}`);
805
- }
806
- catch (error) {
807
- const formattedError = this.formatError(error, 'login');
808
- this.logError(formattedError);
809
- }
810
- }
811
- /**
812
- * Logout and clear user session, fall back to UUIDv4 identifier
813
- *
814
- * @example
815
- * // Logout user and return to anonymous mode
816
- * client.logout();
817
- *
818
- * // After logout, events will use the persistent UUIDv4 identifier
819
- * client.track('page_view', { page: 'home' });
820
- */
821
- logout() {
822
- try {
823
- if (this.isDestroyed) {
824
- const error = new Error('Grain Analytics: Client has been destroyed');
825
- const formattedError = this.formatError(error, 'logout (client destroyed)');
826
- this.logError(formattedError);
827
- return;
828
- }
829
- this.log('Logout: Clearing user session');
830
- // Clear global user ID
831
- this.globalUserId = null;
832
- // Reset auth strategy to NONE
833
- this.config.authStrategy = 'NONE';
834
- this.config.authProvider = undefined;
835
- // Generate new UUIDv4 identifier if we don't have one
836
- if (!this.persistentAnonymousUserId) {
837
- this.persistentAnonymousUserId = this.generateAnonymousUserId();
838
- // Try to persist the new anonymous ID
839
- if (typeof window !== 'undefined') {
840
- try {
841
- const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
842
- localStorage.setItem(storageKey, this.persistentAnonymousUserId);
843
- }
844
- catch (error) {
845
- this.log('Failed to persist new anonymous user ID after logout:', error);
846
- }
847
- }
848
- }
849
- this.log(`Logout successful. Effective user ID: ${this.getEffectiveUserIdInternal()}`);
850
- }
851
- catch (error) {
852
- const formattedError = this.formatError(error, 'logout');
853
- this.logError(formattedError);
854
- }
855
- }
856
- /**
857
- * Set user properties
858
- */
859
- async setProperty(properties, options) {
860
- try {
861
- if (this.isDestroyed) {
862
- const error = new Error('Grain Analytics: Client has been destroyed');
863
- const formattedError = this.formatError(error, 'setProperty (client destroyed)');
864
- this.logError(formattedError);
865
- return;
866
- }
867
- const userId = options?.userId || this.getEffectiveUserIdInternal();
868
- // Validate property count (max 4 properties)
869
- const propertyKeys = Object.keys(properties);
870
- if (propertyKeys.length > 4) {
871
- const error = new Error('Grain Analytics: Maximum 4 properties allowed per request');
872
- const formattedError = this.formatError(error, 'setProperty (validation)');
873
- this.logError(formattedError);
874
- return;
875
- }
876
- if (propertyKeys.length === 0) {
877
- const error = new Error('Grain Analytics: At least one property is required');
878
- const formattedError = this.formatError(error, 'setProperty (validation)');
879
- this.logError(formattedError);
880
- return;
881
- }
882
- // Serialize all values to strings
883
- const serializedProperties = {};
884
- for (const [key, value] of Object.entries(properties)) {
885
- if (value === null || value === undefined) {
886
- serializedProperties[key] = '';
887
- }
888
- else if (typeof value === 'string') {
889
- serializedProperties[key] = value;
890
- }
891
- else {
892
- serializedProperties[key] = JSON.stringify(value);
893
- }
894
- }
895
- const payload = {
896
- userId,
897
- ...serializedProperties,
898
- };
899
- await this.sendProperties(payload);
900
- }
901
- catch (error) {
902
- const formattedError = this.formatError(error, 'setProperty');
903
- this.logError(formattedError);
904
- }
905
- }
906
- /**
907
- * Send properties to the API
908
- */
909
- async sendProperties(payload) {
910
- let lastError;
911
- for (let attempt = 0; attempt <= this.config.retryAttempts; attempt++) {
912
- try {
913
- const headers = await this.getAuthHeaders();
914
- const url = `${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/properties`;
915
- this.log(`Setting properties for user ${payload.userId} (attempt ${attempt + 1})`);
916
- const response = await fetch(url, {
917
- method: 'POST',
918
- headers,
919
- body: JSON.stringify(payload),
920
- });
921
- if (!response.ok) {
922
- let errorMessage = `HTTP ${response.status}`;
923
- try {
924
- const errorBody = await response.json();
925
- if (errorBody?.message) {
926
- errorMessage = errorBody.message;
927
- }
928
- }
929
- catch {
930
- const errorText = await response.text();
931
- if (errorText) {
932
- errorMessage = errorText;
933
- }
934
- }
935
- const error = new Error(`Failed to set properties: ${errorMessage}`);
936
- error.status = response.status;
937
- throw error;
938
- }
939
- this.log(`Successfully set properties for user ${payload.userId}`);
940
- return; // Success, exit retry loop
941
- }
942
- catch (error) {
943
- lastError = error;
944
- if (attempt === this.config.retryAttempts) {
945
- // Last attempt, don't retry - log error gracefully
946
- const formattedError = this.formatError(error, `sendProperties (attempt ${attempt + 1}/${this.config.retryAttempts + 1})`);
947
- this.logError(formattedError);
948
- return; // Don't throw, just return gracefully
949
- }
950
- if (!this.isRetriableError(error)) {
951
- // Non-retriable error, don't retry - log error gracefully
952
- const formattedError = this.formatError(error, 'sendProperties (non-retriable error)');
953
- this.logError(formattedError);
954
- return; // Don't throw, just return gracefully
955
- }
956
- const delayMs = this.config.retryDelay * Math.pow(2, attempt); // Exponential backoff
957
- this.log(`Retrying in ${delayMs}ms after error:`, error);
958
- await this.delay(delayMs);
959
- }
960
- }
961
- }
962
- // Template event methods
963
- /**
964
- * Track user login event
965
- */
966
- async trackLogin(properties, options) {
967
- try {
968
- return await this.track('login', properties, options);
969
- }
970
- catch (error) {
971
- const formattedError = this.formatError(error, 'trackLogin');
972
- this.logError(formattedError);
973
- }
974
- }
975
- /**
976
- * Track user signup event
977
- */
978
- async trackSignup(properties, options) {
979
- try {
980
- return await this.track('signup', properties, options);
981
- }
982
- catch (error) {
983
- const formattedError = this.formatError(error, 'trackSignup');
984
- this.logError(formattedError);
985
- }
986
- }
987
- /**
988
- * Track checkout event
989
- */
990
- async trackCheckout(properties, options) {
991
- try {
992
- return await this.track('checkout', properties, options);
993
- }
994
- catch (error) {
995
- const formattedError = this.formatError(error, 'trackCheckout');
996
- this.logError(formattedError);
997
- }
998
- }
999
- /**
1000
- * Track page view event
1001
- */
1002
- async trackPageView(properties, options) {
1003
- try {
1004
- return await this.track('page_view', properties, options);
1005
- }
1006
- catch (error) {
1007
- const formattedError = this.formatError(error, 'trackPageView');
1008
- this.logError(formattedError);
1009
- }
1010
- }
1011
- /**
1012
- * Track purchase event
1013
- */
1014
- async trackPurchase(properties, options) {
1015
- try {
1016
- return await this.track('purchase', properties, options);
1017
- }
1018
- catch (error) {
1019
- const formattedError = this.formatError(error, 'trackPurchase');
1020
- this.logError(formattedError);
1021
- }
1022
- }
1023
- /**
1024
- * Track search event
1025
- */
1026
- async trackSearch(properties, options) {
1027
- try {
1028
- return await this.track('search', properties, options);
1029
- }
1030
- catch (error) {
1031
- const formattedError = this.formatError(error, 'trackSearch');
1032
- this.logError(formattedError);
1033
- }
1034
- }
1035
- /**
1036
- * Track add to cart event
1037
- */
1038
- async trackAddToCart(properties, options) {
1039
- try {
1040
- return await this.track('add_to_cart', properties, options);
1041
- }
1042
- catch (error) {
1043
- const formattedError = this.formatError(error, 'trackAddToCart');
1044
- this.logError(formattedError);
1045
- }
1046
- }
1047
- /**
1048
- * Track remove from cart event
1049
- */
1050
- async trackRemoveFromCart(properties, options) {
1051
- try {
1052
- return await this.track('remove_from_cart', properties, options);
1053
- }
1054
- catch (error) {
1055
- const formattedError = this.formatError(error, 'trackRemoveFromCart');
1056
- this.logError(formattedError);
1057
- }
1058
- }
1059
- /**
1060
- * Manually flush all queued events
1061
- */
1062
- async flush() {
1063
- try {
1064
- if (this.eventQueue.length === 0)
1065
- return;
1066
- const eventsToSend = [...this.eventQueue];
1067
- this.eventQueue = [];
1068
- // Split events into chunks to respect maxEventsPerRequest limit
1069
- const chunks = this.chunkEvents(eventsToSend, this.config.maxEventsPerRequest);
1070
- // Send all chunks sequentially to maintain order
1071
- for (const chunk of chunks) {
1072
- await this.sendEvents(chunk);
1073
- }
1074
- }
1075
- catch (error) {
1076
- const formattedError = this.formatError(error, 'flush');
1077
- this.logError(formattedError);
1078
- }
1079
- }
1080
- // Remote Config Methods
1081
- /**
1082
- * Initialize configuration cache from localStorage
1083
- */
1084
- initializeConfigCache() {
1085
- if (!this.config.enableConfigCache || typeof window === 'undefined')
1086
- return;
1087
- try {
1088
- const cached = localStorage.getItem(this.config.configCacheKey);
1089
- if (cached) {
1090
- this.configCache = JSON.parse(cached);
1091
- this.log('Loaded configuration from cache:', this.configCache);
1092
- }
1093
- }
1094
- catch (error) {
1095
- this.log('Failed to load configuration cache:', error);
1096
- }
1097
- }
1098
- /**
1099
- * Save configuration cache to localStorage
1100
- */
1101
- saveConfigCache(cache) {
1102
- if (!this.config.enableConfigCache || typeof window === 'undefined')
1103
- return;
1104
- try {
1105
- localStorage.setItem(this.config.configCacheKey, JSON.stringify(cache));
1106
- this.log('Saved configuration to cache:', cache);
1107
- }
1108
- catch (error) {
1109
- this.log('Failed to save configuration cache:', error);
1110
- }
1111
- }
1112
- /**
1113
- * Get configuration value with fallback to defaults
1114
- */
1115
- getConfig(key) {
1116
- // First check cache
1117
- if (this.configCache?.configurations?.[key]) {
1118
- return this.configCache.configurations[key];
1119
- }
1120
- // Then check defaults
1121
- if (this.config.defaultConfigurations?.[key]) {
1122
- return this.config.defaultConfigurations[key];
1123
- }
1124
- return undefined;
1125
- }
1126
- /**
1127
- * Get all configurations with fallback to defaults
1128
- */
1129
- getAllConfigs() {
1130
- const configs = { ...this.config.defaultConfigurations };
1131
- if (this.configCache?.configurations) {
1132
- Object.assign(configs, this.configCache.configurations);
1133
- }
1134
- return configs;
1135
- }
1136
- /**
1137
- * Fetch configurations from API
1138
- */
1139
- async fetchConfig(options = {}) {
1140
- try {
1141
- if (this.isDestroyed) {
1142
- const error = new Error('Grain Analytics: Client has been destroyed');
1143
- const formattedError = this.formatError(error, 'fetchConfig (client destroyed)');
1144
- this.logError(formattedError);
1145
- return null;
1146
- }
1147
- const userId = options.userId || this.getEffectiveUserIdInternal();
1148
- const immediateKeys = options.immediateKeys || [];
1149
- const properties = options.properties || {};
1150
- const request = {
1151
- userId,
1152
- immediateKeys,
1153
- properties,
1154
- };
1155
- let lastError;
1156
- for (let attempt = 0; attempt <= this.config.retryAttempts; attempt++) {
1157
- try {
1158
- const headers = await this.getAuthHeaders();
1159
- const url = `${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/config/configurations`;
1160
- this.log(`Fetching configurations for user ${userId} (attempt ${attempt + 1})`);
1161
- const response = await fetch(url, {
1162
- method: 'POST',
1163
- headers,
1164
- body: JSON.stringify(request),
1165
- });
1166
- if (!response.ok) {
1167
- let errorMessage = `HTTP ${response.status}`;
1168
- try {
1169
- const errorBody = await response.json();
1170
- if (errorBody?.message) {
1171
- errorMessage = errorBody.message;
1172
- }
1173
- }
1174
- catch {
1175
- const errorText = await response.text();
1176
- if (errorText) {
1177
- errorMessage = errorText;
1178
- }
1179
- }
1180
- const error = new Error(`Failed to fetch configurations: ${errorMessage}`);
1181
- error.status = response.status;
1182
- throw error;
1183
- }
1184
- const configResponse = await response.json();
1185
- // Update cache if successful
1186
- if (configResponse.configurations) {
1187
- this.updateConfigCache(configResponse, userId);
1188
- }
1189
- this.log(`Successfully fetched configurations for user ${userId}:`, configResponse);
1190
- return configResponse;
1191
- }
1192
- catch (error) {
1193
- lastError = error;
1194
- if (attempt === this.config.retryAttempts) {
1195
- // Last attempt, don't retry - log error gracefully
1196
- const formattedError = this.formatError(error, `fetchConfig (attempt ${attempt + 1}/${this.config.retryAttempts + 1})`);
1197
- this.logError(formattedError);
1198
- return null;
1199
- }
1200
- if (!this.isRetriableError(error)) {
1201
- // Non-retriable error, don't retry - log error gracefully
1202
- const formattedError = this.formatError(error, 'fetchConfig (non-retriable error)');
1203
- this.logError(formattedError);
1204
- return null;
1205
- }
1206
- const delayMs = this.config.retryDelay * Math.pow(2, attempt);
1207
- this.log(`Retrying config fetch in ${delayMs}ms after error:`, error);
1208
- await this.delay(delayMs);
1209
- }
1210
- }
1211
- return null;
1212
- }
1213
- catch (error) {
1214
- const formattedError = this.formatError(error, 'fetchConfig');
1215
- this.logError(formattedError);
1216
- return null;
1217
- }
1218
- }
1219
- /**
1220
- * Get configuration asynchronously (cache-first with fallback to API)
1221
- */
1222
- async getConfigAsync(key, options = {}) {
1223
- try {
1224
- // Return immediately if we have it in cache and not forcing refresh
1225
- if (!options.forceRefresh && this.configCache?.configurations?.[key]) {
1226
- return this.configCache.configurations[key];
1227
- }
1228
- // Return default if available and not forcing refresh
1229
- if (!options.forceRefresh && this.config.defaultConfigurations?.[key]) {
1230
- return this.config.defaultConfigurations[key];
1231
- }
1232
- // Fetch from API
1233
- const response = await this.fetchConfig(options);
1234
- if (response) {
1235
- return response.configurations[key];
1236
- }
1237
- // Return default as fallback
1238
- return this.config.defaultConfigurations?.[key];
1239
- }
1240
- catch (error) {
1241
- const formattedError = this.formatError(error, 'getConfigAsync');
1242
- this.logError(formattedError);
1243
- // Return default as fallback
1244
- return this.config.defaultConfigurations?.[key];
1245
- }
1246
- }
1247
- /**
1248
- * Get all configurations asynchronously (cache-first with fallback to API)
1249
- */
1250
- async getAllConfigsAsync(options = {}) {
1251
- try {
1252
- // Return cache if available and not forcing refresh
1253
- if (!options.forceRefresh && this.configCache?.configurations) {
1254
- return { ...this.config.defaultConfigurations, ...this.configCache.configurations };
1255
- }
1256
- // Fetch from API
1257
- const response = await this.fetchConfig(options);
1258
- if (response) {
1259
- return { ...this.config.defaultConfigurations, ...response.configurations };
1260
- }
1261
- // Return defaults as fallback
1262
- return { ...this.config.defaultConfigurations };
1263
- }
1264
- catch (error) {
1265
- const formattedError = this.formatError(error, 'getAllConfigsAsync');
1266
- this.logError(formattedError);
1267
- // Return defaults as fallback
1268
- return { ...this.config.defaultConfigurations };
1269
- }
1270
- }
1271
- /**
1272
- * Update configuration cache and notify listeners
1273
- */
1274
- updateConfigCache(response, userId) {
1275
- const newCache = {
1276
- configurations: response.configurations,
1277
- snapshotId: response.snapshotId,
1278
- timestamp: response.timestamp,
1279
- userId,
1280
- };
1281
- const oldConfigs = this.configCache?.configurations || {};
1282
- this.configCache = newCache;
1283
- this.saveConfigCache(newCache);
1284
- // Notify listeners if configurations changed
1285
- if (JSON.stringify(oldConfigs) !== JSON.stringify(response.configurations)) {
1286
- this.notifyConfigChangeListeners(response.configurations);
1287
- }
1288
- }
1289
- /**
1290
- * Add configuration change listener
1291
- */
1292
- addConfigChangeListener(listener) {
1293
- this.configChangeListeners.push(listener);
1294
- }
1295
- /**
1296
- * Remove configuration change listener
1297
- */
1298
- removeConfigChangeListener(listener) {
1299
- const index = this.configChangeListeners.indexOf(listener);
1300
- if (index > -1) {
1301
- this.configChangeListeners.splice(index, 1);
1302
- }
1303
- }
1304
- /**
1305
- * Notify all configuration change listeners
1306
- */
1307
- notifyConfigChangeListeners(configurations) {
1308
- this.configChangeListeners.forEach(listener => {
1309
- try {
1310
- listener(configurations);
1311
- }
1312
- catch (error) {
1313
- console.error('[Grain Analytics] Config change listener error:', error);
1314
- }
1315
- });
1316
- }
1317
- /**
1318
- * Start automatic configuration refresh timer
1319
- */
1320
- startConfigRefreshTimer() {
1321
- if (typeof window === 'undefined')
1322
- return;
1323
- if (this.configRefreshTimer) {
1324
- clearInterval(this.configRefreshTimer);
1325
- }
1326
- this.configRefreshTimer = window.setInterval(() => {
1327
- if (!this.isDestroyed) {
1328
- // Use effective userId (will be generated if not set)
1329
- this.fetchConfig().catch((error) => {
1330
- const formattedError = this.formatError(error, 'auto-config refresh');
1331
- this.logError(formattedError);
1332
- });
1333
- }
1334
- }, this.config.configRefreshInterval);
1335
- }
1336
- /**
1337
- * Stop automatic configuration refresh timer
1338
- */
1339
- stopConfigRefreshTimer() {
1340
- if (this.configRefreshTimer) {
1341
- clearInterval(this.configRefreshTimer);
1342
- this.configRefreshTimer = null;
1343
- }
1344
- }
1345
- /**
1346
- * Preload configurations for immediate access
1347
- */
1348
- async preloadConfig(immediateKeys = [], properties) {
1349
- try {
1350
- // Use effective userId (will be generated if not set)
1351
- const effectiveUserId = this.getEffectiveUserIdInternal();
1352
- this.log(`Preloading config for user: ${effectiveUserId}`);
1353
- const response = await this.fetchConfig({ immediateKeys, properties });
1354
- if (response) {
1355
- this.startConfigRefreshTimer();
1356
- }
1357
- }
1358
- catch (error) {
1359
- const formattedError = this.formatError(error, 'preloadConfig');
1360
- this.logError(formattedError);
1361
- }
1362
- }
1363
- /**
1364
- * Split events array into chunks of specified size
1365
- */
1366
- chunkEvents(events, chunkSize) {
1367
- const chunks = [];
1368
- for (let i = 0; i < events.length; i += chunkSize) {
1369
- chunks.push(events.slice(i, i + chunkSize));
1370
- }
1371
- return chunks;
1372
- }
1373
- // Privacy & Consent Methods
1374
- /**
1375
- * Grant consent for tracking
1376
- * @param categories - Optional array of consent categories (e.g., ['analytics', 'functional'])
1377
- */
1378
- grantConsent(categories) {
1379
- try {
1380
- this.consentManager.grantConsent(categories);
1381
- this.log('Consent granted', categories);
1382
- }
1383
- catch (error) {
1384
- const formattedError = this.formatError(error, 'grantConsent');
1385
- this.logError(formattedError);
1386
- }
1387
- }
1388
- /**
1389
- * Revoke consent for tracking (opt-out)
1390
- * @param categories - Optional array of categories to revoke (if not provided, revokes all)
1391
- */
1392
- revokeConsent(categories) {
1393
- try {
1394
- this.consentManager.revokeConsent(categories);
1395
- this.log('Consent revoked', categories);
1396
- // Clear queued events when consent is revoked
1397
- this.eventQueue = [];
1398
- this.waitingForConsentQueue = [];
1399
- }
1400
- catch (error) {
1401
- const formattedError = this.formatError(error, 'revokeConsent');
1402
- this.logError(formattedError);
1403
- }
1404
- }
1405
- /**
1406
- * Get current consent state
1407
- */
1408
- getConsentState() {
1409
- return this.consentManager.getConsentState();
1410
- }
1411
- /**
1412
- * Check if user has granted consent
1413
- * @param category - Optional category to check (if not provided, checks general consent)
1414
- */
1415
- hasConsent(category) {
1416
- return this.consentManager.hasConsent(category);
1417
- }
1418
- /**
1419
- * Add listener for consent state changes
1420
- */
1421
- onConsentChange(listener) {
1422
- this.consentManager.addListener(listener);
1423
- }
1424
- /**
1425
- * Remove consent change listener
1426
- */
1427
- offConsentChange(listener) {
1428
- this.consentManager.removeListener(listener);
1429
- }
1430
- /**
1431
- * Destroy the client and clean up resources
1432
- */
1433
- destroy() {
1434
- this.isDestroyed = true;
1435
- if (this.flushTimer) {
1436
- clearInterval(this.flushTimer);
1437
- this.flushTimer = null;
1438
- }
1439
- // Stop config refresh timer
1440
- this.stopConfigRefreshTimer();
1441
- // Clear config change listeners
1442
- this.configChangeListeners = [];
1443
- // Destroy automatic tracking managers
1444
- if (this.heartbeatManager) {
1445
- this.heartbeatManager.destroy();
1446
- this.heartbeatManager = null;
1447
- }
1448
- if (this.pageTrackingManager) {
1449
- this.pageTrackingManager.destroy();
1450
- this.pageTrackingManager = null;
1451
- }
1452
- if (this.activityDetector) {
1453
- this.activityDetector.destroy();
1454
- this.activityDetector = null;
1455
- }
1456
- // Send any remaining events (in chunks if necessary)
1457
- if (this.eventQueue.length > 0) {
1458
- const eventsToSend = [...this.eventQueue];
1459
- this.eventQueue = [];
1460
- const chunks = this.chunkEvents(eventsToSend, this.config.maxEventsPerRequest);
1461
- // Send first chunk with beacon (most important for page unload)
1462
- if (chunks.length > 0) {
1463
- this.sendEventsWithBeacon(chunks[0]).catch(() => {
1464
- // Silently fail during cleanup
1465
- });
1466
- // If there are more chunks, try to send them with regular fetch
1467
- for (let i = 1; i < chunks.length; i++) {
1468
- this.sendEventsWithBeacon(chunks[i]).catch(() => {
1469
- // Silently fail during cleanup
1470
- });
1471
- }
1472
- }
1473
- }
1474
- }
1475
- }
1476
- /**
1477
- * Create a new Grain Analytics client
1478
- */
1479
- export function createGrainAnalytics(config) {
1480
- return new GrainAnalytics(config);
1481
- }
1482
- // Default export for convenience
1483
- export default GrainAnalytics;
1484
- // Auto-setup for IIFE build
1485
- if (typeof window !== 'undefined') {
1486
- window.Grain = {
1487
- GrainAnalytics,
1488
- createGrainAnalytics,
1489
- };
1490
- }
30
+ // Provider
31
+ export { GrainProvider } from './GrainProvider';
32
+ // Hooks
33
+ export { useGrainAnalytics } from './hooks/useGrainAnalytics';
34
+ export { useConfig } from './hooks/useConfig';
35
+ export { useAllConfigs } from './hooks/useAllConfigs';
36
+ export { useTrack } from './hooks/useTrack';
37
+ // Privacy hooks
38
+ export { useConsent } from './hooks/useConsent';
39
+ export { usePrivacyPreferences } from './hooks/usePrivacyPreferences';
40
+ export { useDataDeletion } from './hooks/useDataDeletion';
41
+ // Privacy components
42
+ export { ConsentBanner } from './components/ConsentBanner';
43
+ export { PrivacyPreferenceCenter } from './components/PrivacyPreferenceCenter';
44
+ export { CookieNotice } from './components/CookieNotice';