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