@grainql/analytics-web 1.7.2 → 1.7.4

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.
package/dist/index.js CHANGED
@@ -71,10 +71,10 @@ class GrainAnalytics {
71
71
  });
72
72
  }
73
73
  /**
74
- * Format UUID for anonymous user ID (remove dashes and prefix with 'temp:')
74
+ * Generate a proper UUIDv4 identifier for anonymous user ID
75
75
  */
76
- formatAnonymousUserId(uuid) {
77
- return `temp:${uuid.replace(/-/g, '')}`;
76
+ generateAnonymousUserId() {
77
+ return this.generateUUID();
78
78
  }
79
79
  /**
80
80
  * Initialize persistent anonymous user ID from localStorage or create new one
@@ -90,9 +90,8 @@ class GrainAnalytics {
90
90
  this.log('Loaded persistent anonymous user ID:', this.persistentAnonymousUserId);
91
91
  }
92
92
  else {
93
- // Generate new anonymous user ID
94
- const uuid = this.generateUUID();
95
- this.persistentAnonymousUserId = this.formatAnonymousUserId(uuid);
93
+ // Generate new UUIDv4 anonymous user ID
94
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
96
95
  localStorage.setItem(storageKey, this.persistentAnonymousUserId);
97
96
  this.log('Generated new persistent anonymous user ID:', this.persistentAnonymousUserId);
98
97
  }
@@ -100,15 +99,32 @@ class GrainAnalytics {
100
99
  catch (error) {
101
100
  this.log('Failed to initialize persistent anonymous user ID:', error);
102
101
  // Fallback: generate temporary ID without persistence
103
- const uuid = this.generateUUID();
104
- this.persistentAnonymousUserId = this.formatAnonymousUserId(uuid);
102
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
105
103
  }
106
104
  }
107
105
  /**
108
106
  * Get the effective user ID (global userId or persistent anonymous ID)
109
107
  */
110
108
  getEffectiveUserId() {
111
- return this.globalUserId || this.persistentAnonymousUserId || 'anonymous';
109
+ if (this.globalUserId) {
110
+ return this.globalUserId;
111
+ }
112
+ if (this.persistentAnonymousUserId) {
113
+ return this.persistentAnonymousUserId;
114
+ }
115
+ // Generate a new UUIDv4 identifier as fallback
116
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
117
+ // Try to persist it
118
+ if (typeof window !== 'undefined') {
119
+ try {
120
+ const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
121
+ localStorage.setItem(storageKey, this.persistentAnonymousUserId);
122
+ }
123
+ catch (error) {
124
+ this.log('Failed to persist generated anonymous user ID:', error);
125
+ }
126
+ }
127
+ return this.persistentAnonymousUserId;
112
128
  }
113
129
  log(...args) {
114
130
  if (this.config.debug) {
@@ -466,10 +482,26 @@ class GrainAnalytics {
466
482
  setUserId(userId) {
467
483
  this.log(`Set global user ID: ${userId}`);
468
484
  this.globalUserId = userId;
469
- // Clear persistent anonymous user ID if setting a real user ID
470
485
  if (userId) {
486
+ // Clear persistent anonymous user ID if setting a real user ID
471
487
  this.persistentAnonymousUserId = null;
472
488
  }
489
+ else {
490
+ // If clearing user ID, ensure we have a UUIDv4 identifier
491
+ if (!this.persistentAnonymousUserId) {
492
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
493
+ // Try to persist the new anonymous ID
494
+ if (typeof window !== 'undefined') {
495
+ try {
496
+ const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
497
+ localStorage.setItem(storageKey, this.persistentAnonymousUserId);
498
+ }
499
+ catch (error) {
500
+ this.log('Failed to persist new anonymous user ID:', error);
501
+ }
502
+ }
503
+ }
504
+ }
473
505
  }
474
506
  /**
475
507
  * Get current global user ID
@@ -483,6 +515,106 @@ class GrainAnalytics {
483
515
  getEffectiveUserIdPublic() {
484
516
  return this.getEffectiveUserId();
485
517
  }
518
+ /**
519
+ * Login with auth token or userId on the fly
520
+ *
521
+ * @example
522
+ * // Login with userId only
523
+ * client.login({ userId: 'user123' });
524
+ *
525
+ * // Login with auth token (automatically sets authStrategy to JWT)
526
+ * client.login({ authToken: 'jwt-token-here' });
527
+ *
528
+ * // Login with both userId and auth token
529
+ * client.login({ userId: 'user123', authToken: 'jwt-token-here' });
530
+ *
531
+ * // Override auth strategy
532
+ * client.login({ userId: 'user123', authStrategy: 'SERVER_SIDE' });
533
+ */
534
+ login(options) {
535
+ try {
536
+ if (this.isDestroyed) {
537
+ const error = new Error('Grain Analytics: Client has been destroyed');
538
+ const formattedError = this.formatError(error, 'login (client destroyed)');
539
+ this.logError(formattedError);
540
+ return;
541
+ }
542
+ // Set userId if provided
543
+ if (options.userId) {
544
+ this.log(`Login: Setting user ID to ${options.userId}`);
545
+ this.globalUserId = options.userId;
546
+ // Clear persistent anonymous user ID since we now have a real user ID
547
+ this.persistentAnonymousUserId = null;
548
+ }
549
+ // Handle auth token if provided
550
+ if (options.authToken) {
551
+ this.log('Login: Setting auth token');
552
+ // Update auth strategy to JWT if not already set
553
+ if (this.config.authStrategy === 'NONE') {
554
+ this.config.authStrategy = 'JWT';
555
+ }
556
+ // Create a simple auth provider that returns the provided token
557
+ this.config.authProvider = {
558
+ getToken: () => options.authToken
559
+ };
560
+ }
561
+ // Override auth strategy if provided
562
+ if (options.authStrategy) {
563
+ this.log(`Login: Setting auth strategy to ${options.authStrategy}`);
564
+ this.config.authStrategy = options.authStrategy;
565
+ }
566
+ this.log(`Login successful. Effective user ID: ${this.getEffectiveUserId()}`);
567
+ }
568
+ catch (error) {
569
+ const formattedError = this.formatError(error, 'login');
570
+ this.logError(formattedError);
571
+ }
572
+ }
573
+ /**
574
+ * Logout and clear user session, fall back to UUIDv4 identifier
575
+ *
576
+ * @example
577
+ * // Logout user and return to anonymous mode
578
+ * client.logout();
579
+ *
580
+ * // After logout, events will use the persistent UUIDv4 identifier
581
+ * client.track('page_view', { page: 'home' });
582
+ */
583
+ logout() {
584
+ try {
585
+ if (this.isDestroyed) {
586
+ const error = new Error('Grain Analytics: Client has been destroyed');
587
+ const formattedError = this.formatError(error, 'logout (client destroyed)');
588
+ this.logError(formattedError);
589
+ return;
590
+ }
591
+ this.log('Logout: Clearing user session');
592
+ // Clear global user ID
593
+ this.globalUserId = null;
594
+ // Reset auth strategy to NONE
595
+ this.config.authStrategy = 'NONE';
596
+ this.config.authProvider = undefined;
597
+ // Generate new UUIDv4 identifier if we don't have one
598
+ if (!this.persistentAnonymousUserId) {
599
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
600
+ // Try to persist the new anonymous ID
601
+ if (typeof window !== 'undefined') {
602
+ try {
603
+ const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
604
+ localStorage.setItem(storageKey, this.persistentAnonymousUserId);
605
+ }
606
+ catch (error) {
607
+ this.log('Failed to persist new anonymous user ID after logout:', error);
608
+ }
609
+ }
610
+ }
611
+ this.log(`Logout successful. Effective user ID: ${this.getEffectiveUserId()}`);
612
+ }
613
+ catch (error) {
614
+ const formattedError = this.formatError(error, 'logout');
615
+ this.logError(formattedError);
616
+ }
617
+ }
486
618
  /**
487
619
  * Set user properties
488
620
  */
@@ -952,7 +1084,8 @@ class GrainAnalytics {
952
1084
  clearInterval(this.configRefreshTimer);
953
1085
  }
954
1086
  this.configRefreshTimer = window.setInterval(() => {
955
- if (!this.isDestroyed && this.globalUserId) {
1087
+ if (!this.isDestroyed) {
1088
+ // Use effective userId (will be generated if not set)
956
1089
  this.fetchConfig().catch((error) => {
957
1090
  const formattedError = this.formatError(error, 'auto-config refresh');
958
1091
  this.logError(formattedError);
@@ -974,10 +1107,9 @@ class GrainAnalytics {
974
1107
  */
975
1108
  async preloadConfig(immediateKeys = [], properties) {
976
1109
  try {
977
- if (!this.globalUserId) {
978
- this.log('Cannot preload config: no user ID set');
979
- return;
980
- }
1110
+ // Use effective userId (will be generated if not set)
1111
+ const effectiveUserId = this.getEffectiveUserId();
1112
+ this.log(`Preloading config for user: ${effectiveUserId}`);
981
1113
  const response = await this.fetchConfig({ immediateKeys, properties });
982
1114
  if (response) {
983
1115
  this.startConfigRefreshTimer();
package/dist/index.mjs CHANGED
@@ -67,10 +67,10 @@ export class GrainAnalytics {
67
67
  });
68
68
  }
69
69
  /**
70
- * Format UUID for anonymous user ID (remove dashes and prefix with 'temp:')
70
+ * Generate a proper UUIDv4 identifier for anonymous user ID
71
71
  */
72
- formatAnonymousUserId(uuid) {
73
- return `temp:${uuid.replace(/-/g, '')}`;
72
+ generateAnonymousUserId() {
73
+ return this.generateUUID();
74
74
  }
75
75
  /**
76
76
  * Initialize persistent anonymous user ID from localStorage or create new one
@@ -86,9 +86,8 @@ export class GrainAnalytics {
86
86
  this.log('Loaded persistent anonymous user ID:', this.persistentAnonymousUserId);
87
87
  }
88
88
  else {
89
- // Generate new anonymous user ID
90
- const uuid = this.generateUUID();
91
- this.persistentAnonymousUserId = this.formatAnonymousUserId(uuid);
89
+ // Generate new UUIDv4 anonymous user ID
90
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
92
91
  localStorage.setItem(storageKey, this.persistentAnonymousUserId);
93
92
  this.log('Generated new persistent anonymous user ID:', this.persistentAnonymousUserId);
94
93
  }
@@ -96,15 +95,32 @@ export class GrainAnalytics {
96
95
  catch (error) {
97
96
  this.log('Failed to initialize persistent anonymous user ID:', error);
98
97
  // Fallback: generate temporary ID without persistence
99
- const uuid = this.generateUUID();
100
- this.persistentAnonymousUserId = this.formatAnonymousUserId(uuid);
98
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
101
99
  }
102
100
  }
103
101
  /**
104
102
  * Get the effective user ID (global userId or persistent anonymous ID)
105
103
  */
106
104
  getEffectiveUserId() {
107
- return this.globalUserId || this.persistentAnonymousUserId || 'anonymous';
105
+ if (this.globalUserId) {
106
+ return this.globalUserId;
107
+ }
108
+ if (this.persistentAnonymousUserId) {
109
+ return this.persistentAnonymousUserId;
110
+ }
111
+ // Generate a new UUIDv4 identifier as fallback
112
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
113
+ // Try to persist it
114
+ if (typeof window !== 'undefined') {
115
+ try {
116
+ const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
117
+ localStorage.setItem(storageKey, this.persistentAnonymousUserId);
118
+ }
119
+ catch (error) {
120
+ this.log('Failed to persist generated anonymous user ID:', error);
121
+ }
122
+ }
123
+ return this.persistentAnonymousUserId;
108
124
  }
109
125
  log(...args) {
110
126
  if (this.config.debug) {
@@ -462,10 +478,26 @@ export class GrainAnalytics {
462
478
  setUserId(userId) {
463
479
  this.log(`Set global user ID: ${userId}`);
464
480
  this.globalUserId = userId;
465
- // Clear persistent anonymous user ID if setting a real user ID
466
481
  if (userId) {
482
+ // Clear persistent anonymous user ID if setting a real user ID
467
483
  this.persistentAnonymousUserId = null;
468
484
  }
485
+ else {
486
+ // If clearing user ID, ensure we have a UUIDv4 identifier
487
+ if (!this.persistentAnonymousUserId) {
488
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
489
+ // Try to persist the new anonymous ID
490
+ if (typeof window !== 'undefined') {
491
+ try {
492
+ const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
493
+ localStorage.setItem(storageKey, this.persistentAnonymousUserId);
494
+ }
495
+ catch (error) {
496
+ this.log('Failed to persist new anonymous user ID:', error);
497
+ }
498
+ }
499
+ }
500
+ }
469
501
  }
470
502
  /**
471
503
  * Get current global user ID
@@ -479,6 +511,106 @@ export class GrainAnalytics {
479
511
  getEffectiveUserIdPublic() {
480
512
  return this.getEffectiveUserId();
481
513
  }
514
+ /**
515
+ * Login with auth token or userId on the fly
516
+ *
517
+ * @example
518
+ * // Login with userId only
519
+ * client.login({ userId: 'user123' });
520
+ *
521
+ * // Login with auth token (automatically sets authStrategy to JWT)
522
+ * client.login({ authToken: 'jwt-token-here' });
523
+ *
524
+ * // Login with both userId and auth token
525
+ * client.login({ userId: 'user123', authToken: 'jwt-token-here' });
526
+ *
527
+ * // Override auth strategy
528
+ * client.login({ userId: 'user123', authStrategy: 'SERVER_SIDE' });
529
+ */
530
+ login(options) {
531
+ try {
532
+ if (this.isDestroyed) {
533
+ const error = new Error('Grain Analytics: Client has been destroyed');
534
+ const formattedError = this.formatError(error, 'login (client destroyed)');
535
+ this.logError(formattedError);
536
+ return;
537
+ }
538
+ // Set userId if provided
539
+ if (options.userId) {
540
+ this.log(`Login: Setting user ID to ${options.userId}`);
541
+ this.globalUserId = options.userId;
542
+ // Clear persistent anonymous user ID since we now have a real user ID
543
+ this.persistentAnonymousUserId = null;
544
+ }
545
+ // Handle auth token if provided
546
+ if (options.authToken) {
547
+ this.log('Login: Setting auth token');
548
+ // Update auth strategy to JWT if not already set
549
+ if (this.config.authStrategy === 'NONE') {
550
+ this.config.authStrategy = 'JWT';
551
+ }
552
+ // Create a simple auth provider that returns the provided token
553
+ this.config.authProvider = {
554
+ getToken: () => options.authToken
555
+ };
556
+ }
557
+ // Override auth strategy if provided
558
+ if (options.authStrategy) {
559
+ this.log(`Login: Setting auth strategy to ${options.authStrategy}`);
560
+ this.config.authStrategy = options.authStrategy;
561
+ }
562
+ this.log(`Login successful. Effective user ID: ${this.getEffectiveUserId()}`);
563
+ }
564
+ catch (error) {
565
+ const formattedError = this.formatError(error, 'login');
566
+ this.logError(formattedError);
567
+ }
568
+ }
569
+ /**
570
+ * Logout and clear user session, fall back to UUIDv4 identifier
571
+ *
572
+ * @example
573
+ * // Logout user and return to anonymous mode
574
+ * client.logout();
575
+ *
576
+ * // After logout, events will use the persistent UUIDv4 identifier
577
+ * client.track('page_view', { page: 'home' });
578
+ */
579
+ logout() {
580
+ try {
581
+ if (this.isDestroyed) {
582
+ const error = new Error('Grain Analytics: Client has been destroyed');
583
+ const formattedError = this.formatError(error, 'logout (client destroyed)');
584
+ this.logError(formattedError);
585
+ return;
586
+ }
587
+ this.log('Logout: Clearing user session');
588
+ // Clear global user ID
589
+ this.globalUserId = null;
590
+ // Reset auth strategy to NONE
591
+ this.config.authStrategy = 'NONE';
592
+ this.config.authProvider = undefined;
593
+ // Generate new UUIDv4 identifier if we don't have one
594
+ if (!this.persistentAnonymousUserId) {
595
+ this.persistentAnonymousUserId = this.generateAnonymousUserId();
596
+ // Try to persist the new anonymous ID
597
+ if (typeof window !== 'undefined') {
598
+ try {
599
+ const storageKey = `grain_anonymous_user_id_${this.config.tenantId}`;
600
+ localStorage.setItem(storageKey, this.persistentAnonymousUserId);
601
+ }
602
+ catch (error) {
603
+ this.log('Failed to persist new anonymous user ID after logout:', error);
604
+ }
605
+ }
606
+ }
607
+ this.log(`Logout successful. Effective user ID: ${this.getEffectiveUserId()}`);
608
+ }
609
+ catch (error) {
610
+ const formattedError = this.formatError(error, 'logout');
611
+ this.logError(formattedError);
612
+ }
613
+ }
482
614
  /**
483
615
  * Set user properties
484
616
  */
@@ -948,7 +1080,8 @@ export class GrainAnalytics {
948
1080
  clearInterval(this.configRefreshTimer);
949
1081
  }
950
1082
  this.configRefreshTimer = window.setInterval(() => {
951
- if (!this.isDestroyed && this.globalUserId) {
1083
+ if (!this.isDestroyed) {
1084
+ // Use effective userId (will be generated if not set)
952
1085
  this.fetchConfig().catch((error) => {
953
1086
  const formattedError = this.formatError(error, 'auto-config refresh');
954
1087
  this.logError(formattedError);
@@ -970,10 +1103,9 @@ export class GrainAnalytics {
970
1103
  */
971
1104
  async preloadConfig(immediateKeys = [], properties) {
972
1105
  try {
973
- if (!this.globalUserId) {
974
- this.log('Cannot preload config: no user ID set');
975
- return;
976
- }
1106
+ // Use effective userId (will be generated if not set)
1107
+ const effectiveUserId = this.getEffectiveUserId();
1108
+ this.log(`Preloading config for user: ${effectiveUserId}`);
977
1109
  const response = await this.fetchConfig({ immediateKeys, properties });
978
1110
  if (response) {
979
1111
  this.startConfigRefreshTimer();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grainql/analytics-web",
3
- "version": "1.7.2",
3
+ "version": "1.7.4",
4
4
  "description": "Lightweight TypeScript SDK for sending analytics events and managing remote configurations via Grain's REST API",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",