@clianta/sdk 1.6.8 → 1.7.2

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.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.6.8
2
+ * Clianta SDK v1.7.2
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -11,7 +11,7 @@ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentS
11
11
  * @see SDK_VERSION in core/config.ts
12
12
  */
13
13
  /** SDK Version */
14
- const SDK_VERSION = '1.6.7';
14
+ const SDK_VERSION = '1.7.2';
15
15
  /** Default API endpoint — reads from env or falls back to localhost */
16
16
  const getDefaultApiEndpoint = () => {
17
17
  // Next.js (process.env)
@@ -37,6 +37,15 @@ const getDefaultApiEndpoint = () => {
37
37
  if (typeof process !== 'undefined' && process.env?.CLIANTA_API_ENDPOINT) {
38
38
  return process.env.CLIANTA_API_ENDPOINT;
39
39
  }
40
+ // No env var found — warn if we're not on localhost (likely a production misconfiguration)
41
+ const isLocalhost = typeof window !== 'undefined' &&
42
+ (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');
43
+ if (!isLocalhost && typeof console !== 'undefined') {
44
+ console.warn('[Clianta] No API endpoint configured. ' +
45
+ 'Set NEXT_PUBLIC_CLIANTA_API_ENDPOINT (Next.js), VITE_CLIANTA_API_ENDPOINT (Vite), ' +
46
+ 'or pass apiEndpoint directly to clianta(). ' +
47
+ 'Falling back to localhost — tracking will not work in production.');
48
+ }
40
49
  return 'http://localhost:5000';
41
50
  };
42
51
  /** Core plugins enabled by default — all auto-track with zero config */
@@ -182,7 +191,9 @@ const logger = createLogger(false);
182
191
  */
183
192
  const DEFAULT_TIMEOUT = 10000; // 10 seconds
184
193
  const DEFAULT_MAX_RETRIES = 3;
185
- const DEFAULT_RETRY_DELAY = 1000; // 1 second
194
+ const DEFAULT_RETRY_DELAY = 1000; // 1 second base — doubles each attempt (exponential backoff)
195
+ /** fetch keepalive hard limit in browsers (64KB) */
196
+ const KEEPALIVE_SIZE_LIMIT = 60000; // leave 4KB margin
186
197
  /**
187
198
  * Transport class for sending data to the backend
188
199
  */
@@ -201,6 +212,11 @@ class Transport {
201
212
  async sendEvents(events) {
202
213
  const url = `${this.config.apiEndpoint}/api/public/track/event`;
203
214
  const payload = JSON.stringify({ events });
215
+ // keepalive has a 64KB hard limit — fall back to beacon if too large
216
+ if (payload.length > KEEPALIVE_SIZE_LIMIT) {
217
+ const sent = this.sendBeacon(events);
218
+ return sent ? { success: true } : this.send(url, payload, 1, false);
219
+ }
204
220
  return this.send(url, payload);
205
221
  }
206
222
  /**
@@ -265,6 +281,15 @@ class Transport {
265
281
  return false;
266
282
  }
267
283
  }
284
+ /**
285
+ * Send an arbitrary POST request through the transport (with timeout + retry).
286
+ * Used for one-off calls like alias() that don't fit the event-batch or identify shapes.
287
+ */
288
+ async sendPost(path, body) {
289
+ const url = `${this.config.apiEndpoint}${path}`;
290
+ const payload = JSON.stringify(body);
291
+ return this.send(url, payload);
292
+ }
268
293
  /**
269
294
  * Fetch data from the tracking API (GET request)
270
295
  * Used for read-back APIs (visitor profile, activity, etc.)
@@ -299,38 +324,44 @@ class Transport {
299
324
  }
300
325
  }
301
326
  /**
302
- * Internal send with retry logic
327
+ * Internal send with exponential backoff retry logic
303
328
  */
304
- async send(url, payload, attempt = 1) {
329
+ async send(url, payload, attempt = 1, useKeepalive = true) {
330
+ // Don't bother sending when offline — caller should re-queue
331
+ if (typeof navigator !== 'undefined' && !navigator.onLine) {
332
+ logger.warn('Device offline, skipping send');
333
+ return { success: false, error: new Error('offline') };
334
+ }
305
335
  try {
306
336
  const response = await this.fetchWithTimeout(url, {
307
337
  method: 'POST',
308
- headers: {
309
- 'Content-Type': 'application/json',
310
- },
338
+ headers: { 'Content-Type': 'application/json' },
311
339
  body: payload,
312
- keepalive: true,
340
+ keepalive: useKeepalive,
313
341
  });
314
342
  if (response.ok) {
315
343
  logger.debug('Request successful:', url);
316
344
  return { success: true, status: response.status };
317
345
  }
318
- // Server error - may retry
346
+ // Server error retry with exponential backoff
319
347
  if (response.status >= 500 && attempt < this.config.maxRetries) {
320
- logger.warn(`Server error (${response.status}), retrying...`);
321
- await this.delay(this.config.retryDelay * attempt);
322
- return this.send(url, payload, attempt + 1);
348
+ const backoff = this.config.retryDelay * Math.pow(2, attempt - 1);
349
+ logger.warn(`Server error (${response.status}), retrying in ${backoff}ms...`);
350
+ await this.delay(backoff);
351
+ return this.send(url, payload, attempt + 1, useKeepalive);
323
352
  }
324
- // Client error - don't retry
353
+ // 4xx don't retry (bad payload, auth failure, etc.)
325
354
  logger.error(`Request failed with status ${response.status}`);
326
355
  return { success: false, status: response.status };
327
356
  }
328
357
  catch (error) {
329
- // Network error - retry if possible
330
- if (attempt < this.config.maxRetries) {
331
- logger.warn(`Network error, retrying (${attempt}/${this.config.maxRetries})...`);
332
- await this.delay(this.config.retryDelay * attempt);
333
- return this.send(url, payload, attempt + 1);
358
+ // Network error retry with exponential backoff if still online
359
+ const isOnline = typeof navigator === 'undefined' || navigator.onLine;
360
+ if (isOnline && attempt < this.config.maxRetries) {
361
+ const backoff = this.config.retryDelay * Math.pow(2, attempt - 1);
362
+ logger.warn(`Network error, retrying in ${backoff}ms (${attempt}/${this.config.maxRetries})...`);
363
+ await this.delay(backoff);
364
+ return this.send(url, payload, attempt + 1, useKeepalive);
334
365
  }
335
366
  logger.error('Request failed after retries:', error);
336
367
  return { success: false, error: error };
@@ -679,12 +710,17 @@ class EventQueue {
679
710
  this.queue = [];
680
711
  this.flushTimer = null;
681
712
  this.isFlushing = false;
713
+ this.isOnline = true;
682
714
  /** Rate limiting: timestamps of recent events */
683
715
  this.eventTimestamps = [];
684
716
  /** Unload handler references for cleanup */
685
717
  this.boundBeforeUnload = null;
686
718
  this.boundVisibilityChange = null;
687
719
  this.boundPageHide = null;
720
+ this.boundOnline = null;
721
+ this.boundOffline = null;
722
+ /** Guards against double-flush on unload (beforeunload + pagehide + visibilitychange all fire) */
723
+ this.unloadFlushed = false;
688
724
  this.transport = transport;
689
725
  this.config = {
690
726
  batchSize: config.batchSize ?? 10,
@@ -693,6 +729,7 @@ class EventQueue {
693
729
  storageKey: config.storageKey ?? STORAGE_KEYS.EVENT_QUEUE,
694
730
  };
695
731
  this.persistMode = config.persistMode || 'session';
732
+ this.isOnline = typeof navigator === 'undefined' || navigator.onLine;
696
733
  // Restore persisted queue
697
734
  this.restoreQueue();
698
735
  // Start auto-flush timer
@@ -741,7 +778,7 @@ class EventQueue {
741
778
  * Flush the queue (send all events)
742
779
  */
743
780
  async flush() {
744
- if (this.isFlushing || this.queue.length === 0) {
781
+ if (this.isFlushing || this.queue.length === 0 || !this.isOnline) {
745
782
  return;
746
783
  }
747
784
  this.isFlushing = true;
@@ -772,11 +809,14 @@ class EventQueue {
772
809
  }
773
810
  }
774
811
  /**
775
- * Flush synchronously using sendBeacon (for page unload)
812
+ * Flush synchronously using sendBeacon (for page unload).
813
+ * Guarded: no-ops after the first call per navigation to prevent
814
+ * triple-flush from beforeunload + visibilitychange + pagehide.
776
815
  */
777
816
  flushSync() {
778
- if (this.queue.length === 0)
817
+ if (this.unloadFlushed || this.queue.length === 0)
779
818
  return;
819
+ this.unloadFlushed = true;
780
820
  const events = this.queue.splice(0, this.queue.length);
781
821
  logger.debug(`Sync flushing ${events.length} events via beacon`);
782
822
  const success = this.transport.sendBeacon(events);
@@ -814,17 +854,17 @@ class EventQueue {
814
854
  clearInterval(this.flushTimer);
815
855
  this.flushTimer = null;
816
856
  }
817
- // Remove unload handlers
818
857
  if (typeof window !== 'undefined') {
819
- if (this.boundBeforeUnload) {
858
+ if (this.boundBeforeUnload)
820
859
  window.removeEventListener('beforeunload', this.boundBeforeUnload);
821
- }
822
- if (this.boundVisibilityChange) {
860
+ if (this.boundVisibilityChange)
823
861
  window.removeEventListener('visibilitychange', this.boundVisibilityChange);
824
- }
825
- if (this.boundPageHide) {
862
+ if (this.boundPageHide)
826
863
  window.removeEventListener('pagehide', this.boundPageHide);
827
- }
864
+ if (this.boundOnline)
865
+ window.removeEventListener('online', this.boundOnline);
866
+ if (this.boundOffline)
867
+ window.removeEventListener('offline', this.boundOffline);
828
868
  }
829
869
  }
830
870
  /**
@@ -839,24 +879,38 @@ class EventQueue {
839
879
  }, this.config.flushInterval);
840
880
  }
841
881
  /**
842
- * Setup page unload handlers
882
+ * Setup page unload handlers and online/offline listeners
843
883
  */
844
884
  setupUnloadHandlers() {
845
885
  if (typeof window === 'undefined')
846
886
  return;
847
- // Flush on page unload
887
+ // All three unload events share the same guarded flushSync()
848
888
  this.boundBeforeUnload = () => this.flushSync();
849
889
  window.addEventListener('beforeunload', this.boundBeforeUnload);
850
- // Flush when page becomes hidden
851
890
  this.boundVisibilityChange = () => {
852
891
  if (document.visibilityState === 'hidden') {
853
892
  this.flushSync();
854
893
  }
894
+ else {
895
+ // Page became visible again (e.g. tab switch back) — reset guard
896
+ this.unloadFlushed = false;
897
+ }
855
898
  };
856
899
  window.addEventListener('visibilitychange', this.boundVisibilityChange);
857
- // Flush on page hide (iOS Safari)
858
900
  this.boundPageHide = () => this.flushSync();
859
901
  window.addEventListener('pagehide', this.boundPageHide);
902
+ // Pause queue when offline, resume + flush when back online
903
+ this.boundOnline = () => {
904
+ logger.info('Connection restored — flushing queued events');
905
+ this.isOnline = true;
906
+ this.flush();
907
+ };
908
+ this.boundOffline = () => {
909
+ logger.warn('Connection lost — pausing event queue');
910
+ this.isOnline = false;
911
+ };
912
+ window.addEventListener('online', this.boundOnline);
913
+ window.addEventListener('offline', this.boundOffline);
860
914
  }
861
915
  /**
862
916
  * Persist queue to storage based on persistMode
@@ -939,6 +993,8 @@ class BasePlugin {
939
993
  * Clianta SDK - Page View Plugin
940
994
  * @see SDK_VERSION in core/config.ts
941
995
  */
996
+ /** Sentinel flag to prevent double-wrapping history methods across multiple SDK instances */
997
+ const WRAPPED_FLAG = '__clianta_pv_wrapped__';
942
998
  /**
943
999
  * Page View Plugin - Tracks page views
944
1000
  */
@@ -948,50 +1004,64 @@ class PageViewPlugin extends BasePlugin {
948
1004
  this.name = 'pageView';
949
1005
  this.originalPushState = null;
950
1006
  this.originalReplaceState = null;
1007
+ this.navHandler = null;
951
1008
  this.popstateHandler = null;
952
1009
  }
953
1010
  init(tracker) {
954
1011
  super.init(tracker);
955
1012
  // Track initial page view
956
1013
  this.trackPageView();
957
- // Track SPA navigation (History API)
958
- if (typeof window !== 'undefined') {
959
- // Store originals for cleanup
1014
+ if (typeof window === 'undefined')
1015
+ return;
1016
+ // Only wrap history methods once — guard against multiple SDK instances (e.g. microfrontends)
1017
+ // wrapping them repeatedly, which would cause duplicate navigation events and broken cleanup.
1018
+ if (!history.pushState[WRAPPED_FLAG]) {
960
1019
  this.originalPushState = history.pushState;
961
1020
  this.originalReplaceState = history.replaceState;
962
- // Intercept pushState and replaceState
963
- const self = this;
1021
+ const originalPush = this.originalPushState;
1022
+ const originalReplace = this.originalReplaceState;
964
1023
  history.pushState = function (...args) {
965
- self.originalPushState.apply(history, args);
966
- self.trackPageView();
967
- // Notify other plugins (e.g. ScrollPlugin) about navigation
1024
+ originalPush.apply(history, args);
1025
+ // Dispatch event so all listening instances track the navigation
968
1026
  window.dispatchEvent(new Event('clianta:navigation'));
969
1027
  };
1028
+ history.pushState[WRAPPED_FLAG] = true;
970
1029
  history.replaceState = function (...args) {
971
- self.originalReplaceState.apply(history, args);
972
- self.trackPageView();
1030
+ originalReplace.apply(history, args);
973
1031
  window.dispatchEvent(new Event('clianta:navigation'));
974
1032
  };
975
- // Handle back/forward navigation
976
- this.popstateHandler = () => this.trackPageView();
977
- window.addEventListener('popstate', this.popstateHandler);
1033
+ history.replaceState[WRAPPED_FLAG] = true;
978
1034
  }
1035
+ // Each instance listens to the shared navigation event rather than embedding
1036
+ // tracking directly in the pushState wrapper — decouples tracking from wrapping.
1037
+ this.navHandler = () => this.trackPageView();
1038
+ window.addEventListener('clianta:navigation', this.navHandler);
1039
+ // Handle back/forward navigation
1040
+ this.popstateHandler = () => this.trackPageView();
1041
+ window.addEventListener('popstate', this.popstateHandler);
979
1042
  }
980
1043
  destroy() {
981
- // Restore original history methods
1044
+ if (typeof window !== 'undefined') {
1045
+ if (this.navHandler) {
1046
+ window.removeEventListener('clianta:navigation', this.navHandler);
1047
+ this.navHandler = null;
1048
+ }
1049
+ if (this.popstateHandler) {
1050
+ window.removeEventListener('popstate', this.popstateHandler);
1051
+ this.popstateHandler = null;
1052
+ }
1053
+ }
1054
+ // Restore original history methods only if this instance was the one that wrapped them
982
1055
  if (this.originalPushState) {
983
1056
  history.pushState = this.originalPushState;
1057
+ delete history.pushState[WRAPPED_FLAG];
984
1058
  this.originalPushState = null;
985
1059
  }
986
1060
  if (this.originalReplaceState) {
987
1061
  history.replaceState = this.originalReplaceState;
1062
+ delete history.replaceState[WRAPPED_FLAG];
988
1063
  this.originalReplaceState = null;
989
1064
  }
990
- // Remove popstate listener
991
- if (this.popstateHandler && typeof window !== 'undefined') {
992
- window.removeEventListener('popstate', this.popstateHandler);
993
- this.popstateHandler = null;
994
- }
995
1065
  super.destroy();
996
1066
  }
997
1067
  trackPageView() {
@@ -1120,6 +1190,7 @@ class FormsPlugin extends BasePlugin {
1120
1190
  this.trackedForms = new WeakSet();
1121
1191
  this.formInteractions = new Set();
1122
1192
  this.observer = null;
1193
+ this.observerTimer = null;
1123
1194
  this.listeners = [];
1124
1195
  }
1125
1196
  init(tracker) {
@@ -1128,13 +1199,21 @@ class FormsPlugin extends BasePlugin {
1128
1199
  return;
1129
1200
  // Track existing forms
1130
1201
  this.trackAllForms();
1131
- // Watch for dynamically added forms
1202
+ // Watch for dynamically added forms — debounced to avoid O(DOM) cost on every mutation
1132
1203
  if (typeof MutationObserver !== 'undefined') {
1133
- this.observer = new MutationObserver(() => this.trackAllForms());
1204
+ this.observer = new MutationObserver(() => {
1205
+ if (this.observerTimer)
1206
+ clearTimeout(this.observerTimer);
1207
+ this.observerTimer = setTimeout(() => this.trackAllForms(), 100);
1208
+ });
1134
1209
  this.observer.observe(document.body, { childList: true, subtree: true });
1135
1210
  }
1136
1211
  }
1137
1212
  destroy() {
1213
+ if (this.observerTimer) {
1214
+ clearTimeout(this.observerTimer);
1215
+ this.observerTimer = null;
1216
+ }
1138
1217
  if (this.observer) {
1139
1218
  this.observer.disconnect();
1140
1219
  this.observer = null;
@@ -1256,8 +1335,13 @@ class ClicksPlugin extends BasePlugin {
1256
1335
  super.destroy();
1257
1336
  }
1258
1337
  handleClick(e) {
1259
- const target = e.target;
1260
- if (!target || !isTrackableClickElement(target))
1338
+ // Walk up the DOM to find the nearest trackable ancestor.
1339
+ // Without this, clicks on <span> or <img> inside a <button> are silently dropped.
1340
+ let target = e.target;
1341
+ while (target && !isTrackableClickElement(target)) {
1342
+ target = target.parentElement;
1343
+ }
1344
+ if (!target)
1261
1345
  return;
1262
1346
  const buttonText = getElementText(target, 100);
1263
1347
  const elementInfo = getElementInfo(target);
@@ -1290,6 +1374,8 @@ class EngagementPlugin extends BasePlugin {
1290
1374
  this.engagementStartTime = 0;
1291
1375
  this.isEngaged = false;
1292
1376
  this.engagementTimeout = null;
1377
+ /** Guard: beforeunload + visibilitychange:hidden both fire on tab close — only report once */
1378
+ this.unloadReported = false;
1293
1379
  this.boundMarkEngaged = null;
1294
1380
  this.boundTrackTimeOnPage = null;
1295
1381
  this.boundVisibilityHandler = null;
@@ -1311,8 +1397,9 @@ class EngagementPlugin extends BasePlugin {
1311
1397
  this.trackTimeOnPage();
1312
1398
  }
1313
1399
  else {
1314
- // Reset engagement timer when page becomes visible again
1400
+ // Page is visible again reset both the time counter and the unload guard
1315
1401
  this.engagementStartTime = Date.now();
1402
+ this.unloadReported = false;
1316
1403
  }
1317
1404
  };
1318
1405
  ['mousemove', 'keydown', 'touchstart', 'scroll'].forEach((event) => {
@@ -1358,6 +1445,7 @@ class EngagementPlugin extends BasePlugin {
1358
1445
  this.pageLoadTime = Date.now();
1359
1446
  this.engagementStartTime = Date.now();
1360
1447
  this.isEngaged = false;
1448
+ this.unloadReported = false;
1361
1449
  if (this.engagementTimeout) {
1362
1450
  clearTimeout(this.engagementTimeout);
1363
1451
  this.engagementTimeout = null;
@@ -1379,6 +1467,10 @@ class EngagementPlugin extends BasePlugin {
1379
1467
  }, 30000); // 30 seconds of inactivity
1380
1468
  }
1381
1469
  trackTimeOnPage() {
1470
+ // Guard: beforeunload and visibilitychange:hidden both fire on tab close — only report once
1471
+ if (this.unloadReported)
1472
+ return;
1473
+ this.unloadReported = true;
1382
1474
  const timeSpent = Math.floor((Date.now() - this.engagementStartTime) / 1000);
1383
1475
  if (timeSpent > 0) {
1384
1476
  this.track('time_on_page', 'Time Spent', {
@@ -1537,12 +1629,16 @@ class ExitIntentPlugin extends BasePlugin {
1537
1629
  /**
1538
1630
  * Error Tracking Plugin - Tracks JavaScript errors
1539
1631
  */
1632
+ /** Max unique errors to track per page (prevents queue flooding from error loops) */
1633
+ const MAX_UNIQUE_ERRORS = 20;
1540
1634
  class ErrorsPlugin extends BasePlugin {
1541
1635
  constructor() {
1542
1636
  super(...arguments);
1543
1637
  this.name = 'errors';
1544
1638
  this.boundErrorHandler = null;
1545
1639
  this.boundRejectionHandler = null;
1640
+ /** Seen error fingerprints — deduplicates repeated identical errors */
1641
+ this.seenErrors = new Set();
1546
1642
  }
1547
1643
  init(tracker) {
1548
1644
  super.init(tracker);
@@ -1565,6 +1661,9 @@ class ErrorsPlugin extends BasePlugin {
1565
1661
  super.destroy();
1566
1662
  }
1567
1663
  handleError(e) {
1664
+ const fingerprint = `${e.message}:${e.filename}:${e.lineno}`;
1665
+ if (!this.dedup(fingerprint))
1666
+ return;
1568
1667
  this.track('error', 'JavaScript Error', {
1569
1668
  message: e.message,
1570
1669
  filename: e.filename,
@@ -1574,9 +1673,22 @@ class ErrorsPlugin extends BasePlugin {
1574
1673
  });
1575
1674
  }
1576
1675
  handleRejection(e) {
1577
- this.track('error', 'Unhandled Promise Rejection', {
1578
- reason: String(e.reason).substring(0, 200),
1579
- });
1676
+ const reason = String(e.reason).substring(0, 200);
1677
+ if (!this.dedup(reason))
1678
+ return;
1679
+ this.track('error', 'Unhandled Promise Rejection', { reason });
1680
+ }
1681
+ /**
1682
+ * Returns true if this error fingerprint is new (should be tracked).
1683
+ * Caps at MAX_UNIQUE_ERRORS to prevent queue flooding from error loops.
1684
+ */
1685
+ dedup(fingerprint) {
1686
+ if (this.seenErrors.has(fingerprint))
1687
+ return false;
1688
+ if (this.seenErrors.size >= MAX_UNIQUE_ERRORS)
1689
+ return false;
1690
+ this.seenErrors.add(fingerprint);
1691
+ return true;
1580
1692
  }
1581
1693
  }
1582
1694
 
@@ -3515,28 +3627,17 @@ class Tracker {
3515
3627
  }
3516
3628
  const prevId = previousId || this.visitorId;
3517
3629
  logger.info('Aliasing visitor:', { from: prevId, to: newId });
3518
- try {
3519
- const url = `${this.config.apiEndpoint}/api/public/track/alias`;
3520
- const response = await fetch(url, {
3521
- method: 'POST',
3522
- headers: { 'Content-Type': 'application/json' },
3523
- body: JSON.stringify({
3524
- workspaceId: this.workspaceId,
3525
- previousId: prevId,
3526
- newId,
3527
- }),
3528
- });
3529
- if (response.ok) {
3530
- logger.info('Alias successful');
3531
- return true;
3532
- }
3533
- logger.error('Alias failed:', response.status);
3534
- return false;
3535
- }
3536
- catch (error) {
3537
- logger.error('Alias request failed:', error);
3538
- return false;
3630
+ const result = await this.transport.sendPost('/api/public/track/alias', {
3631
+ workspaceId: this.workspaceId,
3632
+ previousId: prevId,
3633
+ newId,
3634
+ });
3635
+ if (result.success) {
3636
+ logger.info('Alias successful');
3637
+ return true;
3539
3638
  }
3639
+ logger.error('Alias failed:', result.error ?? result.status);
3640
+ return false;
3540
3641
  }
3541
3642
  /**
3542
3643
  * Track a screen view (for mobile-first PWAs and SPAs).
@@ -3899,13 +4000,24 @@ let globalInstance = null;
3899
4000
  * });
3900
4001
  */
3901
4002
  function clianta(workspaceId, config) {
3902
- // Return existing instance if same workspace
4003
+ // Return existing instance if same workspace and no config change
3903
4004
  if (globalInstance && globalInstance.getWorkspaceId() === workspaceId) {
4005
+ if (config && Object.keys(config).length > 0) {
4006
+ // Config was passed to an already-initialized instance — warn the developer
4007
+ // because the new config is ignored. They must call destroy() first to reconfigure.
4008
+ if (typeof console !== 'undefined') {
4009
+ console.warn('[Clianta] clianta() called with config on an already-initialized instance ' +
4010
+ 'for workspace "' + workspaceId + '". The new config was ignored. ' +
4011
+ 'Call tracker.destroy() first if you need to reconfigure.');
4012
+ }
4013
+ }
3904
4014
  return globalInstance;
3905
4015
  }
3906
- // Destroy existing instance if workspace changed
4016
+ // Destroy existing instance if workspace changed (fire-and-forget flush, then destroy)
3907
4017
  if (globalInstance) {
3908
- globalInstance.destroy();
4018
+ // Kick off async flush+destroy without blocking the new instance creation.
4019
+ // Using void to make the intentional fire-and-forget explicit.
4020
+ void globalInstance.destroy();
3909
4021
  }
3910
4022
  // Create new instance
3911
4023
  globalInstance = new Tracker(workspaceId, config);
@@ -3933,8 +4045,21 @@ if (typeof window !== 'undefined') {
3933
4045
  const projectId = script.getAttribute('data-project-id');
3934
4046
  if (!projectId)
3935
4047
  return;
3936
- const debug = script.hasAttribute('data-debug');
3937
- const instance = clianta(projectId, { debug });
4048
+ const initConfig = {
4049
+ debug: script.hasAttribute('data-debug'),
4050
+ };
4051
+ // Support additional config via script tag attributes:
4052
+ // data-api-endpoint="https://api.yourhost.com"
4053
+ // data-cookieless (boolean flag)
4054
+ // data-use-cookies (boolean flag)
4055
+ const apiEndpoint = script.getAttribute('data-api-endpoint');
4056
+ if (apiEndpoint)
4057
+ initConfig.apiEndpoint = apiEndpoint;
4058
+ if (script.hasAttribute('data-cookieless'))
4059
+ initConfig.cookielessMode = true;
4060
+ if (script.hasAttribute('data-use-cookies'))
4061
+ initConfig.useCookies = true;
4062
+ const instance = clianta(projectId, initConfig);
3938
4063
  // Expose the auto-initialized instance globally
3939
4064
  window.__clianta = instance;
3940
4065
  };