@grainql/analytics-web 1.7.4 → 2.1.0

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