@clianta/sdk 1.4.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4432 @@
1
+ /*!
2
+ * Clianta SDK v1.5.1
3
+ * (c) 2026 Clianta
4
+ * Released under the MIT License.
5
+ */
6
+ 'use strict';
7
+
8
+ /**
9
+ * Clianta SDK - Configuration
10
+ * @see SDK_VERSION in core/config.ts
11
+ */
12
+ /** SDK Version */
13
+ const SDK_VERSION = '1.4.0';
14
+ /** Default API endpoint — reads from env or falls back to localhost */
15
+ const getDefaultApiEndpoint = () => {
16
+ // Build-time env var (works with Next.js, Vite, CRA, etc.)
17
+ if (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_CLIANTA_API_ENDPOINT) {
18
+ return process.env.NEXT_PUBLIC_CLIANTA_API_ENDPOINT;
19
+ }
20
+ if (typeof process !== 'undefined' && process.env?.VITE_CLIANTA_API_ENDPOINT) {
21
+ return process.env.VITE_CLIANTA_API_ENDPOINT;
22
+ }
23
+ if (typeof process !== 'undefined' && process.env?.REACT_APP_CLIANTA_API_ENDPOINT) {
24
+ return process.env.REACT_APP_CLIANTA_API_ENDPOINT;
25
+ }
26
+ if (typeof process !== 'undefined' && process.env?.CLIANTA_API_ENDPOINT) {
27
+ return process.env.CLIANTA_API_ENDPOINT;
28
+ }
29
+ return 'http://localhost:5000';
30
+ };
31
+ /** Core plugins enabled by default */
32
+ const DEFAULT_PLUGINS = [
33
+ 'pageView',
34
+ 'forms',
35
+ 'scroll',
36
+ 'clicks',
37
+ 'engagement',
38
+ 'downloads',
39
+ 'exitIntent',
40
+ ];
41
+ /** Default configuration values */
42
+ const DEFAULT_CONFIG = {
43
+ projectId: '',
44
+ apiEndpoint: getDefaultApiEndpoint(),
45
+ authToken: '',
46
+ apiKey: '',
47
+ debug: false,
48
+ autoPageView: true,
49
+ plugins: DEFAULT_PLUGINS,
50
+ sessionTimeout: 30 * 60 * 1000, // 30 minutes
51
+ batchSize: 10,
52
+ flushInterval: 5000, // 5 seconds
53
+ consent: {
54
+ defaultConsent: { analytics: true, marketing: false, personalization: false },
55
+ waitForConsent: false,
56
+ storageKey: 'mb_consent',
57
+ anonymousMode: false,
58
+ },
59
+ cookieDomain: '',
60
+ useCookies: false,
61
+ cookielessMode: false,
62
+ persistMode: 'session',
63
+ };
64
+ /** Storage keys */
65
+ const STORAGE_KEYS = {
66
+ VISITOR_ID: 'mb_vid',
67
+ SESSION_ID: 'mb_sid',
68
+ SESSION_TIMESTAMP: 'mb_st',
69
+ CONSENT: 'mb_consent',
70
+ EVENT_QUEUE: 'mb_queue',
71
+ };
72
+ /** Scroll depth milestones to track */
73
+ const SCROLL_MILESTONES = [25, 50, 75, 100];
74
+ /** File extensions to track as downloads */
75
+ const DOWNLOAD_EXTENSIONS = [
76
+ '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',
77
+ '.zip', '.rar', '.tar', '.gz', '.7z',
78
+ '.csv', '.txt', '.json', '.xml',
79
+ '.mp3', '.mp4', '.wav', '.avi', '.mov',
80
+ ];
81
+ /**
82
+ * Merge user config with defaults
83
+ */
84
+ function mergeConfig(userConfig = {}) {
85
+ return {
86
+ ...DEFAULT_CONFIG,
87
+ ...userConfig,
88
+ consent: {
89
+ ...DEFAULT_CONFIG.consent,
90
+ ...userConfig.consent,
91
+ },
92
+ };
93
+ }
94
+
95
+ /**
96
+ * Clianta SDK - Debug Logger
97
+ * @see SDK_VERSION in core/config.ts
98
+ */
99
+ const LOG_PREFIX = '[Clianta]';
100
+ const LOG_STYLES = {
101
+ debug: 'color: #6b7280; font-weight: normal;',
102
+ info: 'color: #3b82f6; font-weight: normal;',
103
+ warn: 'color: #f59e0b; font-weight: bold;',
104
+ error: 'color: #ef4444; font-weight: bold;',
105
+ };
106
+ const LOG_LEVELS = {
107
+ debug: 0,
108
+ info: 1,
109
+ warn: 2,
110
+ error: 3,
111
+ };
112
+ /**
113
+ * Create a logger instance
114
+ */
115
+ function createLogger(enabled = false) {
116
+ let currentLevel = 'debug';
117
+ let isEnabled = enabled;
118
+ const shouldLog = (level) => {
119
+ if (!isEnabled)
120
+ return false;
121
+ return LOG_LEVELS[level] >= LOG_LEVELS[currentLevel];
122
+ };
123
+ const formatArgs = (level, args) => {
124
+ if (typeof console !== 'undefined' && typeof window !== 'undefined') {
125
+ // Browser with styled console
126
+ return [`%c${LOG_PREFIX}`, LOG_STYLES[level], ...args];
127
+ }
128
+ // Node.js or basic console
129
+ return [`${LOG_PREFIX} [${level.toUpperCase()}]`, ...args];
130
+ };
131
+ return {
132
+ get enabled() {
133
+ return isEnabled;
134
+ },
135
+ set enabled(value) {
136
+ isEnabled = value;
137
+ },
138
+ debug(...args) {
139
+ if (shouldLog('debug') && typeof console !== 'undefined') {
140
+ console.log(...formatArgs('debug', args));
141
+ }
142
+ },
143
+ info(...args) {
144
+ if (shouldLog('info') && typeof console !== 'undefined') {
145
+ console.info(...formatArgs('info', args));
146
+ }
147
+ },
148
+ warn(...args) {
149
+ if (shouldLog('warn') && typeof console !== 'undefined') {
150
+ console.warn(...formatArgs('warn', args));
151
+ }
152
+ },
153
+ error(...args) {
154
+ if (shouldLog('error') && typeof console !== 'undefined') {
155
+ console.error(...formatArgs('error', args));
156
+ }
157
+ },
158
+ setLevel(level) {
159
+ currentLevel = level;
160
+ },
161
+ };
162
+ }
163
+ /** Global logger instance */
164
+ const logger = createLogger(false);
165
+
166
+ /**
167
+ * Clianta SDK - Transport Layer
168
+ * Handles sending events to the backend with retry logic
169
+ * @see SDK_VERSION in core/config.ts
170
+ */
171
+ const DEFAULT_TIMEOUT = 10000; // 10 seconds
172
+ const DEFAULT_MAX_RETRIES = 3;
173
+ const DEFAULT_RETRY_DELAY = 1000; // 1 second
174
+ /**
175
+ * Transport class for sending data to the backend
176
+ */
177
+ class Transport {
178
+ constructor(config) {
179
+ this.config = {
180
+ apiEndpoint: config.apiEndpoint,
181
+ maxRetries: config.maxRetries ?? DEFAULT_MAX_RETRIES,
182
+ retryDelay: config.retryDelay ?? DEFAULT_RETRY_DELAY,
183
+ timeout: config.timeout ?? DEFAULT_TIMEOUT,
184
+ };
185
+ }
186
+ /**
187
+ * Send events to the tracking endpoint
188
+ */
189
+ async sendEvents(events) {
190
+ const url = `${this.config.apiEndpoint}/api/public/track/event`;
191
+ const payload = JSON.stringify({ events });
192
+ return this.send(url, payload);
193
+ }
194
+ /**
195
+ * Send identify request.
196
+ * Returns contactId from the server response so the Tracker can store it.
197
+ */
198
+ async sendIdentify(data) {
199
+ const url = `${this.config.apiEndpoint}/api/public/track/identify`;
200
+ try {
201
+ const response = await this.fetchWithTimeout(url, {
202
+ method: 'POST',
203
+ headers: { 'Content-Type': 'application/json' },
204
+ body: JSON.stringify(data),
205
+ keepalive: true,
206
+ });
207
+ const body = await response.json().catch(() => ({}));
208
+ if (response.ok) {
209
+ logger.debug('Identify successful, contactId:', body.contactId);
210
+ return {
211
+ success: true,
212
+ status: response.status,
213
+ contactId: body.contactId ?? undefined,
214
+ };
215
+ }
216
+ if (response.status >= 500) {
217
+ logger.warn(`Identify server error (${response.status})`);
218
+ }
219
+ else {
220
+ logger.error(`Identify failed with status ${response.status}:`, body.message);
221
+ }
222
+ return { success: false, status: response.status };
223
+ }
224
+ catch (error) {
225
+ logger.error('Identify request failed:', error);
226
+ return { success: false, error: error };
227
+ }
228
+ }
229
+ /**
230
+ * Send events synchronously (for page unload)
231
+ * Uses navigator.sendBeacon for reliability
232
+ */
233
+ sendBeacon(events) {
234
+ if (typeof navigator === 'undefined' || !navigator.sendBeacon) {
235
+ logger.warn('sendBeacon not available, events may be lost');
236
+ return false;
237
+ }
238
+ const url = `${this.config.apiEndpoint}/api/public/track/event`;
239
+ const payload = JSON.stringify({ events });
240
+ const blob = new Blob([payload], { type: 'application/json' });
241
+ try {
242
+ const success = navigator.sendBeacon(url, blob);
243
+ if (success) {
244
+ logger.debug(`Beacon sent ${events.length} events`);
245
+ }
246
+ else {
247
+ logger.warn('sendBeacon returned false');
248
+ }
249
+ return success;
250
+ }
251
+ catch (error) {
252
+ logger.error('sendBeacon error:', error);
253
+ return false;
254
+ }
255
+ }
256
+ /**
257
+ * Fetch data from the tracking API (GET request)
258
+ * Used for read-back APIs (visitor profile, activity, etc.)
259
+ */
260
+ async fetchData(path, params) {
261
+ const url = new URL(`${this.config.apiEndpoint}${path}`);
262
+ if (params) {
263
+ Object.entries(params).forEach(([key, value]) => {
264
+ if (value !== undefined && value !== null) {
265
+ url.searchParams.set(key, value);
266
+ }
267
+ });
268
+ }
269
+ try {
270
+ const response = await this.fetchWithTimeout(url.toString(), {
271
+ method: 'GET',
272
+ headers: {
273
+ 'Accept': 'application/json',
274
+ },
275
+ });
276
+ if (response.ok) {
277
+ const body = await response.json();
278
+ logger.debug('Fetch successful:', path);
279
+ return { success: true, data: body.data ?? body, status: response.status };
280
+ }
281
+ logger.error(`Fetch failed with status ${response.status}`);
282
+ return { success: false, status: response.status };
283
+ }
284
+ catch (error) {
285
+ logger.error('Fetch request failed:', error);
286
+ return { success: false, error: error };
287
+ }
288
+ }
289
+ /**
290
+ * Internal send with retry logic
291
+ */
292
+ async send(url, payload, attempt = 1) {
293
+ try {
294
+ const response = await this.fetchWithTimeout(url, {
295
+ method: 'POST',
296
+ headers: {
297
+ 'Content-Type': 'application/json',
298
+ },
299
+ body: payload,
300
+ keepalive: true,
301
+ });
302
+ if (response.ok) {
303
+ logger.debug('Request successful:', url);
304
+ return { success: true, status: response.status };
305
+ }
306
+ // Server error - may retry
307
+ if (response.status >= 500 && attempt < this.config.maxRetries) {
308
+ logger.warn(`Server error (${response.status}), retrying...`);
309
+ await this.delay(this.config.retryDelay * attempt);
310
+ return this.send(url, payload, attempt + 1);
311
+ }
312
+ // Client error - don't retry
313
+ logger.error(`Request failed with status ${response.status}`);
314
+ return { success: false, status: response.status };
315
+ }
316
+ catch (error) {
317
+ // Network error - retry if possible
318
+ if (attempt < this.config.maxRetries) {
319
+ logger.warn(`Network error, retrying (${attempt}/${this.config.maxRetries})...`);
320
+ await this.delay(this.config.retryDelay * attempt);
321
+ return this.send(url, payload, attempt + 1);
322
+ }
323
+ logger.error('Request failed after retries:', error);
324
+ return { success: false, error: error };
325
+ }
326
+ }
327
+ /**
328
+ * Fetch with timeout
329
+ */
330
+ async fetchWithTimeout(url, options) {
331
+ const controller = new AbortController();
332
+ const timeout = setTimeout(() => controller.abort(), this.config.timeout);
333
+ try {
334
+ const response = await fetch(url, {
335
+ ...options,
336
+ signal: controller.signal,
337
+ });
338
+ return response;
339
+ }
340
+ finally {
341
+ clearTimeout(timeout);
342
+ }
343
+ }
344
+ /**
345
+ * Delay helper
346
+ */
347
+ delay(ms) {
348
+ return new Promise((resolve) => setTimeout(resolve, ms));
349
+ }
350
+ }
351
+
352
+ /**
353
+ * Clianta SDK - Utility Functions
354
+ * @see SDK_VERSION in core/config.ts
355
+ */
356
+ // ============================================
357
+ // UUID GENERATION
358
+ // ============================================
359
+ /**
360
+ * Generate a UUID v4
361
+ */
362
+ function generateUUID() {
363
+ // Use crypto.randomUUID if available (modern browsers)
364
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
365
+ return crypto.randomUUID();
366
+ }
367
+ // Fallback to manual generation
368
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
369
+ const r = (Math.random() * 16) | 0;
370
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
371
+ return v.toString(16);
372
+ });
373
+ }
374
+ // ============================================
375
+ // STORAGE UTILITIES
376
+ // ============================================
377
+ /**
378
+ * Safely get from localStorage
379
+ */
380
+ function getLocalStorage(key) {
381
+ try {
382
+ if (typeof localStorage !== 'undefined') {
383
+ return localStorage.getItem(key);
384
+ }
385
+ }
386
+ catch {
387
+ // localStorage not available or blocked
388
+ }
389
+ return null;
390
+ }
391
+ /**
392
+ * Safely set to localStorage
393
+ */
394
+ function setLocalStorage(key, value) {
395
+ try {
396
+ if (typeof localStorage !== 'undefined') {
397
+ localStorage.setItem(key, value);
398
+ return true;
399
+ }
400
+ }
401
+ catch {
402
+ // localStorage not available or blocked
403
+ }
404
+ return false;
405
+ }
406
+ /**
407
+ * Safely get from sessionStorage
408
+ */
409
+ function getSessionStorage(key) {
410
+ try {
411
+ if (typeof sessionStorage !== 'undefined') {
412
+ return sessionStorage.getItem(key);
413
+ }
414
+ }
415
+ catch {
416
+ // sessionStorage not available or blocked
417
+ }
418
+ return null;
419
+ }
420
+ /**
421
+ * Safely set to sessionStorage
422
+ */
423
+ function setSessionStorage(key, value) {
424
+ try {
425
+ if (typeof sessionStorage !== 'undefined') {
426
+ sessionStorage.setItem(key, value);
427
+ return true;
428
+ }
429
+ }
430
+ catch {
431
+ // sessionStorage not available or blocked
432
+ }
433
+ return false;
434
+ }
435
+ /**
436
+ * Get or set a cookie
437
+ */
438
+ function cookie(name, value, days) {
439
+ if (typeof document === 'undefined')
440
+ return null;
441
+ // Get cookie
442
+ if (value === undefined) {
443
+ const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
444
+ return match ? match[2] : null;
445
+ }
446
+ // Set cookie
447
+ let expires = '';
448
+ if (days) {
449
+ const date = new Date();
450
+ date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
451
+ expires = '; expires=' + date.toUTCString();
452
+ }
453
+ // Add Secure flag on HTTPS to prevent cookie leakage over plaintext
454
+ const secure = typeof location !== 'undefined' && location.protocol === 'https:' ? '; Secure' : '';
455
+ document.cookie = name + '=' + value + expires + '; path=/; SameSite=Lax' + secure;
456
+ return value;
457
+ }
458
+ // ============================================
459
+ // VISITOR & SESSION MANAGEMENT
460
+ // ============================================
461
+ /**
462
+ * Get or create a persistent visitor ID
463
+ */
464
+ function getOrCreateVisitorId(useCookies = false) {
465
+ const key = STORAGE_KEYS.VISITOR_ID;
466
+ // Try to get existing ID
467
+ let visitorId = null;
468
+ if (useCookies) {
469
+ visitorId = cookie(key);
470
+ }
471
+ else {
472
+ visitorId = getLocalStorage(key);
473
+ }
474
+ // Create new ID if not found
475
+ if (!visitorId) {
476
+ visitorId = generateUUID();
477
+ if (useCookies) {
478
+ cookie(key, visitorId, 365); // 1 year
479
+ }
480
+ else {
481
+ setLocalStorage(key, visitorId);
482
+ }
483
+ }
484
+ return visitorId;
485
+ }
486
+ /**
487
+ * Get or create a session ID (expires after timeout)
488
+ */
489
+ function getOrCreateSessionId(timeout) {
490
+ const sidKey = STORAGE_KEYS.SESSION_ID;
491
+ const tsKey = STORAGE_KEYS.SESSION_TIMESTAMP;
492
+ let sessionId = getSessionStorage(sidKey);
493
+ const lastActivity = parseInt(getSessionStorage(tsKey) || '0', 10);
494
+ const now = Date.now();
495
+ // Check if session expired
496
+ if (!sessionId || now - lastActivity > timeout) {
497
+ sessionId = generateUUID();
498
+ setSessionStorage(sidKey, sessionId);
499
+ }
500
+ // Update last activity
501
+ setSessionStorage(tsKey, now.toString());
502
+ return sessionId;
503
+ }
504
+ /**
505
+ * Reset visitor and session IDs
506
+ */
507
+ function resetIds(useCookies = false) {
508
+ const visitorKey = STORAGE_KEYS.VISITOR_ID;
509
+ if (useCookies) {
510
+ cookie(visitorKey, '', -1); // Delete cookie
511
+ }
512
+ else {
513
+ try {
514
+ localStorage.removeItem(visitorKey);
515
+ }
516
+ catch {
517
+ // Ignore
518
+ }
519
+ }
520
+ try {
521
+ sessionStorage.removeItem(STORAGE_KEYS.SESSION_ID);
522
+ sessionStorage.removeItem(STORAGE_KEYS.SESSION_TIMESTAMP);
523
+ }
524
+ catch {
525
+ // Ignore
526
+ }
527
+ }
528
+ // ============================================
529
+ // URL UTILITIES
530
+ // ============================================
531
+ /**
532
+ * Extract UTM parameters from URL
533
+ */
534
+ function getUTMParams() {
535
+ if (typeof window === 'undefined')
536
+ return {};
537
+ try {
538
+ const params = new URLSearchParams(window.location.search);
539
+ return {
540
+ utmSource: params.get('utm_source') || undefined,
541
+ utmMedium: params.get('utm_medium') || undefined,
542
+ utmCampaign: params.get('utm_campaign') || undefined,
543
+ utmTerm: params.get('utm_term') || undefined,
544
+ utmContent: params.get('utm_content') || undefined,
545
+ };
546
+ }
547
+ catch {
548
+ return {};
549
+ }
550
+ }
551
+ /**
552
+ * Check if URL is a download link
553
+ */
554
+ function isDownloadUrl(url) {
555
+ const lowerUrl = url.toLowerCase();
556
+ return DOWNLOAD_EXTENSIONS.some((ext) => lowerUrl.includes(ext));
557
+ }
558
+ /**
559
+ * Extract filename from URL
560
+ */
561
+ function getFilenameFromUrl(url) {
562
+ try {
563
+ return url.split('/').pop()?.split('?')[0] || 'unknown';
564
+ }
565
+ catch {
566
+ return 'unknown';
567
+ }
568
+ }
569
+ /**
570
+ * Extract file extension from URL
571
+ */
572
+ function getFileExtension(url) {
573
+ const filename = getFilenameFromUrl(url);
574
+ const parts = filename.split('.');
575
+ return parts.length > 1 ? parts.pop() || 'unknown' : 'unknown';
576
+ }
577
+ // ============================================
578
+ // DOM UTILITIES
579
+ // ============================================
580
+ /**
581
+ * Get text content from element (truncated)
582
+ */
583
+ function getElementText(element, maxLength = 100) {
584
+ const text = element.innerText ||
585
+ element.textContent ||
586
+ element.value ||
587
+ '';
588
+ return text.trim().substring(0, maxLength);
589
+ }
590
+ /**
591
+ * Get element identification info
592
+ */
593
+ function getElementInfo(element) {
594
+ return {
595
+ tag: element.tagName?.toLowerCase() || 'unknown',
596
+ id: element.id || '',
597
+ className: element.className || '',
598
+ text: getElementText(element, 50),
599
+ };
600
+ }
601
+ /**
602
+ * Check if element is a trackable click target
603
+ */
604
+ function isTrackableClickElement(element) {
605
+ const trackableTags = ['BUTTON', 'A', 'INPUT'];
606
+ return (trackableTags.includes(element.tagName) ||
607
+ element.hasAttribute('data-track-click') ||
608
+ element.classList.contains('track-click'));
609
+ }
610
+ /**
611
+ * Check if device is mobile
612
+ */
613
+ function isMobile() {
614
+ if (typeof navigator === 'undefined')
615
+ return false;
616
+ return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
617
+ }
618
+ // ============================================
619
+ // VALIDATION UTILITIES
620
+ // ============================================
621
+ /**
622
+ * Validate email format
623
+ */
624
+ function isValidEmail(email) {
625
+ if (typeof email !== 'string' || !email)
626
+ return false;
627
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
628
+ }
629
+ // ============================================
630
+ // DEVICE INFO
631
+ // ============================================
632
+ /**
633
+ * Get current device information
634
+ */
635
+ function getDeviceInfo() {
636
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
637
+ return {
638
+ userAgent: 'unknown',
639
+ screen: 'unknown',
640
+ language: 'unknown',
641
+ timezone: 'unknown',
642
+ };
643
+ }
644
+ return {
645
+ userAgent: navigator.userAgent,
646
+ screen: `${screen.width}x${screen.height}`,
647
+ language: navigator.language,
648
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'unknown',
649
+ };
650
+ }
651
+
652
+ /**
653
+ * Clianta SDK - Event Queue
654
+ * Handles batching and flushing of events
655
+ * @see SDK_VERSION in core/config.ts
656
+ */
657
+ const MAX_QUEUE_SIZE = 1000;
658
+ /** Rate limit: max events per window */
659
+ const RATE_LIMIT_MAX_EVENTS = 100;
660
+ /** Rate limit window in ms (1 minute) */
661
+ const RATE_LIMIT_WINDOW_MS = 60000;
662
+ /**
663
+ * Event queue with batching, persistence, rate limiting, and auto-flush
664
+ */
665
+ class EventQueue {
666
+ constructor(transport, config = {}) {
667
+ this.queue = [];
668
+ this.flushTimer = null;
669
+ this.isFlushing = false;
670
+ /** Rate limiting: timestamps of recent events */
671
+ this.eventTimestamps = [];
672
+ /** Unload handler references for cleanup */
673
+ this.boundBeforeUnload = null;
674
+ this.boundVisibilityChange = null;
675
+ this.boundPageHide = null;
676
+ this.transport = transport;
677
+ this.config = {
678
+ batchSize: config.batchSize ?? 10,
679
+ flushInterval: config.flushInterval ?? 5000,
680
+ maxQueueSize: config.maxQueueSize ?? MAX_QUEUE_SIZE,
681
+ storageKey: config.storageKey ?? STORAGE_KEYS.EVENT_QUEUE,
682
+ };
683
+ this.persistMode = config.persistMode || 'session';
684
+ // Restore persisted queue
685
+ this.restoreQueue();
686
+ // Start auto-flush timer
687
+ this.startFlushTimer();
688
+ // Setup unload handlers
689
+ this.setupUnloadHandlers();
690
+ }
691
+ /**
692
+ * Add an event to the queue
693
+ */
694
+ push(event) {
695
+ // Rate limiting check
696
+ if (!this.checkRateLimit()) {
697
+ logger.warn('Rate limit exceeded, event dropped:', event.eventName);
698
+ return;
699
+ }
700
+ // Don't exceed max queue size
701
+ if (this.queue.length >= this.config.maxQueueSize) {
702
+ logger.warn('Queue full, dropping oldest event');
703
+ this.queue.shift();
704
+ }
705
+ this.queue.push(event);
706
+ logger.debug('Event queued:', event.eventName, `(${this.queue.length} in queue)`);
707
+ // Flush if batch size reached
708
+ if (this.queue.length >= this.config.batchSize) {
709
+ this.flush();
710
+ }
711
+ }
712
+ /**
713
+ * Check and enforce rate limiting
714
+ * @returns true if event is allowed, false if rate limited
715
+ */
716
+ checkRateLimit() {
717
+ const now = Date.now();
718
+ // Remove timestamps outside the window
719
+ this.eventTimestamps = this.eventTimestamps.filter(ts => now - ts < RATE_LIMIT_WINDOW_MS);
720
+ // Check if under limit
721
+ if (this.eventTimestamps.length >= RATE_LIMIT_MAX_EVENTS) {
722
+ return false;
723
+ }
724
+ // Record this event
725
+ this.eventTimestamps.push(now);
726
+ return true;
727
+ }
728
+ /**
729
+ * Flush the queue (send all events)
730
+ */
731
+ async flush() {
732
+ if (this.isFlushing || this.queue.length === 0) {
733
+ return;
734
+ }
735
+ this.isFlushing = true;
736
+ // Atomically take snapshot of current queue length to avoid race condition
737
+ const count = this.queue.length;
738
+ const events = this.queue.splice(0, count);
739
+ try {
740
+ logger.debug(`Flushing ${events.length} events`);
741
+ // Clear persisted queue
742
+ this.persistQueue([]);
743
+ // Send to backend
744
+ const result = await this.transport.sendEvents(events);
745
+ if (!result.success) {
746
+ // Re-queue events on failure (at the front)
747
+ logger.warn('Flush failed, re-queuing events');
748
+ this.queue.unshift(...events);
749
+ this.persistQueue(this.queue);
750
+ }
751
+ else {
752
+ logger.debug('Flush successful');
753
+ }
754
+ }
755
+ catch (error) {
756
+ logger.error('Flush error:', error);
757
+ }
758
+ finally {
759
+ this.isFlushing = false;
760
+ }
761
+ }
762
+ /**
763
+ * Flush synchronously using sendBeacon (for page unload)
764
+ */
765
+ flushSync() {
766
+ if (this.queue.length === 0)
767
+ return;
768
+ const events = this.queue.splice(0, this.queue.length);
769
+ logger.debug(`Sync flushing ${events.length} events via beacon`);
770
+ const success = this.transport.sendBeacon(events);
771
+ if (!success) {
772
+ // Re-queue and persist for next page load
773
+ this.queue.unshift(...events);
774
+ this.persistQueue(this.queue);
775
+ }
776
+ }
777
+ /**
778
+ * Get current queue length
779
+ */
780
+ get length() {
781
+ return this.queue.length;
782
+ }
783
+ /**
784
+ * Clear the queue
785
+ */
786
+ clear() {
787
+ this.queue = [];
788
+ this.persistQueue([]);
789
+ // Also clear localStorage if used
790
+ if (this.persistMode === 'local' && typeof localStorage !== 'undefined') {
791
+ try {
792
+ localStorage.removeItem(this.config.storageKey);
793
+ }
794
+ catch { /* ignore */ }
795
+ }
796
+ }
797
+ /**
798
+ * Stop the flush timer and cleanup handlers
799
+ */
800
+ destroy() {
801
+ if (this.flushTimer) {
802
+ clearInterval(this.flushTimer);
803
+ this.flushTimer = null;
804
+ }
805
+ // Remove unload handlers
806
+ if (typeof window !== 'undefined') {
807
+ if (this.boundBeforeUnload) {
808
+ window.removeEventListener('beforeunload', this.boundBeforeUnload);
809
+ }
810
+ if (this.boundVisibilityChange) {
811
+ window.removeEventListener('visibilitychange', this.boundVisibilityChange);
812
+ }
813
+ if (this.boundPageHide) {
814
+ window.removeEventListener('pagehide', this.boundPageHide);
815
+ }
816
+ }
817
+ }
818
+ /**
819
+ * Start auto-flush timer
820
+ */
821
+ startFlushTimer() {
822
+ if (this.flushTimer) {
823
+ clearInterval(this.flushTimer);
824
+ }
825
+ this.flushTimer = setInterval(() => {
826
+ this.flush();
827
+ }, this.config.flushInterval);
828
+ }
829
+ /**
830
+ * Setup page unload handlers
831
+ */
832
+ setupUnloadHandlers() {
833
+ if (typeof window === 'undefined')
834
+ return;
835
+ // Flush on page unload
836
+ this.boundBeforeUnload = () => this.flushSync();
837
+ window.addEventListener('beforeunload', this.boundBeforeUnload);
838
+ // Flush when page becomes hidden
839
+ this.boundVisibilityChange = () => {
840
+ if (document.visibilityState === 'hidden') {
841
+ this.flushSync();
842
+ }
843
+ };
844
+ window.addEventListener('visibilitychange', this.boundVisibilityChange);
845
+ // Flush on page hide (iOS Safari)
846
+ this.boundPageHide = () => this.flushSync();
847
+ window.addEventListener('pagehide', this.boundPageHide);
848
+ }
849
+ /**
850
+ * Persist queue to storage based on persistMode
851
+ */
852
+ persistQueue(events) {
853
+ if (this.persistMode === 'none')
854
+ return;
855
+ try {
856
+ const serialized = JSON.stringify(events);
857
+ if (this.persistMode === 'local' && typeof localStorage !== 'undefined') {
858
+ try {
859
+ localStorage.setItem(this.config.storageKey, serialized);
860
+ }
861
+ catch {
862
+ // localStorage quota exceeded — fallback to sessionStorage
863
+ setSessionStorage(this.config.storageKey, serialized);
864
+ }
865
+ }
866
+ else {
867
+ setSessionStorage(this.config.storageKey, serialized);
868
+ }
869
+ }
870
+ catch {
871
+ // Ignore storage errors
872
+ }
873
+ }
874
+ /**
875
+ * Restore queue from storage
876
+ */
877
+ restoreQueue() {
878
+ try {
879
+ let stored = null;
880
+ // Check localStorage first (cross-session persistence)
881
+ if (this.persistMode === 'local' && typeof localStorage !== 'undefined') {
882
+ stored = localStorage.getItem(this.config.storageKey);
883
+ }
884
+ // Fall back to sessionStorage
885
+ if (!stored) {
886
+ stored = getSessionStorage(this.config.storageKey);
887
+ }
888
+ if (stored) {
889
+ const events = JSON.parse(stored);
890
+ if (Array.isArray(events) && events.length > 0) {
891
+ this.queue = events;
892
+ logger.debug(`Restored ${events.length} events from storage`);
893
+ }
894
+ }
895
+ }
896
+ catch {
897
+ // Ignore parse errors
898
+ }
899
+ }
900
+ }
901
+
902
+ /**
903
+ * Clianta SDK - Plugin Base
904
+ * @see SDK_VERSION in core/config.ts
905
+ */
906
+ /**
907
+ * Base class for plugins
908
+ */
909
+ class BasePlugin {
910
+ constructor() {
911
+ this.tracker = null;
912
+ }
913
+ init(tracker) {
914
+ this.tracker = tracker;
915
+ }
916
+ destroy() {
917
+ this.tracker = null;
918
+ }
919
+ track(eventType, eventName, properties) {
920
+ if (this.tracker) {
921
+ this.tracker.track(eventType, eventName, properties);
922
+ }
923
+ }
924
+ }
925
+
926
+ /**
927
+ * Clianta SDK - Page View Plugin
928
+ * @see SDK_VERSION in core/config.ts
929
+ */
930
+ /**
931
+ * Page View Plugin - Tracks page views
932
+ */
933
+ class PageViewPlugin extends BasePlugin {
934
+ constructor() {
935
+ super(...arguments);
936
+ this.name = 'pageView';
937
+ this.originalPushState = null;
938
+ this.originalReplaceState = null;
939
+ this.popstateHandler = null;
940
+ }
941
+ init(tracker) {
942
+ super.init(tracker);
943
+ // Track initial page view
944
+ this.trackPageView();
945
+ // Track SPA navigation (History API)
946
+ if (typeof window !== 'undefined') {
947
+ // Store originals for cleanup
948
+ this.originalPushState = history.pushState;
949
+ this.originalReplaceState = history.replaceState;
950
+ // Intercept pushState and replaceState
951
+ const self = this;
952
+ history.pushState = function (...args) {
953
+ self.originalPushState.apply(history, args);
954
+ self.trackPageView();
955
+ // Notify other plugins (e.g. ScrollPlugin) about navigation
956
+ window.dispatchEvent(new Event('clianta:navigation'));
957
+ };
958
+ history.replaceState = function (...args) {
959
+ self.originalReplaceState.apply(history, args);
960
+ self.trackPageView();
961
+ window.dispatchEvent(new Event('clianta:navigation'));
962
+ };
963
+ // Handle back/forward navigation
964
+ this.popstateHandler = () => this.trackPageView();
965
+ window.addEventListener('popstate', this.popstateHandler);
966
+ }
967
+ }
968
+ destroy() {
969
+ // Restore original history methods
970
+ if (this.originalPushState) {
971
+ history.pushState = this.originalPushState;
972
+ this.originalPushState = null;
973
+ }
974
+ if (this.originalReplaceState) {
975
+ history.replaceState = this.originalReplaceState;
976
+ this.originalReplaceState = null;
977
+ }
978
+ // Remove popstate listener
979
+ if (this.popstateHandler && typeof window !== 'undefined') {
980
+ window.removeEventListener('popstate', this.popstateHandler);
981
+ this.popstateHandler = null;
982
+ }
983
+ super.destroy();
984
+ }
985
+ trackPageView() {
986
+ if (typeof window === 'undefined' || typeof document === 'undefined')
987
+ return;
988
+ this.track('page_view', 'Page Viewed', {
989
+ title: document.title,
990
+ path: window.location.pathname,
991
+ search: window.location.search,
992
+ hash: window.location.hash,
993
+ referrer: document.referrer || 'direct',
994
+ viewport: `${window.innerWidth}x${window.innerHeight}`,
995
+ });
996
+ }
997
+ }
998
+
999
+ /**
1000
+ * Clianta SDK - Scroll Depth Plugin
1001
+ * @see SDK_VERSION in core/config.ts
1002
+ */
1003
+ /**
1004
+ * Scroll Depth Plugin - Tracks scroll milestones
1005
+ */
1006
+ class ScrollPlugin extends BasePlugin {
1007
+ constructor() {
1008
+ super(...arguments);
1009
+ this.name = 'scroll';
1010
+ this.milestonesReached = new Set();
1011
+ this.maxScrollDepth = 0;
1012
+ this.pageLoadTime = 0;
1013
+ this.scrollTimeout = null;
1014
+ this.boundHandler = null;
1015
+ /** SPA navigation — listen for PageViewPlugin's custom event instead of patching history */
1016
+ this.navigationHandler = null;
1017
+ this.popstateHandler = null;
1018
+ }
1019
+ init(tracker) {
1020
+ super.init(tracker);
1021
+ this.pageLoadTime = Date.now();
1022
+ if (typeof window !== 'undefined') {
1023
+ this.boundHandler = this.handleScroll.bind(this);
1024
+ window.addEventListener('scroll', this.boundHandler, { passive: true });
1025
+ // Listen for navigation events dispatched by PageViewPlugin
1026
+ // instead of independently monkey-patching history.pushState
1027
+ this.navigationHandler = () => this.resetForNavigation();
1028
+ window.addEventListener('clianta:navigation', this.navigationHandler);
1029
+ // Handle back/forward navigation
1030
+ this.popstateHandler = () => this.resetForNavigation();
1031
+ window.addEventListener('popstate', this.popstateHandler);
1032
+ }
1033
+ }
1034
+ destroy() {
1035
+ if (this.boundHandler && typeof window !== 'undefined') {
1036
+ window.removeEventListener('scroll', this.boundHandler);
1037
+ }
1038
+ if (this.scrollTimeout) {
1039
+ clearTimeout(this.scrollTimeout);
1040
+ }
1041
+ if (this.navigationHandler && typeof window !== 'undefined') {
1042
+ window.removeEventListener('clianta:navigation', this.navigationHandler);
1043
+ this.navigationHandler = null;
1044
+ }
1045
+ if (this.popstateHandler && typeof window !== 'undefined') {
1046
+ window.removeEventListener('popstate', this.popstateHandler);
1047
+ this.popstateHandler = null;
1048
+ }
1049
+ super.destroy();
1050
+ }
1051
+ /**
1052
+ * Reset scroll tracking for SPA navigation
1053
+ */
1054
+ resetForNavigation() {
1055
+ this.milestonesReached.clear();
1056
+ this.maxScrollDepth = 0;
1057
+ this.pageLoadTime = Date.now();
1058
+ }
1059
+ handleScroll() {
1060
+ // Debounce scroll tracking
1061
+ if (this.scrollTimeout) {
1062
+ clearTimeout(this.scrollTimeout);
1063
+ }
1064
+ this.scrollTimeout = setTimeout(() => this.trackScrollDepth(), 150);
1065
+ }
1066
+ trackScrollDepth() {
1067
+ if (typeof window === 'undefined' || typeof document === 'undefined')
1068
+ return;
1069
+ const windowHeight = window.innerHeight;
1070
+ const documentHeight = document.documentElement.scrollHeight;
1071
+ const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
1072
+ const scrollableHeight = documentHeight - windowHeight;
1073
+ // Guard against divide-by-zero on short pages
1074
+ if (scrollableHeight <= 0)
1075
+ return;
1076
+ const scrollPercent = Math.floor((scrollTop / scrollableHeight) * 100);
1077
+ // Clamp to valid range
1078
+ const clampedPercent = Math.max(0, Math.min(100, scrollPercent));
1079
+ // Update max scroll depth
1080
+ if (clampedPercent > this.maxScrollDepth) {
1081
+ this.maxScrollDepth = clampedPercent;
1082
+ }
1083
+ // Track milestones
1084
+ for (const milestone of SCROLL_MILESTONES) {
1085
+ if (clampedPercent >= milestone && !this.milestonesReached.has(milestone)) {
1086
+ this.milestonesReached.add(milestone);
1087
+ this.track('scroll_depth', `Scrolled ${milestone}%`, {
1088
+ depth: milestone,
1089
+ maxDepth: this.maxScrollDepth,
1090
+ timeToReach: Date.now() - this.pageLoadTime,
1091
+ });
1092
+ }
1093
+ }
1094
+ }
1095
+ }
1096
+
1097
+ /**
1098
+ * Clianta SDK - Form Tracking Plugin
1099
+ * @see SDK_VERSION in core/config.ts
1100
+ */
1101
+ /**
1102
+ * Form Tracking Plugin - Auto-tracks form views, interactions, and submissions
1103
+ */
1104
+ class FormsPlugin extends BasePlugin {
1105
+ constructor() {
1106
+ super(...arguments);
1107
+ this.name = 'forms';
1108
+ this.trackedForms = new WeakSet();
1109
+ this.formInteractions = new Set();
1110
+ this.observer = null;
1111
+ this.listeners = [];
1112
+ }
1113
+ init(tracker) {
1114
+ super.init(tracker);
1115
+ if (typeof document === 'undefined')
1116
+ return;
1117
+ // Track existing forms
1118
+ this.trackAllForms();
1119
+ // Watch for dynamically added forms
1120
+ if (typeof MutationObserver !== 'undefined') {
1121
+ this.observer = new MutationObserver(() => this.trackAllForms());
1122
+ this.observer.observe(document.body, { childList: true, subtree: true });
1123
+ }
1124
+ }
1125
+ destroy() {
1126
+ if (this.observer) {
1127
+ this.observer.disconnect();
1128
+ this.observer = null;
1129
+ }
1130
+ // Remove all tracked event listeners
1131
+ for (const { element, event, handler } of this.listeners) {
1132
+ element.removeEventListener(event, handler);
1133
+ }
1134
+ this.listeners = [];
1135
+ super.destroy();
1136
+ }
1137
+ /**
1138
+ * Track event listener for cleanup
1139
+ */
1140
+ addListener(element, event, handler) {
1141
+ element.addEventListener(event, handler);
1142
+ this.listeners.push({ element, event, handler });
1143
+ }
1144
+ trackAllForms() {
1145
+ document.querySelectorAll('form').forEach((form) => {
1146
+ this.setupFormTracking(form);
1147
+ });
1148
+ }
1149
+ setupFormTracking(form) {
1150
+ if (this.trackedForms.has(form))
1151
+ return;
1152
+ this.trackedForms.add(form);
1153
+ const formId = form.id || form.name || `form-${Math.random().toString(36).substr(2, 9)}`;
1154
+ // Track form view
1155
+ this.track('form_view', 'Form Viewed', {
1156
+ formId,
1157
+ action: form.action,
1158
+ method: form.method,
1159
+ fieldCount: form.elements.length,
1160
+ });
1161
+ // Track field interactions
1162
+ Array.from(form.elements).forEach((field) => {
1163
+ if (field instanceof HTMLInputElement ||
1164
+ field instanceof HTMLSelectElement ||
1165
+ field instanceof HTMLTextAreaElement) {
1166
+ if (!field.name || field.type === 'submit' || field.type === 'button')
1167
+ return;
1168
+ ['focus', 'blur', 'change'].forEach((eventType) => {
1169
+ const handler = () => {
1170
+ const key = `${formId}-${field.name}-${eventType}`;
1171
+ if (!this.formInteractions.has(key)) {
1172
+ this.formInteractions.add(key);
1173
+ this.track('form_interaction', 'Form Field Interaction', {
1174
+ formId,
1175
+ fieldName: field.name,
1176
+ fieldType: field.type,
1177
+ interactionType: eventType,
1178
+ });
1179
+ }
1180
+ };
1181
+ this.addListener(field, eventType, handler);
1182
+ });
1183
+ }
1184
+ });
1185
+ // Track form submission
1186
+ const submitHandler = () => {
1187
+ this.track('form_submit', 'Form Submitted', {
1188
+ formId,
1189
+ action: form.action,
1190
+ method: form.method,
1191
+ });
1192
+ // Auto-identify if email field found
1193
+ this.autoIdentify(form);
1194
+ };
1195
+ this.addListener(form, 'submit', submitHandler);
1196
+ }
1197
+ autoIdentify(form) {
1198
+ const emailField = form.querySelector('input[type="email"], input[name*="email"]');
1199
+ if (!emailField?.value || !this.tracker)
1200
+ return;
1201
+ const email = emailField.value;
1202
+ const traits = {};
1203
+ // Capture common fields
1204
+ const firstNameField = form.querySelector('[name*="first"], [name*="fname"]');
1205
+ const lastNameField = form.querySelector('[name*="last"], [name*="lname"]');
1206
+ const companyField = form.querySelector('[name*="company"], [name*="organization"]');
1207
+ const phoneField = form.querySelector('[type="tel"], [name*="phone"]');
1208
+ if (firstNameField?.value)
1209
+ traits.firstName = firstNameField.value;
1210
+ if (lastNameField?.value)
1211
+ traits.lastName = lastNameField.value;
1212
+ if (companyField?.value)
1213
+ traits.company = companyField.value;
1214
+ if (phoneField?.value)
1215
+ traits.phone = phoneField.value;
1216
+ this.tracker.identify(email, traits);
1217
+ }
1218
+ }
1219
+
1220
+ /**
1221
+ * Clianta SDK - Click Tracking Plugin
1222
+ * @see SDK_VERSION in core/config.ts
1223
+ */
1224
+ /**
1225
+ * Click Tracking Plugin - Tracks button and CTA clicks
1226
+ */
1227
+ class ClicksPlugin extends BasePlugin {
1228
+ constructor() {
1229
+ super(...arguments);
1230
+ this.name = 'clicks';
1231
+ this.boundHandler = null;
1232
+ }
1233
+ init(tracker) {
1234
+ super.init(tracker);
1235
+ if (typeof document !== 'undefined') {
1236
+ this.boundHandler = this.handleClick.bind(this);
1237
+ document.addEventListener('click', this.boundHandler, true);
1238
+ }
1239
+ }
1240
+ destroy() {
1241
+ if (this.boundHandler && typeof document !== 'undefined') {
1242
+ document.removeEventListener('click', this.boundHandler, true);
1243
+ }
1244
+ super.destroy();
1245
+ }
1246
+ handleClick(e) {
1247
+ const target = e.target;
1248
+ if (!target || !isTrackableClickElement(target))
1249
+ return;
1250
+ const buttonText = getElementText(target, 100);
1251
+ const elementInfo = getElementInfo(target);
1252
+ this.track('button_click', 'Button Clicked', {
1253
+ buttonText,
1254
+ elementType: target.tagName.toLowerCase(),
1255
+ elementId: elementInfo.id,
1256
+ elementClass: elementInfo.className,
1257
+ href: target.href || undefined,
1258
+ x: Math.round((e.clientX / window.innerWidth) * 100),
1259
+ y: Math.round((e.clientY / window.innerHeight) * 100),
1260
+ viewportWidth: window.innerWidth,
1261
+ viewportHeight: window.innerHeight,
1262
+ });
1263
+ }
1264
+ }
1265
+
1266
+ /**
1267
+ * Clianta SDK - Engagement Plugin
1268
+ * @see SDK_VERSION in core/config.ts
1269
+ */
1270
+ /**
1271
+ * Engagement Plugin - Tracks user engagement and time on page
1272
+ */
1273
+ class EngagementPlugin extends BasePlugin {
1274
+ constructor() {
1275
+ super(...arguments);
1276
+ this.name = 'engagement';
1277
+ this.pageLoadTime = 0;
1278
+ this.engagementStartTime = 0;
1279
+ this.isEngaged = false;
1280
+ this.engagementTimeout = null;
1281
+ this.boundMarkEngaged = null;
1282
+ this.boundTrackTimeOnPage = null;
1283
+ this.boundVisibilityHandler = null;
1284
+ /** SPA navigation — listen for PageViewPlugin's custom event instead of patching history */
1285
+ this.navigationHandler = null;
1286
+ this.popstateHandler = null;
1287
+ }
1288
+ init(tracker) {
1289
+ super.init(tracker);
1290
+ this.pageLoadTime = Date.now();
1291
+ this.engagementStartTime = Date.now();
1292
+ if (typeof document === 'undefined' || typeof window === 'undefined')
1293
+ return;
1294
+ // Setup engagement detection
1295
+ this.boundMarkEngaged = this.markEngaged.bind(this);
1296
+ this.boundTrackTimeOnPage = this.trackTimeOnPage.bind(this);
1297
+ this.boundVisibilityHandler = () => {
1298
+ if (document.visibilityState === 'hidden') {
1299
+ this.trackTimeOnPage();
1300
+ }
1301
+ else {
1302
+ // Reset engagement timer when page becomes visible again
1303
+ this.engagementStartTime = Date.now();
1304
+ }
1305
+ };
1306
+ ['mousemove', 'keydown', 'touchstart', 'scroll'].forEach((event) => {
1307
+ document.addEventListener(event, this.boundMarkEngaged, { passive: true });
1308
+ });
1309
+ // Track time on page before unload
1310
+ window.addEventListener('beforeunload', this.boundTrackTimeOnPage);
1311
+ document.addEventListener('visibilitychange', this.boundVisibilityHandler);
1312
+ // Listen for navigation events dispatched by PageViewPlugin
1313
+ // instead of independently monkey-patching history.pushState
1314
+ this.navigationHandler = () => this.resetForNavigation();
1315
+ window.addEventListener('clianta:navigation', this.navigationHandler);
1316
+ // Handle back/forward navigation
1317
+ this.popstateHandler = () => this.resetForNavigation();
1318
+ window.addEventListener('popstate', this.popstateHandler);
1319
+ }
1320
+ destroy() {
1321
+ if (this.boundMarkEngaged && typeof document !== 'undefined') {
1322
+ ['mousemove', 'keydown', 'touchstart', 'scroll'].forEach((event) => {
1323
+ document.removeEventListener(event, this.boundMarkEngaged);
1324
+ });
1325
+ }
1326
+ if (this.boundTrackTimeOnPage && typeof window !== 'undefined') {
1327
+ window.removeEventListener('beforeunload', this.boundTrackTimeOnPage);
1328
+ }
1329
+ if (this.boundVisibilityHandler && typeof document !== 'undefined') {
1330
+ document.removeEventListener('visibilitychange', this.boundVisibilityHandler);
1331
+ }
1332
+ if (this.navigationHandler && typeof window !== 'undefined') {
1333
+ window.removeEventListener('clianta:navigation', this.navigationHandler);
1334
+ this.navigationHandler = null;
1335
+ }
1336
+ if (this.popstateHandler && typeof window !== 'undefined') {
1337
+ window.removeEventListener('popstate', this.popstateHandler);
1338
+ this.popstateHandler = null;
1339
+ }
1340
+ if (this.engagementTimeout) {
1341
+ clearTimeout(this.engagementTimeout);
1342
+ }
1343
+ super.destroy();
1344
+ }
1345
+ resetForNavigation() {
1346
+ this.pageLoadTime = Date.now();
1347
+ this.engagementStartTime = Date.now();
1348
+ this.isEngaged = false;
1349
+ if (this.engagementTimeout) {
1350
+ clearTimeout(this.engagementTimeout);
1351
+ this.engagementTimeout = null;
1352
+ }
1353
+ }
1354
+ markEngaged() {
1355
+ if (!this.isEngaged) {
1356
+ this.isEngaged = true;
1357
+ this.track('engagement', 'User Engaged', {
1358
+ timeToEngage: Date.now() - this.pageLoadTime,
1359
+ });
1360
+ }
1361
+ // Reset engagement timeout
1362
+ if (this.engagementTimeout) {
1363
+ clearTimeout(this.engagementTimeout);
1364
+ }
1365
+ this.engagementTimeout = setTimeout(() => {
1366
+ this.isEngaged = false;
1367
+ }, 30000); // 30 seconds of inactivity
1368
+ }
1369
+ trackTimeOnPage() {
1370
+ const timeSpent = Math.floor((Date.now() - this.engagementStartTime) / 1000);
1371
+ if (timeSpent > 0) {
1372
+ this.track('time_on_page', 'Time Spent', {
1373
+ seconds: timeSpent,
1374
+ engaged: this.isEngaged,
1375
+ });
1376
+ }
1377
+ }
1378
+ }
1379
+
1380
+ /**
1381
+ * Clianta SDK - Downloads Plugin
1382
+ * @see SDK_VERSION in core/config.ts
1383
+ */
1384
+ /**
1385
+ * Downloads Plugin - Tracks file downloads
1386
+ */
1387
+ class DownloadsPlugin extends BasePlugin {
1388
+ constructor() {
1389
+ super(...arguments);
1390
+ this.name = 'downloads';
1391
+ this.trackedDownloads = new Set();
1392
+ this.boundHandler = null;
1393
+ /** SPA navigation — listen for PageViewPlugin's custom event instead of patching history */
1394
+ this.navigationHandler = null;
1395
+ this.popstateHandler = null;
1396
+ }
1397
+ init(tracker) {
1398
+ super.init(tracker);
1399
+ if (typeof document !== 'undefined') {
1400
+ this.boundHandler = this.handleClick.bind(this);
1401
+ document.addEventListener('click', this.boundHandler, true);
1402
+ }
1403
+ if (typeof window !== 'undefined') {
1404
+ // Listen for navigation events dispatched by PageViewPlugin
1405
+ // instead of independently monkey-patching history.pushState
1406
+ this.navigationHandler = () => this.resetForNavigation();
1407
+ window.addEventListener('clianta:navigation', this.navigationHandler);
1408
+ // Handle back/forward navigation
1409
+ this.popstateHandler = () => this.resetForNavigation();
1410
+ window.addEventListener('popstate', this.popstateHandler);
1411
+ }
1412
+ }
1413
+ destroy() {
1414
+ if (this.boundHandler && typeof document !== 'undefined') {
1415
+ document.removeEventListener('click', this.boundHandler, true);
1416
+ }
1417
+ if (this.navigationHandler && typeof window !== 'undefined') {
1418
+ window.removeEventListener('clianta:navigation', this.navigationHandler);
1419
+ this.navigationHandler = null;
1420
+ }
1421
+ if (this.popstateHandler && typeof window !== 'undefined') {
1422
+ window.removeEventListener('popstate', this.popstateHandler);
1423
+ this.popstateHandler = null;
1424
+ }
1425
+ super.destroy();
1426
+ }
1427
+ /**
1428
+ * Reset download tracking for SPA navigation
1429
+ */
1430
+ resetForNavigation() {
1431
+ this.trackedDownloads.clear();
1432
+ }
1433
+ handleClick(e) {
1434
+ const link = e.target.closest('a');
1435
+ if (!link || !link.href)
1436
+ return;
1437
+ const url = link.href;
1438
+ // Check if it's a download link
1439
+ if (!isDownloadUrl(url))
1440
+ return;
1441
+ // Avoid tracking the same download multiple times
1442
+ if (this.trackedDownloads.has(url))
1443
+ return;
1444
+ this.trackedDownloads.add(url);
1445
+ this.track('download', 'File Download', {
1446
+ url,
1447
+ filename: getFilenameFromUrl(url),
1448
+ fileType: getFileExtension(url),
1449
+ linkText: getElementText(link, 100),
1450
+ });
1451
+ }
1452
+ }
1453
+
1454
+ /**
1455
+ * Clianta SDK - Exit Intent Plugin
1456
+ * @see SDK_VERSION in core/config.ts
1457
+ */
1458
+ /**
1459
+ * Exit Intent Plugin - Detects when user intends to leave the page
1460
+ */
1461
+ class ExitIntentPlugin extends BasePlugin {
1462
+ constructor() {
1463
+ super(...arguments);
1464
+ this.name = 'exitIntent';
1465
+ this.exitIntentShown = false;
1466
+ this.pageLoadTime = 0;
1467
+ this.boundHandler = null;
1468
+ /** SPA navigation — listen for PageViewPlugin's custom event instead of patching history */
1469
+ this.navigationHandler = null;
1470
+ this.popstateHandler = null;
1471
+ }
1472
+ init(tracker) {
1473
+ super.init(tracker);
1474
+ this.pageLoadTime = Date.now();
1475
+ // Skip on mobile (no mouse events)
1476
+ if (isMobile())
1477
+ return;
1478
+ if (typeof document !== 'undefined') {
1479
+ this.boundHandler = this.handleMouseLeave.bind(this);
1480
+ document.addEventListener('mouseleave', this.boundHandler);
1481
+ }
1482
+ if (typeof window !== 'undefined') {
1483
+ // Listen for navigation events dispatched by PageViewPlugin
1484
+ // instead of independently monkey-patching history.pushState
1485
+ this.navigationHandler = () => this.resetForNavigation();
1486
+ window.addEventListener('clianta:navigation', this.navigationHandler);
1487
+ // Handle back/forward navigation
1488
+ this.popstateHandler = () => this.resetForNavigation();
1489
+ window.addEventListener('popstate', this.popstateHandler);
1490
+ }
1491
+ }
1492
+ destroy() {
1493
+ if (this.boundHandler && typeof document !== 'undefined') {
1494
+ document.removeEventListener('mouseleave', this.boundHandler);
1495
+ }
1496
+ if (this.navigationHandler && typeof window !== 'undefined') {
1497
+ window.removeEventListener('clianta:navigation', this.navigationHandler);
1498
+ this.navigationHandler = null;
1499
+ }
1500
+ if (this.popstateHandler && typeof window !== 'undefined') {
1501
+ window.removeEventListener('popstate', this.popstateHandler);
1502
+ this.popstateHandler = null;
1503
+ }
1504
+ super.destroy();
1505
+ }
1506
+ resetForNavigation() {
1507
+ this.exitIntentShown = false;
1508
+ this.pageLoadTime = Date.now();
1509
+ }
1510
+ handleMouseLeave(e) {
1511
+ // Only trigger when mouse leaves from the top of the page
1512
+ if (e.clientY > 0 || this.exitIntentShown)
1513
+ return;
1514
+ this.exitIntentShown = true;
1515
+ this.track('exit_intent', 'Exit Intent Detected', {
1516
+ timeOnPage: Date.now() - this.pageLoadTime,
1517
+ });
1518
+ }
1519
+ }
1520
+
1521
+ /**
1522
+ * Clianta SDK - Error Tracking Plugin
1523
+ * @see SDK_VERSION in core/config.ts
1524
+ */
1525
+ /**
1526
+ * Error Tracking Plugin - Tracks JavaScript errors
1527
+ */
1528
+ class ErrorsPlugin extends BasePlugin {
1529
+ constructor() {
1530
+ super(...arguments);
1531
+ this.name = 'errors';
1532
+ this.boundErrorHandler = null;
1533
+ this.boundRejectionHandler = null;
1534
+ }
1535
+ init(tracker) {
1536
+ super.init(tracker);
1537
+ if (typeof window !== 'undefined') {
1538
+ this.boundErrorHandler = this.handleError.bind(this);
1539
+ this.boundRejectionHandler = this.handleRejection.bind(this);
1540
+ window.addEventListener('error', this.boundErrorHandler);
1541
+ window.addEventListener('unhandledrejection', this.boundRejectionHandler);
1542
+ }
1543
+ }
1544
+ destroy() {
1545
+ if (typeof window !== 'undefined') {
1546
+ if (this.boundErrorHandler) {
1547
+ window.removeEventListener('error', this.boundErrorHandler);
1548
+ }
1549
+ if (this.boundRejectionHandler) {
1550
+ window.removeEventListener('unhandledrejection', this.boundRejectionHandler);
1551
+ }
1552
+ }
1553
+ super.destroy();
1554
+ }
1555
+ handleError(e) {
1556
+ this.track('error', 'JavaScript Error', {
1557
+ message: e.message,
1558
+ filename: e.filename,
1559
+ line: e.lineno,
1560
+ column: e.colno,
1561
+ stack: e.error?.stack?.substring(0, 500),
1562
+ });
1563
+ }
1564
+ handleRejection(e) {
1565
+ this.track('error', 'Unhandled Promise Rejection', {
1566
+ reason: String(e.reason).substring(0, 200),
1567
+ });
1568
+ }
1569
+ }
1570
+
1571
+ /**
1572
+ * Clianta SDK - Performance Plugin
1573
+ * @see SDK_VERSION in core/config.ts
1574
+ */
1575
+ /**
1576
+ * Performance Plugin - Tracks page performance and Web Vitals
1577
+ */
1578
+ class PerformancePlugin extends BasePlugin {
1579
+ constructor() {
1580
+ super(...arguments);
1581
+ this.name = 'performance';
1582
+ this.boundLoadHandler = null;
1583
+ this.observers = [];
1584
+ this.boundClsVisibilityHandler = null;
1585
+ }
1586
+ init(tracker) {
1587
+ super.init(tracker);
1588
+ if (typeof window !== 'undefined') {
1589
+ // Track performance after page load
1590
+ this.boundLoadHandler = () => {
1591
+ // Delay to ensure all metrics are available
1592
+ setTimeout(() => this.trackPerformance(), 100);
1593
+ };
1594
+ window.addEventListener('load', this.boundLoadHandler);
1595
+ }
1596
+ }
1597
+ destroy() {
1598
+ if (this.boundLoadHandler && typeof window !== 'undefined') {
1599
+ window.removeEventListener('load', this.boundLoadHandler);
1600
+ }
1601
+ for (const observer of this.observers) {
1602
+ observer.disconnect();
1603
+ }
1604
+ this.observers = [];
1605
+ if (this.boundClsVisibilityHandler && typeof window !== 'undefined') {
1606
+ window.removeEventListener('visibilitychange', this.boundClsVisibilityHandler);
1607
+ }
1608
+ super.destroy();
1609
+ }
1610
+ trackPerformance() {
1611
+ if (typeof performance === 'undefined')
1612
+ return;
1613
+ // Use modern Navigation Timing API (PerformanceNavigationTiming)
1614
+ const entries = performance.getEntriesByType('navigation');
1615
+ if (entries.length > 0) {
1616
+ const navTiming = entries[0];
1617
+ const loadTime = Math.round(navTiming.loadEventEnd - navTiming.startTime);
1618
+ const domReady = Math.round(navTiming.domContentLoadedEventEnd - navTiming.startTime);
1619
+ const ttfb = Math.round(navTiming.responseStart - navTiming.requestStart);
1620
+ const domInteractive = Math.round(navTiming.domInteractive - navTiming.startTime);
1621
+ this.track('performance', 'Page Performance', {
1622
+ loadTime,
1623
+ domReady,
1624
+ ttfb, // Time to First Byte
1625
+ domInteractive,
1626
+ // Additional modern metrics
1627
+ dns: Math.round(navTiming.domainLookupEnd - navTiming.domainLookupStart),
1628
+ connection: Math.round(navTiming.connectEnd - navTiming.connectStart),
1629
+ transferSize: navTiming.transferSize,
1630
+ });
1631
+ }
1632
+ else {
1633
+ // Fallback for older browsers using deprecated API
1634
+ const timing = performance.timing;
1635
+ if (!timing)
1636
+ return;
1637
+ const loadTime = timing.loadEventEnd - timing.navigationStart;
1638
+ const domReady = timing.domContentLoadedEventEnd - timing.navigationStart;
1639
+ const ttfb = timing.responseStart - timing.navigationStart;
1640
+ const domInteractive = timing.domInteractive - timing.navigationStart;
1641
+ this.track('performance', 'Page Performance', {
1642
+ loadTime,
1643
+ domReady,
1644
+ ttfb,
1645
+ domInteractive,
1646
+ });
1647
+ }
1648
+ // Track Web Vitals if available
1649
+ this.trackWebVitals();
1650
+ }
1651
+ trackWebVitals() {
1652
+ // LCP (Largest Contentful Paint)
1653
+ if ('PerformanceObserver' in window) {
1654
+ try {
1655
+ const lcpObserver = new PerformanceObserver((entryList) => {
1656
+ const entries = entryList.getEntries();
1657
+ const lastEntry = entries[entries.length - 1];
1658
+ if (lastEntry) {
1659
+ this.track('performance', 'Web Vital - LCP', {
1660
+ metric: 'LCP',
1661
+ value: Math.round(lastEntry.startTime),
1662
+ });
1663
+ }
1664
+ });
1665
+ lcpObserver.observe({ type: 'largest-contentful-paint', buffered: true });
1666
+ this.observers.push(lcpObserver);
1667
+ }
1668
+ catch {
1669
+ // LCP not supported
1670
+ }
1671
+ // FID (First Input Delay)
1672
+ try {
1673
+ const fidObserver = new PerformanceObserver((entryList) => {
1674
+ const entries = entryList.getEntries();
1675
+ const firstEntry = entries[0];
1676
+ if (firstEntry) {
1677
+ this.track('performance', 'Web Vital - FID', {
1678
+ metric: 'FID',
1679
+ value: Math.round(firstEntry.processingStart - firstEntry.startTime),
1680
+ });
1681
+ }
1682
+ });
1683
+ fidObserver.observe({ type: 'first-input', buffered: true });
1684
+ this.observers.push(fidObserver);
1685
+ }
1686
+ catch {
1687
+ // FID not supported
1688
+ }
1689
+ // CLS (Cumulative Layout Shift)
1690
+ try {
1691
+ let clsValue = 0;
1692
+ const clsObserver = new PerformanceObserver((entryList) => {
1693
+ const entries = entryList.getEntries();
1694
+ entries.forEach((entry) => {
1695
+ if (!entry.hadRecentInput) {
1696
+ clsValue += entry.value || 0;
1697
+ }
1698
+ });
1699
+ });
1700
+ clsObserver.observe({ type: 'layout-shift', buffered: true });
1701
+ this.observers.push(clsObserver);
1702
+ // Report CLS after page is hidden
1703
+ this.boundClsVisibilityHandler = () => {
1704
+ if (document.visibilityState === 'hidden' && clsValue > 0) {
1705
+ this.track('performance', 'Web Vital - CLS', {
1706
+ metric: 'CLS',
1707
+ value: Math.round(clsValue * 1000) / 1000,
1708
+ });
1709
+ }
1710
+ };
1711
+ window.addEventListener('visibilitychange', this.boundClsVisibilityHandler, { once: true });
1712
+ }
1713
+ catch {
1714
+ // CLS not supported
1715
+ }
1716
+ }
1717
+ }
1718
+ }
1719
+
1720
+ /**
1721
+ * Clianta Tracking SDK - Popup Forms Plugin
1722
+ * @see SDK_VERSION in core/config.ts
1723
+ *
1724
+ * Auto-loads and displays lead capture popups based on triggers
1725
+ */
1726
+ /**
1727
+ * Popup Forms Plugin - Fetches and displays lead capture forms
1728
+ */
1729
+ class PopupFormsPlugin extends BasePlugin {
1730
+ constructor() {
1731
+ super(...arguments);
1732
+ this.name = 'popupForms';
1733
+ this.forms = [];
1734
+ this.shownForms = new Set();
1735
+ this.scrollHandler = null;
1736
+ this.exitHandler = null;
1737
+ this.delayTimers = [];
1738
+ this.clickTriggerListeners = [];
1739
+ }
1740
+ async init(tracker) {
1741
+ super.init(tracker);
1742
+ if (typeof window === 'undefined')
1743
+ return;
1744
+ // Load shown forms from storage
1745
+ this.loadShownForms();
1746
+ // Fetch active forms
1747
+ await this.fetchForms();
1748
+ // Setup triggers
1749
+ this.setupTriggers();
1750
+ }
1751
+ destroy() {
1752
+ this.removeTriggers();
1753
+ for (const timer of this.delayTimers) {
1754
+ clearTimeout(timer);
1755
+ }
1756
+ this.delayTimers = [];
1757
+ for (const { element, handler } of this.clickTriggerListeners) {
1758
+ element.removeEventListener('click', handler);
1759
+ }
1760
+ this.clickTriggerListeners = [];
1761
+ super.destroy();
1762
+ }
1763
+ loadShownForms() {
1764
+ try {
1765
+ const stored = localStorage.getItem('clianta_shown_forms');
1766
+ if (stored) {
1767
+ const data = JSON.parse(stored);
1768
+ this.shownForms = new Set(data.forms || []);
1769
+ }
1770
+ }
1771
+ catch (e) {
1772
+ // Ignore storage errors
1773
+ }
1774
+ }
1775
+ saveShownForms() {
1776
+ try {
1777
+ localStorage.setItem('clianta_shown_forms', JSON.stringify({
1778
+ forms: Array.from(this.shownForms),
1779
+ timestamp: Date.now(),
1780
+ }));
1781
+ }
1782
+ catch (e) {
1783
+ // Ignore storage errors
1784
+ }
1785
+ }
1786
+ async fetchForms() {
1787
+ if (!this.tracker)
1788
+ return;
1789
+ const config = this.tracker.getConfig();
1790
+ const workspaceId = this.tracker.getWorkspaceId();
1791
+ const apiEndpoint = config.apiEndpoint || 'http://localhost:5000';
1792
+ try {
1793
+ const url = encodeURIComponent(window.location.href);
1794
+ const response = await fetch(`${apiEndpoint}/api/public/lead-forms/${workspaceId}?url=${url}`);
1795
+ if (!response.ok)
1796
+ return;
1797
+ const data = await response.json();
1798
+ if (data.success && Array.isArray(data.data)) {
1799
+ this.forms = data.data.filter((form) => this.shouldShowForm(form));
1800
+ }
1801
+ }
1802
+ catch (error) {
1803
+ console.error('[Clianta] Failed to fetch forms:', error);
1804
+ }
1805
+ }
1806
+ shouldShowForm(form) {
1807
+ // Check show frequency
1808
+ if (form.showFrequency === 'once_per_visitor') {
1809
+ if (this.shownForms.has(form._id))
1810
+ return false;
1811
+ }
1812
+ else if (form.showFrequency === 'once_per_session') {
1813
+ const sessionKey = `clianta_form_${form._id}_shown`;
1814
+ if (sessionStorage.getItem(sessionKey))
1815
+ return false;
1816
+ }
1817
+ return true;
1818
+ }
1819
+ setupTriggers() {
1820
+ this.forms.forEach(form => {
1821
+ switch (form.trigger.type) {
1822
+ case 'delay':
1823
+ this.delayTimers.push(setTimeout(() => this.showForm(form), (form.trigger.value || 5) * 1000));
1824
+ break;
1825
+ case 'scroll':
1826
+ this.setupScrollTrigger(form);
1827
+ break;
1828
+ case 'exit_intent':
1829
+ this.setupExitIntentTrigger(form);
1830
+ break;
1831
+ case 'click':
1832
+ this.setupClickTrigger(form);
1833
+ break;
1834
+ }
1835
+ });
1836
+ }
1837
+ setupScrollTrigger(form) {
1838
+ const threshold = form.trigger.value || 50;
1839
+ this.scrollHandler = () => {
1840
+ const scrollPercent = (window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100;
1841
+ if (scrollPercent >= threshold) {
1842
+ this.showForm(form);
1843
+ if (this.scrollHandler) {
1844
+ window.removeEventListener('scroll', this.scrollHandler);
1845
+ }
1846
+ }
1847
+ };
1848
+ window.addEventListener('scroll', this.scrollHandler, { passive: true });
1849
+ }
1850
+ setupExitIntentTrigger(form) {
1851
+ this.exitHandler = (e) => {
1852
+ if (e.clientY <= 0) {
1853
+ this.showForm(form);
1854
+ if (this.exitHandler) {
1855
+ document.removeEventListener('mouseout', this.exitHandler);
1856
+ }
1857
+ }
1858
+ };
1859
+ document.addEventListener('mouseout', this.exitHandler);
1860
+ }
1861
+ setupClickTrigger(form) {
1862
+ if (!form.trigger.selector)
1863
+ return;
1864
+ const elements = document.querySelectorAll(form.trigger.selector);
1865
+ elements.forEach(el => {
1866
+ const handler = () => this.showForm(form);
1867
+ el.addEventListener('click', handler);
1868
+ this.clickTriggerListeners.push({ element: el, handler });
1869
+ });
1870
+ }
1871
+ removeTriggers() {
1872
+ if (this.scrollHandler) {
1873
+ window.removeEventListener('scroll', this.scrollHandler);
1874
+ }
1875
+ if (this.exitHandler) {
1876
+ document.removeEventListener('mouseout', this.exitHandler);
1877
+ }
1878
+ }
1879
+ async showForm(form) {
1880
+ // Check if already shown in this session
1881
+ if (!this.shouldShowForm(form))
1882
+ return;
1883
+ // Mark as shown
1884
+ this.shownForms.add(form._id);
1885
+ this.saveShownForms();
1886
+ sessionStorage.setItem(`clianta_form_${form._id}_shown`, 'true');
1887
+ // Track view
1888
+ await this.trackFormView(form._id);
1889
+ // Render form
1890
+ this.renderForm(form);
1891
+ }
1892
+ async trackFormView(formId) {
1893
+ if (!this.tracker)
1894
+ return;
1895
+ const config = this.tracker.getConfig();
1896
+ const apiEndpoint = config.apiEndpoint || 'http://localhost:5000';
1897
+ try {
1898
+ await fetch(`${apiEndpoint}/api/public/lead-forms/${formId}/view`, {
1899
+ method: 'POST',
1900
+ headers: { 'Content-Type': 'application/json' },
1901
+ });
1902
+ }
1903
+ catch (e) {
1904
+ // Ignore tracking errors
1905
+ }
1906
+ }
1907
+ renderForm(form) {
1908
+ // Create overlay
1909
+ const overlay = document.createElement('div');
1910
+ overlay.id = `clianta-form-overlay-${form._id}`;
1911
+ overlay.style.cssText = `
1912
+ position: fixed;
1913
+ top: 0;
1914
+ left: 0;
1915
+ right: 0;
1916
+ bottom: 0;
1917
+ background: rgba(0, 0, 0, 0.5);
1918
+ z-index: 999998;
1919
+ display: flex;
1920
+ align-items: center;
1921
+ justify-content: center;
1922
+ opacity: 0;
1923
+ transition: opacity 0.3s ease;
1924
+ `;
1925
+ // Create form container
1926
+ const container = document.createElement('div');
1927
+ container.id = `clianta-form-${form._id}`;
1928
+ const style = form.style || {};
1929
+ container.style.cssText = `
1930
+ background: ${style.backgroundColor || '#FFFFFF'};
1931
+ border-radius: ${style.borderRadius || 12}px;
1932
+ padding: 24px;
1933
+ max-width: 400px;
1934
+ width: 90%;
1935
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
1936
+ transform: translateY(20px);
1937
+ opacity: 0;
1938
+ transition: all 0.3s ease;
1939
+ `;
1940
+ // Build form using safe DOM APIs (no innerHTML for user content)
1941
+ this.buildFormDOM(form, container);
1942
+ overlay.appendChild(container);
1943
+ document.body.appendChild(overlay);
1944
+ // Animate in
1945
+ requestAnimationFrame(() => {
1946
+ overlay.style.opacity = '1';
1947
+ container.style.transform = 'translateY(0)';
1948
+ container.style.opacity = '1';
1949
+ });
1950
+ // Setup event listeners
1951
+ this.setupFormEvents(form, overlay, container);
1952
+ }
1953
+ /**
1954
+ * Escape HTML to prevent XSS - used only for static structure
1955
+ */
1956
+ escapeHTML(str) {
1957
+ const div = document.createElement('div');
1958
+ div.textContent = str;
1959
+ return div.innerHTML;
1960
+ }
1961
+ /**
1962
+ * Build form using safe DOM APIs (prevents XSS)
1963
+ */
1964
+ buildFormDOM(form, container) {
1965
+ const style = form.style || {};
1966
+ const primaryColor = style.primaryColor || '#10B981';
1967
+ const textColor = style.textColor || '#18181B';
1968
+ // Close button
1969
+ const closeBtn = document.createElement('button');
1970
+ closeBtn.id = 'clianta-form-close';
1971
+ closeBtn.style.cssText = `
1972
+ position: absolute;
1973
+ top: 12px;
1974
+ right: 12px;
1975
+ background: none;
1976
+ border: none;
1977
+ font-size: 20px;
1978
+ cursor: pointer;
1979
+ color: #71717A;
1980
+ padding: 4px;
1981
+ `;
1982
+ closeBtn.textContent = '×';
1983
+ container.appendChild(closeBtn);
1984
+ // Headline
1985
+ const headline = document.createElement('h2');
1986
+ headline.style.cssText = `font-size: 20px; font-weight: 700; margin-bottom: 8px; color: ${this.escapeHTML(textColor)};`;
1987
+ headline.textContent = form.headline || 'Stay in touch';
1988
+ container.appendChild(headline);
1989
+ // Subheadline
1990
+ const subheadline = document.createElement('p');
1991
+ subheadline.style.cssText = 'font-size: 14px; color: #71717A; margin-bottom: 16px;';
1992
+ subheadline.textContent = form.subheadline || 'Get the latest updates';
1993
+ container.appendChild(subheadline);
1994
+ // Form element
1995
+ const formElement = document.createElement('form');
1996
+ formElement.id = 'clianta-form-element';
1997
+ // Build fields
1998
+ form.fields.forEach(field => {
1999
+ const fieldWrapper = document.createElement('div');
2000
+ fieldWrapper.style.marginBottom = '12px';
2001
+ if (field.type === 'checkbox') {
2002
+ // Checkbox layout
2003
+ const label = document.createElement('label');
2004
+ label.style.cssText = `display: flex; align-items: center; gap: 8px; font-size: 14px; color: ${this.escapeHTML(textColor)}; cursor: pointer;`;
2005
+ const input = document.createElement('input');
2006
+ input.type = 'checkbox';
2007
+ input.name = field.name;
2008
+ if (field.required)
2009
+ input.required = true;
2010
+ input.style.cssText = 'width: 16px; height: 16px;';
2011
+ label.appendChild(input);
2012
+ const labelText = document.createTextNode(field.label + ' ');
2013
+ label.appendChild(labelText);
2014
+ if (field.required) {
2015
+ const requiredMark = document.createElement('span');
2016
+ requiredMark.style.color = '#EF4444';
2017
+ requiredMark.textContent = '*';
2018
+ label.appendChild(requiredMark);
2019
+ }
2020
+ fieldWrapper.appendChild(label);
2021
+ }
2022
+ else {
2023
+ // Label
2024
+ const label = document.createElement('label');
2025
+ label.style.cssText = `display: block; font-size: 14px; font-weight: 500; margin-bottom: 4px; color: ${this.escapeHTML(textColor)};`;
2026
+ label.textContent = field.label + ' ';
2027
+ if (field.required) {
2028
+ const requiredMark = document.createElement('span');
2029
+ requiredMark.style.color = '#EF4444';
2030
+ requiredMark.textContent = '*';
2031
+ label.appendChild(requiredMark);
2032
+ }
2033
+ fieldWrapper.appendChild(label);
2034
+ // Input/Textarea/Select
2035
+ if (field.type === 'textarea') {
2036
+ const textarea = document.createElement('textarea');
2037
+ textarea.name = field.name;
2038
+ if (field.placeholder)
2039
+ textarea.placeholder = field.placeholder;
2040
+ if (field.required)
2041
+ textarea.required = true;
2042
+ textarea.style.cssText = 'width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; resize: vertical; min-height: 80px; box-sizing: border-box;';
2043
+ fieldWrapper.appendChild(textarea);
2044
+ }
2045
+ else if (field.type === 'select') {
2046
+ const select = document.createElement('select');
2047
+ select.name = field.name;
2048
+ if (field.required)
2049
+ select.required = true;
2050
+ select.style.cssText = 'width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; box-sizing: border-box; background: white; cursor: pointer;';
2051
+ // Add placeholder option
2052
+ if (field.placeholder) {
2053
+ const placeholderOption = document.createElement('option');
2054
+ placeholderOption.value = '';
2055
+ placeholderOption.textContent = field.placeholder;
2056
+ placeholderOption.disabled = true;
2057
+ placeholderOption.selected = true;
2058
+ select.appendChild(placeholderOption);
2059
+ }
2060
+ // Add options from field.options array if provided
2061
+ if (field.options && Array.isArray(field.options)) {
2062
+ field.options.forEach((opt) => {
2063
+ const option = document.createElement('option');
2064
+ if (typeof opt === 'string') {
2065
+ option.value = opt;
2066
+ option.textContent = opt;
2067
+ }
2068
+ else {
2069
+ option.value = opt.value;
2070
+ option.textContent = opt.label;
2071
+ }
2072
+ select.appendChild(option);
2073
+ });
2074
+ }
2075
+ fieldWrapper.appendChild(select);
2076
+ }
2077
+ else {
2078
+ const input = document.createElement('input');
2079
+ input.type = field.type;
2080
+ input.name = field.name;
2081
+ if (field.placeholder)
2082
+ input.placeholder = field.placeholder;
2083
+ if (field.required)
2084
+ input.required = true;
2085
+ input.style.cssText = 'width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; box-sizing: border-box;';
2086
+ fieldWrapper.appendChild(input);
2087
+ }
2088
+ }
2089
+ formElement.appendChild(fieldWrapper);
2090
+ });
2091
+ // Submit button
2092
+ const submitBtn = document.createElement('button');
2093
+ submitBtn.type = 'submit';
2094
+ submitBtn.style.cssText = `
2095
+ width: 100%;
2096
+ padding: 10px 16px;
2097
+ background: ${this.escapeHTML(primaryColor)};
2098
+ color: white;
2099
+ border: none;
2100
+ border-radius: 6px;
2101
+ font-size: 14px;
2102
+ font-weight: 500;
2103
+ cursor: pointer;
2104
+ margin-top: 8px;
2105
+ `;
2106
+ submitBtn.textContent = form.submitButtonText || 'Subscribe';
2107
+ formElement.appendChild(submitBtn);
2108
+ container.appendChild(formElement);
2109
+ }
2110
+ setupFormEvents(form, overlay, container) {
2111
+ // Close button
2112
+ const closeBtn = container.querySelector('#clianta-form-close');
2113
+ if (closeBtn) {
2114
+ closeBtn.addEventListener('click', () => this.closeForm(form._id, overlay, container));
2115
+ }
2116
+ // Overlay click
2117
+ overlay.addEventListener('click', (e) => {
2118
+ if (e.target === overlay) {
2119
+ this.closeForm(form._id, overlay, container);
2120
+ }
2121
+ });
2122
+ // Form submit
2123
+ const formElement = container.querySelector('#clianta-form-element');
2124
+ if (formElement) {
2125
+ formElement.addEventListener('submit', async (e) => {
2126
+ e.preventDefault();
2127
+ await this.handleSubmit(form, formElement, container);
2128
+ });
2129
+ }
2130
+ }
2131
+ closeForm(formId, overlay, container) {
2132
+ container.style.transform = 'translateY(20px)';
2133
+ container.style.opacity = '0';
2134
+ overlay.style.opacity = '0';
2135
+ setTimeout(() => {
2136
+ overlay.remove();
2137
+ }, 300);
2138
+ }
2139
+ async handleSubmit(form, formElement, container) {
2140
+ if (!this.tracker)
2141
+ return;
2142
+ const config = this.tracker.getConfig();
2143
+ const apiEndpoint = config.apiEndpoint || 'http://localhost:5000';
2144
+ const visitorId = this.tracker.getVisitorId();
2145
+ // Collect form data
2146
+ const formData = new FormData(formElement);
2147
+ const data = {};
2148
+ formData.forEach((value, key) => {
2149
+ data[key] = value;
2150
+ });
2151
+ // Disable submit button
2152
+ const submitBtn = formElement.querySelector('button[type="submit"]');
2153
+ if (submitBtn) {
2154
+ submitBtn.disabled = true;
2155
+ submitBtn.textContent = 'Submitting...';
2156
+ }
2157
+ try {
2158
+ const response = await fetch(`${apiEndpoint}/api/public/lead-forms/${form._id}/submit`, {
2159
+ method: 'POST',
2160
+ headers: { 'Content-Type': 'application/json' },
2161
+ body: JSON.stringify({
2162
+ visitorId,
2163
+ data,
2164
+ url: window.location.href,
2165
+ }),
2166
+ });
2167
+ const result = await response.json();
2168
+ if (result.success) {
2169
+ // Show success message using safe DOM APIs
2170
+ container.innerHTML = '';
2171
+ const successWrapper = document.createElement('div');
2172
+ successWrapper.style.cssText = 'text-align: center; padding: 20px;';
2173
+ const iconWrapper = document.createElement('div');
2174
+ iconWrapper.style.cssText = 'width: 48px; height: 48px; background: #10B981; border-radius: 50%; margin: 0 auto 16px; display: flex; align-items: center; justify-content: center;';
2175
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
2176
+ svg.setAttribute('width', '24');
2177
+ svg.setAttribute('height', '24');
2178
+ svg.setAttribute('viewBox', '0 0 24 24');
2179
+ svg.setAttribute('fill', 'none');
2180
+ svg.setAttribute('stroke', 'white');
2181
+ svg.setAttribute('stroke-width', '2');
2182
+ const polyline = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
2183
+ polyline.setAttribute('points', '20 6 9 17 4 12');
2184
+ svg.appendChild(polyline);
2185
+ iconWrapper.appendChild(svg);
2186
+ const message = document.createElement('p');
2187
+ message.style.cssText = 'font-size: 16px; font-weight: 500; color: #18181B;';
2188
+ message.textContent = form.successMessage || 'Thank you!';
2189
+ successWrapper.appendChild(iconWrapper);
2190
+ successWrapper.appendChild(message);
2191
+ container.appendChild(successWrapper);
2192
+ // Track identify
2193
+ if (data.email) {
2194
+ this.tracker?.identify(data.email, data);
2195
+ }
2196
+ // Redirect if configured (validate URL to prevent open redirect)
2197
+ if (form.redirectUrl) {
2198
+ try {
2199
+ const redirect = new URL(form.redirectUrl, window.location.origin);
2200
+ const isSameOrigin = redirect.origin === window.location.origin;
2201
+ const isSafeProtocol = redirect.protocol === 'https:' || redirect.protocol === 'http:';
2202
+ if (isSameOrigin || isSafeProtocol) {
2203
+ setTimeout(() => {
2204
+ window.location.href = redirect.href;
2205
+ }, 1500);
2206
+ }
2207
+ else {
2208
+ console.warn('[Clianta] Blocked unsafe redirect URL:', form.redirectUrl);
2209
+ }
2210
+ }
2211
+ catch {
2212
+ console.warn('[Clianta] Invalid redirect URL:', form.redirectUrl);
2213
+ }
2214
+ }
2215
+ // Close after delay
2216
+ setTimeout(() => {
2217
+ const overlay = document.getElementById(`clianta-form-overlay-${form._id}`);
2218
+ if (overlay) {
2219
+ this.closeForm(form._id, overlay, container);
2220
+ }
2221
+ }, 2000);
2222
+ }
2223
+ }
2224
+ catch (error) {
2225
+ console.error('[Clianta] Form submit error:', error);
2226
+ if (submitBtn) {
2227
+ submitBtn.disabled = false;
2228
+ submitBtn.textContent = form.submitButtonText || 'Subscribe';
2229
+ }
2230
+ }
2231
+ }
2232
+ }
2233
+
2234
+ /**
2235
+ * Clianta SDK - Plugins Index
2236
+ * Version is defined in core/config.ts as SDK_VERSION
2237
+ */
2238
+ /**
2239
+ * Get plugin instance by name
2240
+ */
2241
+ function getPlugin(name) {
2242
+ switch (name) {
2243
+ case 'pageView':
2244
+ return new PageViewPlugin();
2245
+ case 'scroll':
2246
+ return new ScrollPlugin();
2247
+ case 'forms':
2248
+ return new FormsPlugin();
2249
+ case 'clicks':
2250
+ return new ClicksPlugin();
2251
+ case 'engagement':
2252
+ return new EngagementPlugin();
2253
+ case 'downloads':
2254
+ return new DownloadsPlugin();
2255
+ case 'exitIntent':
2256
+ return new ExitIntentPlugin();
2257
+ case 'errors':
2258
+ return new ErrorsPlugin();
2259
+ case 'performance':
2260
+ return new PerformancePlugin();
2261
+ case 'popupForms':
2262
+ return new PopupFormsPlugin();
2263
+ default:
2264
+ throw new Error(`Unknown plugin: ${name}`);
2265
+ }
2266
+ }
2267
+
2268
+ /**
2269
+ * Clianta SDK - Consent Storage
2270
+ * Handles persistence of consent state
2271
+ * @see SDK_VERSION in core/config.ts
2272
+ */
2273
+ const CONSENT_VERSION = 1;
2274
+ /**
2275
+ * Save consent state to storage
2276
+ */
2277
+ function saveConsent(state) {
2278
+ try {
2279
+ if (typeof localStorage === 'undefined')
2280
+ return false;
2281
+ const stored = {
2282
+ state,
2283
+ timestamp: Date.now(),
2284
+ version: CONSENT_VERSION,
2285
+ };
2286
+ localStorage.setItem(STORAGE_KEYS.CONSENT, JSON.stringify(stored));
2287
+ return true;
2288
+ }
2289
+ catch {
2290
+ return false;
2291
+ }
2292
+ }
2293
+ /**
2294
+ * Load consent state from storage
2295
+ */
2296
+ function loadConsent() {
2297
+ try {
2298
+ if (typeof localStorage === 'undefined')
2299
+ return null;
2300
+ const stored = localStorage.getItem(STORAGE_KEYS.CONSENT);
2301
+ if (!stored)
2302
+ return null;
2303
+ const parsed = JSON.parse(stored);
2304
+ // Validate version
2305
+ if (parsed.version !== CONSENT_VERSION) {
2306
+ clearConsent();
2307
+ return null;
2308
+ }
2309
+ return parsed;
2310
+ }
2311
+ catch {
2312
+ return null;
2313
+ }
2314
+ }
2315
+ /**
2316
+ * Clear consent state from storage
2317
+ */
2318
+ function clearConsent() {
2319
+ try {
2320
+ if (typeof localStorage === 'undefined')
2321
+ return false;
2322
+ localStorage.removeItem(STORAGE_KEYS.CONSENT);
2323
+ return true;
2324
+ }
2325
+ catch {
2326
+ return false;
2327
+ }
2328
+ }
2329
+ /**
2330
+ * Check if consent has been explicitly set
2331
+ */
2332
+ function hasStoredConsent() {
2333
+ return loadConsent() !== null;
2334
+ }
2335
+
2336
+ /**
2337
+ * Clianta SDK - Consent Manager
2338
+ * Manages consent state and event buffering for GDPR/CCPA compliance
2339
+ * @see SDK_VERSION in core/config.ts
2340
+ */
2341
+ /** Maximum events to buffer while waiting for consent */
2342
+ const MAX_BUFFER_SIZE = 100;
2343
+ /**
2344
+ * Manages user consent state for tracking
2345
+ */
2346
+ class ConsentManager {
2347
+ constructor(config = {}) {
2348
+ this.eventBuffer = [];
2349
+ this.callbacks = [];
2350
+ this.hasExplicitConsent = false;
2351
+ this.config = {
2352
+ defaultConsent: { analytics: true, marketing: false, personalization: false },
2353
+ waitForConsent: false,
2354
+ storageKey: 'mb_consent',
2355
+ ...config,
2356
+ };
2357
+ // Load stored consent or use default
2358
+ const stored = loadConsent();
2359
+ if (stored) {
2360
+ this.state = stored.state;
2361
+ this.hasExplicitConsent = true;
2362
+ logger.debug('Loaded stored consent:', this.state);
2363
+ }
2364
+ else {
2365
+ this.state = this.config.defaultConsent || { analytics: true };
2366
+ this.hasExplicitConsent = false;
2367
+ logger.debug('Using default consent:', this.state);
2368
+ }
2369
+ // Register callback if provided
2370
+ if (config.onConsentChange) {
2371
+ this.callbacks.push(config.onConsentChange);
2372
+ }
2373
+ }
2374
+ /**
2375
+ * Grant consent for specified categories
2376
+ */
2377
+ grant(categories) {
2378
+ const previous = { ...this.state };
2379
+ this.state = { ...this.state, ...categories };
2380
+ this.hasExplicitConsent = true;
2381
+ saveConsent(this.state);
2382
+ logger.info('Consent granted:', categories);
2383
+ this.notifyChange(previous);
2384
+ }
2385
+ /**
2386
+ * Revoke consent for specified categories
2387
+ */
2388
+ revoke(categories) {
2389
+ const previous = { ...this.state };
2390
+ for (const category of categories) {
2391
+ this.state[category] = false;
2392
+ }
2393
+ this.hasExplicitConsent = true;
2394
+ saveConsent(this.state);
2395
+ logger.info('Consent revoked:', categories);
2396
+ this.notifyChange(previous);
2397
+ }
2398
+ /**
2399
+ * Update entire consent state
2400
+ */
2401
+ update(state) {
2402
+ const previous = { ...this.state };
2403
+ this.state = { ...state };
2404
+ this.hasExplicitConsent = true;
2405
+ saveConsent(this.state);
2406
+ logger.info('Consent updated:', this.state);
2407
+ this.notifyChange(previous);
2408
+ }
2409
+ /**
2410
+ * Reset consent to default (clear stored consent)
2411
+ */
2412
+ reset() {
2413
+ const previous = { ...this.state };
2414
+ this.state = this.config.defaultConsent || { analytics: true };
2415
+ this.hasExplicitConsent = false;
2416
+ this.eventBuffer = [];
2417
+ clearConsent();
2418
+ logger.info('Consent reset to defaults');
2419
+ this.notifyChange(previous);
2420
+ }
2421
+ /**
2422
+ * Get current consent state
2423
+ */
2424
+ getState() {
2425
+ return { ...this.state };
2426
+ }
2427
+ /**
2428
+ * Check if a specific consent category is granted
2429
+ */
2430
+ hasConsent(category) {
2431
+ return this.state[category] === true;
2432
+ }
2433
+ /**
2434
+ * Check if analytics consent is granted (most common check)
2435
+ */
2436
+ canTrack() {
2437
+ // If waiting for consent and no explicit consent given, cannot track
2438
+ if (this.config.waitForConsent && !this.hasExplicitConsent) {
2439
+ return false;
2440
+ }
2441
+ return this.state.analytics === true;
2442
+ }
2443
+ /**
2444
+ * Check if explicit consent has been given
2445
+ */
2446
+ hasExplicit() {
2447
+ return this.hasExplicitConsent;
2448
+ }
2449
+ /**
2450
+ * Check if there's stored consent
2451
+ */
2452
+ hasStored() {
2453
+ return hasStoredConsent();
2454
+ }
2455
+ /**
2456
+ * Buffer an event (for waitForConsent mode)
2457
+ */
2458
+ bufferEvent(event) {
2459
+ // Prevent unbounded buffer growth
2460
+ if (this.eventBuffer.length >= MAX_BUFFER_SIZE) {
2461
+ logger.warn('Consent event buffer full, dropping oldest event');
2462
+ this.eventBuffer.shift();
2463
+ }
2464
+ this.eventBuffer.push(event);
2465
+ logger.debug('Event buffered (waiting for consent):', event.eventName);
2466
+ }
2467
+ /**
2468
+ * Get and clear buffered events
2469
+ */
2470
+ flushBuffer() {
2471
+ const events = [...this.eventBuffer];
2472
+ this.eventBuffer = [];
2473
+ if (events.length > 0) {
2474
+ logger.debug(`Flushing ${events.length} buffered events`);
2475
+ }
2476
+ return events;
2477
+ }
2478
+ /**
2479
+ * Get buffered event count
2480
+ */
2481
+ getBufferSize() {
2482
+ return this.eventBuffer.length;
2483
+ }
2484
+ /**
2485
+ * Register a consent change callback
2486
+ */
2487
+ onChange(callback) {
2488
+ this.callbacks.push(callback);
2489
+ // Return unsubscribe function
2490
+ return () => {
2491
+ const index = this.callbacks.indexOf(callback);
2492
+ if (index > -1) {
2493
+ this.callbacks.splice(index, 1);
2494
+ }
2495
+ };
2496
+ }
2497
+ /**
2498
+ * Notify all callbacks of consent change
2499
+ */
2500
+ notifyChange(previous) {
2501
+ for (const callback of this.callbacks) {
2502
+ try {
2503
+ callback(this.state, previous);
2504
+ }
2505
+ catch (error) {
2506
+ logger.error('Consent change callback error:', error);
2507
+ }
2508
+ }
2509
+ }
2510
+ }
2511
+
2512
+ /**
2513
+ * Clianta SDK - Event Triggers Manager
2514
+ * Manages event-driven automation and email notifications
2515
+ */
2516
+ /**
2517
+ * Event Triggers Manager
2518
+ * Handles event-driven automation based on CRM actions
2519
+ *
2520
+ * Similar to:
2521
+ * - Salesforce: Process Builder, Flow Automation
2522
+ * - HubSpot: Workflows, Email Sequences
2523
+ * - Pipedrive: Workflow Automation
2524
+ */
2525
+ class EventTriggersManager {
2526
+ constructor(apiEndpoint, workspaceId, authToken) {
2527
+ this.triggers = new Map();
2528
+ this.listeners = new Map();
2529
+ this.apiEndpoint = apiEndpoint;
2530
+ this.workspaceId = workspaceId;
2531
+ this.authToken = authToken;
2532
+ }
2533
+ /**
2534
+ * Set authentication token
2535
+ */
2536
+ setAuthToken(token) {
2537
+ this.authToken = token;
2538
+ }
2539
+ /**
2540
+ * Make authenticated API request
2541
+ */
2542
+ async request(endpoint, options = {}) {
2543
+ const url = `${this.apiEndpoint}${endpoint}`;
2544
+ const headers = {
2545
+ 'Content-Type': 'application/json',
2546
+ ...(options.headers || {}),
2547
+ };
2548
+ if (this.authToken) {
2549
+ headers['Authorization'] = `Bearer ${this.authToken}`;
2550
+ }
2551
+ try {
2552
+ const response = await fetch(url, {
2553
+ ...options,
2554
+ headers,
2555
+ });
2556
+ const data = await response.json();
2557
+ if (!response.ok) {
2558
+ return {
2559
+ success: false,
2560
+ error: data.message || 'Request failed',
2561
+ status: response.status,
2562
+ };
2563
+ }
2564
+ return {
2565
+ success: true,
2566
+ data: data.data || data,
2567
+ status: response.status,
2568
+ };
2569
+ }
2570
+ catch (error) {
2571
+ return {
2572
+ success: false,
2573
+ error: error instanceof Error ? error.message : 'Network error',
2574
+ status: 0,
2575
+ };
2576
+ }
2577
+ }
2578
+ // ============================================
2579
+ // TRIGGER MANAGEMENT
2580
+ // ============================================
2581
+ /**
2582
+ * Get all event triggers
2583
+ */
2584
+ async getTriggers() {
2585
+ return this.request(`/api/workspaces/${this.workspaceId}/triggers`);
2586
+ }
2587
+ /**
2588
+ * Get a single trigger by ID
2589
+ */
2590
+ async getTrigger(triggerId) {
2591
+ return this.request(`/api/workspaces/${this.workspaceId}/triggers/${triggerId}`);
2592
+ }
2593
+ /**
2594
+ * Create a new event trigger
2595
+ */
2596
+ async createTrigger(trigger) {
2597
+ const result = await this.request(`/api/workspaces/${this.workspaceId}/triggers`, {
2598
+ method: 'POST',
2599
+ body: JSON.stringify(trigger),
2600
+ });
2601
+ // Cache the trigger locally if successful
2602
+ if (result.success && result.data?._id) {
2603
+ this.triggers.set(result.data._id, result.data);
2604
+ }
2605
+ return result;
2606
+ }
2607
+ /**
2608
+ * Update an existing trigger
2609
+ */
2610
+ async updateTrigger(triggerId, updates) {
2611
+ const result = await this.request(`/api/workspaces/${this.workspaceId}/triggers/${triggerId}`, {
2612
+ method: 'PUT',
2613
+ body: JSON.stringify(updates),
2614
+ });
2615
+ // Update cache if successful
2616
+ if (result.success && result.data?._id) {
2617
+ this.triggers.set(result.data._id, result.data);
2618
+ }
2619
+ return result;
2620
+ }
2621
+ /**
2622
+ * Delete a trigger
2623
+ */
2624
+ async deleteTrigger(triggerId) {
2625
+ const result = await this.request(`/api/workspaces/${this.workspaceId}/triggers/${triggerId}`, {
2626
+ method: 'DELETE',
2627
+ });
2628
+ // Remove from cache if successful
2629
+ if (result.success) {
2630
+ this.triggers.delete(triggerId);
2631
+ }
2632
+ return result;
2633
+ }
2634
+ /**
2635
+ * Activate a trigger
2636
+ */
2637
+ async activateTrigger(triggerId) {
2638
+ return this.updateTrigger(triggerId, { isActive: true });
2639
+ }
2640
+ /**
2641
+ * Deactivate a trigger
2642
+ */
2643
+ async deactivateTrigger(triggerId) {
2644
+ return this.updateTrigger(triggerId, { isActive: false });
2645
+ }
2646
+ // ============================================
2647
+ // EVENT HANDLING (CLIENT-SIDE)
2648
+ // ============================================
2649
+ /**
2650
+ * Register a local event listener for client-side triggers
2651
+ * This allows immediate client-side reactions to events
2652
+ */
2653
+ on(eventType, callback) {
2654
+ if (!this.listeners.has(eventType)) {
2655
+ this.listeners.set(eventType, new Set());
2656
+ }
2657
+ this.listeners.get(eventType).add(callback);
2658
+ logger.debug(`Event listener registered: ${eventType}`);
2659
+ }
2660
+ /**
2661
+ * Remove an event listener
2662
+ */
2663
+ off(eventType, callback) {
2664
+ const listeners = this.listeners.get(eventType);
2665
+ if (listeners) {
2666
+ listeners.delete(callback);
2667
+ }
2668
+ }
2669
+ /**
2670
+ * Emit an event (client-side only)
2671
+ * This will trigger any registered local listeners
2672
+ */
2673
+ emit(eventType, data) {
2674
+ logger.debug(`Event emitted: ${eventType}`, data);
2675
+ const listeners = this.listeners.get(eventType);
2676
+ if (listeners) {
2677
+ listeners.forEach(callback => {
2678
+ try {
2679
+ callback(data);
2680
+ }
2681
+ catch (error) {
2682
+ logger.error(`Error in event listener for ${eventType}:`, error);
2683
+ }
2684
+ });
2685
+ }
2686
+ }
2687
+ /**
2688
+ * Check if conditions are met for a trigger
2689
+ * Supports dynamic field evaluation including custom fields and nested paths
2690
+ */
2691
+ evaluateConditions(conditions, data) {
2692
+ if (!conditions || conditions.length === 0) {
2693
+ return true; // No conditions means always fire
2694
+ }
2695
+ return conditions.every(condition => {
2696
+ // Support dot notation for nested fields (e.g., 'customFields.industry')
2697
+ const fieldValue = condition.field.includes('.')
2698
+ ? this.getNestedValue(data, condition.field)
2699
+ : data[condition.field];
2700
+ const targetValue = condition.value;
2701
+ switch (condition.operator) {
2702
+ case 'equals':
2703
+ return fieldValue === targetValue;
2704
+ case 'not_equals':
2705
+ return fieldValue !== targetValue;
2706
+ case 'contains':
2707
+ return String(fieldValue).includes(String(targetValue));
2708
+ case 'greater_than':
2709
+ return Number(fieldValue) > Number(targetValue);
2710
+ case 'less_than':
2711
+ return Number(fieldValue) < Number(targetValue);
2712
+ case 'in':
2713
+ return Array.isArray(targetValue) && targetValue.includes(fieldValue);
2714
+ case 'not_in':
2715
+ return Array.isArray(targetValue) && !targetValue.includes(fieldValue);
2716
+ default:
2717
+ return false;
2718
+ }
2719
+ });
2720
+ }
2721
+ /**
2722
+ * Execute actions for a triggered event (client-side preview)
2723
+ * Note: Actual execution happens on the backend
2724
+ */
2725
+ async executeActions(trigger, data) {
2726
+ logger.info(`Executing actions for trigger: ${trigger.name}`);
2727
+ for (const action of trigger.actions) {
2728
+ try {
2729
+ await this.executeAction(action, data);
2730
+ }
2731
+ catch (error) {
2732
+ logger.error(`Failed to execute action:`, error);
2733
+ }
2734
+ }
2735
+ }
2736
+ /**
2737
+ * Execute a single action
2738
+ */
2739
+ async executeAction(action, data) {
2740
+ switch (action.type) {
2741
+ case 'send_email':
2742
+ await this.executeSendEmail(action, data);
2743
+ break;
2744
+ case 'webhook':
2745
+ await this.executeWebhook(action, data);
2746
+ break;
2747
+ case 'create_task':
2748
+ await this.executeCreateTask(action, data);
2749
+ break;
2750
+ case 'update_contact':
2751
+ await this.executeUpdateContact(action, data);
2752
+ break;
2753
+ default:
2754
+ logger.warn(`Unknown action type:`, action);
2755
+ }
2756
+ }
2757
+ /**
2758
+ * Execute send email action (via backend API)
2759
+ */
2760
+ async executeSendEmail(action, data) {
2761
+ logger.debug('Sending email:', action);
2762
+ const payload = {
2763
+ to: this.replaceVariables(action.to, data),
2764
+ subject: action.subject ? this.replaceVariables(action.subject, data) : undefined,
2765
+ body: action.body ? this.replaceVariables(action.body, data) : undefined,
2766
+ templateId: action.templateId,
2767
+ cc: action.cc,
2768
+ bcc: action.bcc,
2769
+ from: action.from,
2770
+ delayMinutes: action.delayMinutes,
2771
+ };
2772
+ await this.request(`/api/workspaces/${this.workspaceId}/emails/send`, {
2773
+ method: 'POST',
2774
+ body: JSON.stringify(payload),
2775
+ });
2776
+ }
2777
+ /**
2778
+ * Execute webhook action
2779
+ */
2780
+ async executeWebhook(action, data) {
2781
+ logger.debug('Calling webhook:', action.url);
2782
+ const body = action.body ? this.replaceVariables(action.body, data) : JSON.stringify(data);
2783
+ await fetch(action.url, {
2784
+ method: action.method,
2785
+ headers: {
2786
+ 'Content-Type': 'application/json',
2787
+ ...action.headers,
2788
+ },
2789
+ body,
2790
+ });
2791
+ }
2792
+ /**
2793
+ * Execute create task action
2794
+ */
2795
+ async executeCreateTask(action, data) {
2796
+ logger.debug('Creating task:', action.title);
2797
+ const dueDate = action.dueDays
2798
+ ? new Date(Date.now() + action.dueDays * 24 * 60 * 60 * 1000).toISOString()
2799
+ : undefined;
2800
+ await this.request(`/api/workspaces/${this.workspaceId}/tasks`, {
2801
+ method: 'POST',
2802
+ body: JSON.stringify({
2803
+ title: this.replaceVariables(action.title, data),
2804
+ description: action.description ? this.replaceVariables(action.description, data) : undefined,
2805
+ priority: action.priority,
2806
+ dueDate,
2807
+ assignedTo: action.assignedTo,
2808
+ relatedContactId: typeof data.contactId === 'string' ? data.contactId : undefined,
2809
+ }),
2810
+ });
2811
+ }
2812
+ /**
2813
+ * Execute update contact action
2814
+ */
2815
+ async executeUpdateContact(action, data) {
2816
+ const contactId = data.contactId || data._id;
2817
+ if (!contactId) {
2818
+ logger.warn('Cannot update contact: no contactId in data');
2819
+ return;
2820
+ }
2821
+ logger.debug('Updating contact:', contactId);
2822
+ await this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`, {
2823
+ method: 'PUT',
2824
+ body: JSON.stringify(action.updates),
2825
+ });
2826
+ }
2827
+ /**
2828
+ * Replace variables in a string template
2829
+ * Supports syntax like {{contact.email}}, {{opportunity.value}}
2830
+ */
2831
+ replaceVariables(template, data) {
2832
+ return template.replace(/\{\{([^}]+)\}\}/g, (match, path) => {
2833
+ const value = this.getNestedValue(data, path.trim());
2834
+ return value !== undefined ? String(value) : match;
2835
+ });
2836
+ }
2837
+ /**
2838
+ * Get nested value from object using dot notation
2839
+ * Supports dynamic field access including custom fields
2840
+ */
2841
+ getNestedValue(obj, path) {
2842
+ return path.split('.').reduce((current, key) => {
2843
+ return current !== null && current !== undefined && typeof current === 'object'
2844
+ ? current[key]
2845
+ : undefined;
2846
+ }, obj);
2847
+ }
2848
+ /**
2849
+ * Extract all available field paths from a data object
2850
+ * Useful for dynamic field discovery based on platform-specific attributes
2851
+ * @param obj - The data object to extract fields from
2852
+ * @param prefix - Internal use for nested paths
2853
+ * @param maxDepth - Maximum depth to traverse (default: 3)
2854
+ * @returns Array of field paths (e.g., ['email', 'contact.firstName', 'customFields.industry'])
2855
+ */
2856
+ extractAvailableFields(obj, prefix = '', maxDepth = 3) {
2857
+ if (maxDepth <= 0)
2858
+ return [];
2859
+ const fields = [];
2860
+ for (const key in obj) {
2861
+ if (!obj.hasOwnProperty(key))
2862
+ continue;
2863
+ const value = obj[key];
2864
+ const fieldPath = prefix ? `${prefix}.${key}` : key;
2865
+ fields.push(fieldPath);
2866
+ // Recursively traverse nested objects
2867
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
2868
+ const nestedFields = this.extractAvailableFields(value, fieldPath, maxDepth - 1);
2869
+ fields.push(...nestedFields);
2870
+ }
2871
+ }
2872
+ return fields;
2873
+ }
2874
+ /**
2875
+ * Get available fields from sample data
2876
+ * Helps with dynamic field detection for platform-specific attributes
2877
+ * @param sampleData - Sample data object to analyze
2878
+ * @returns Array of available field paths
2879
+ */
2880
+ getAvailableFields(sampleData) {
2881
+ return this.extractAvailableFields(sampleData);
2882
+ }
2883
+ // ============================================
2884
+ // HELPER METHODS FOR COMMON PATTERNS
2885
+ // ============================================
2886
+ /**
2887
+ * Create a simple email trigger
2888
+ * Helper method for common use case
2889
+ */
2890
+ async createEmailTrigger(config) {
2891
+ return this.createTrigger({
2892
+ name: config.name,
2893
+ eventType: config.eventType,
2894
+ conditions: config.conditions,
2895
+ actions: [
2896
+ {
2897
+ type: 'send_email',
2898
+ to: config.to,
2899
+ subject: config.subject,
2900
+ body: config.body,
2901
+ },
2902
+ ],
2903
+ isActive: true,
2904
+ });
2905
+ }
2906
+ /**
2907
+ * Create a task creation trigger
2908
+ */
2909
+ async createTaskTrigger(config) {
2910
+ return this.createTrigger({
2911
+ name: config.name,
2912
+ eventType: config.eventType,
2913
+ conditions: config.conditions,
2914
+ actions: [
2915
+ {
2916
+ type: 'create_task',
2917
+ title: config.taskTitle,
2918
+ description: config.taskDescription,
2919
+ priority: config.priority,
2920
+ dueDays: config.dueDays,
2921
+ },
2922
+ ],
2923
+ isActive: true,
2924
+ });
2925
+ }
2926
+ /**
2927
+ * Create a webhook trigger
2928
+ */
2929
+ async createWebhookTrigger(config) {
2930
+ return this.createTrigger({
2931
+ name: config.name,
2932
+ eventType: config.eventType,
2933
+ conditions: config.conditions,
2934
+ actions: [
2935
+ {
2936
+ type: 'webhook',
2937
+ url: config.webhookUrl,
2938
+ method: config.method || 'POST',
2939
+ },
2940
+ ],
2941
+ isActive: true,
2942
+ });
2943
+ }
2944
+ }
2945
+
2946
+ /**
2947
+ * Clianta SDK - CRM API Client
2948
+ * @see SDK_VERSION in core/config.ts
2949
+ */
2950
+ /**
2951
+ * CRM API Client for managing contacts and opportunities
2952
+ */
2953
+ class CRMClient {
2954
+ constructor(apiEndpoint, workspaceId, authToken, apiKey) {
2955
+ this.apiEndpoint = apiEndpoint;
2956
+ this.workspaceId = workspaceId;
2957
+ this.authToken = authToken;
2958
+ this.apiKey = apiKey;
2959
+ this.triggers = new EventTriggersManager(apiEndpoint, workspaceId, authToken);
2960
+ }
2961
+ /**
2962
+ * Set authentication token for API requests (user JWT)
2963
+ */
2964
+ setAuthToken(token) {
2965
+ this.authToken = token;
2966
+ this.apiKey = undefined;
2967
+ this.triggers.setAuthToken(token);
2968
+ }
2969
+ /**
2970
+ * Set workspace API key for server-to-server requests.
2971
+ * Use this instead of setAuthToken when integrating from an external app.
2972
+ */
2973
+ setApiKey(key) {
2974
+ this.apiKey = key;
2975
+ this.authToken = undefined;
2976
+ }
2977
+ /**
2978
+ * Validate required parameter exists
2979
+ * @throws {Error} if value is null/undefined or empty string
2980
+ */
2981
+ validateRequired(param, value, methodName) {
2982
+ if (value === null || value === undefined || value === '') {
2983
+ throw new Error(`[CRMClient.${methodName}] ${param} is required`);
2984
+ }
2985
+ }
2986
+ /**
2987
+ * Make authenticated API request
2988
+ */
2989
+ async request(endpoint, options = {}) {
2990
+ const url = `${this.apiEndpoint}${endpoint}`;
2991
+ const headers = {
2992
+ 'Content-Type': 'application/json',
2993
+ ...(options.headers || {}),
2994
+ };
2995
+ if (this.apiKey) {
2996
+ headers['X-Api-Key'] = this.apiKey;
2997
+ }
2998
+ else if (this.authToken) {
2999
+ headers['Authorization'] = `Bearer ${this.authToken}`;
3000
+ }
3001
+ try {
3002
+ const response = await fetch(url, {
3003
+ ...options,
3004
+ headers,
3005
+ });
3006
+ const data = await response.json();
3007
+ if (!response.ok) {
3008
+ return {
3009
+ success: false,
3010
+ error: data.message || 'Request failed',
3011
+ status: response.status,
3012
+ };
3013
+ }
3014
+ return {
3015
+ success: true,
3016
+ data: data.data || data,
3017
+ status: response.status,
3018
+ };
3019
+ }
3020
+ catch (error) {
3021
+ return {
3022
+ success: false,
3023
+ error: error instanceof Error ? error.message : 'Network error',
3024
+ status: 0,
3025
+ };
3026
+ }
3027
+ }
3028
+ // ============================================
3029
+ // INBOUND EVENTS API (API-key authenticated)
3030
+ // ============================================
3031
+ /**
3032
+ * Send an inbound event from an external app (e.g. user signup on client website).
3033
+ * Requires the client to be initialized with an API key via setApiKey() or the constructor.
3034
+ *
3035
+ * The contact is upserted in the CRM and matching workflow automations fire automatically.
3036
+ *
3037
+ * @example
3038
+ * const crm = new CRMClient('http://localhost:5000', 'WORKSPACE_ID');
3039
+ * crm.setApiKey('mm_live_...');
3040
+ *
3041
+ * await crm.sendEvent({
3042
+ * event: 'user.registered',
3043
+ * contact: { email: 'alice@example.com', firstName: 'Alice' },
3044
+ * data: { plan: 'free', signupSource: 'homepage' },
3045
+ * });
3046
+ */
3047
+ async sendEvent(payload) {
3048
+ const url = `${this.apiEndpoint}/api/public/events`;
3049
+ const headers = { 'Content-Type': 'application/json' };
3050
+ if (this.apiKey) {
3051
+ headers['X-Api-Key'] = this.apiKey;
3052
+ }
3053
+ else if (this.authToken) {
3054
+ headers['Authorization'] = `Bearer ${this.authToken}`;
3055
+ }
3056
+ try {
3057
+ const response = await fetch(url, {
3058
+ method: 'POST',
3059
+ headers,
3060
+ body: JSON.stringify(payload),
3061
+ });
3062
+ const data = await response.json();
3063
+ if (!response.ok) {
3064
+ return {
3065
+ success: false,
3066
+ contactCreated: false,
3067
+ event: payload.event,
3068
+ error: data.error || 'Request failed',
3069
+ };
3070
+ }
3071
+ return {
3072
+ success: data.success,
3073
+ contactCreated: data.contactCreated,
3074
+ contactId: data.contactId,
3075
+ event: data.event,
3076
+ };
3077
+ }
3078
+ catch (error) {
3079
+ return {
3080
+ success: false,
3081
+ contactCreated: false,
3082
+ event: payload.event,
3083
+ error: error instanceof Error ? error.message : 'Network error',
3084
+ };
3085
+ }
3086
+ }
3087
+ // ============================================
3088
+ // CONTACTS API
3089
+ // ============================================
3090
+ /**
3091
+ * Get all contacts with pagination
3092
+ */
3093
+ async getContacts(params) {
3094
+ const queryParams = new URLSearchParams();
3095
+ if (params?.page)
3096
+ queryParams.set('page', params.page.toString());
3097
+ if (params?.limit)
3098
+ queryParams.set('limit', params.limit.toString());
3099
+ if (params?.search)
3100
+ queryParams.set('search', params.search);
3101
+ if (params?.status)
3102
+ queryParams.set('status', params.status);
3103
+ const query = queryParams.toString();
3104
+ const endpoint = `/api/workspaces/${this.workspaceId}/contacts${query ? `?${query}` : ''}`;
3105
+ return this.request(endpoint);
3106
+ }
3107
+ /**
3108
+ * Get a single contact by ID
3109
+ */
3110
+ async getContact(contactId) {
3111
+ this.validateRequired('contactId', contactId, 'getContact');
3112
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`);
3113
+ }
3114
+ /**
3115
+ * Create a new contact
3116
+ */
3117
+ async createContact(contact) {
3118
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts`, {
3119
+ method: 'POST',
3120
+ body: JSON.stringify(contact),
3121
+ });
3122
+ }
3123
+ /**
3124
+ * Update an existing contact
3125
+ */
3126
+ async updateContact(contactId, updates) {
3127
+ this.validateRequired('contactId', contactId, 'updateContact');
3128
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`, {
3129
+ method: 'PUT',
3130
+ body: JSON.stringify(updates),
3131
+ });
3132
+ }
3133
+ /**
3134
+ * Delete a contact
3135
+ */
3136
+ async deleteContact(contactId) {
3137
+ this.validateRequired('contactId', contactId, 'deleteContact');
3138
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`, {
3139
+ method: 'DELETE',
3140
+ });
3141
+ }
3142
+ // ============================================
3143
+ // OPPORTUNITIES API
3144
+ // ============================================
3145
+ /**
3146
+ * Get all opportunities with pagination
3147
+ */
3148
+ async getOpportunities(params) {
3149
+ const queryParams = new URLSearchParams();
3150
+ if (params?.page)
3151
+ queryParams.set('page', params.page.toString());
3152
+ if (params?.limit)
3153
+ queryParams.set('limit', params.limit.toString());
3154
+ if (params?.pipelineId)
3155
+ queryParams.set('pipelineId', params.pipelineId);
3156
+ if (params?.stageId)
3157
+ queryParams.set('stageId', params.stageId);
3158
+ const query = queryParams.toString();
3159
+ const endpoint = `/api/workspaces/${this.workspaceId}/opportunities${query ? `?${query}` : ''}`;
3160
+ return this.request(endpoint);
3161
+ }
3162
+ /**
3163
+ * Get a single opportunity by ID
3164
+ */
3165
+ async getOpportunity(opportunityId) {
3166
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}`);
3167
+ }
3168
+ /**
3169
+ * Create a new opportunity
3170
+ */
3171
+ async createOpportunity(opportunity) {
3172
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities`, {
3173
+ method: 'POST',
3174
+ body: JSON.stringify(opportunity),
3175
+ });
3176
+ }
3177
+ /**
3178
+ * Update an existing opportunity
3179
+ */
3180
+ async updateOpportunity(opportunityId, updates) {
3181
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}`, {
3182
+ method: 'PUT',
3183
+ body: JSON.stringify(updates),
3184
+ });
3185
+ }
3186
+ /**
3187
+ * Delete an opportunity
3188
+ */
3189
+ async deleteOpportunity(opportunityId) {
3190
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}`, {
3191
+ method: 'DELETE',
3192
+ });
3193
+ }
3194
+ /**
3195
+ * Move opportunity to a different stage
3196
+ */
3197
+ async moveOpportunity(opportunityId, stageId) {
3198
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}/move`, {
3199
+ method: 'POST',
3200
+ body: JSON.stringify({ stageId }),
3201
+ });
3202
+ }
3203
+ // ============================================
3204
+ // COMPANIES API
3205
+ // ============================================
3206
+ /**
3207
+ * Get all companies with pagination
3208
+ */
3209
+ async getCompanies(params) {
3210
+ const queryParams = new URLSearchParams();
3211
+ if (params?.page)
3212
+ queryParams.set('page', params.page.toString());
3213
+ if (params?.limit)
3214
+ queryParams.set('limit', params.limit.toString());
3215
+ if (params?.search)
3216
+ queryParams.set('search', params.search);
3217
+ if (params?.status)
3218
+ queryParams.set('status', params.status);
3219
+ if (params?.industry)
3220
+ queryParams.set('industry', params.industry);
3221
+ const query = queryParams.toString();
3222
+ const endpoint = `/api/workspaces/${this.workspaceId}/companies${query ? `?${query}` : ''}`;
3223
+ return this.request(endpoint);
3224
+ }
3225
+ /**
3226
+ * Get a single company by ID
3227
+ */
3228
+ async getCompany(companyId) {
3229
+ return this.request(`/api/workspaces/${this.workspaceId}/companies/${companyId}`);
3230
+ }
3231
+ /**
3232
+ * Create a new company
3233
+ */
3234
+ async createCompany(company) {
3235
+ return this.request(`/api/workspaces/${this.workspaceId}/companies`, {
3236
+ method: 'POST',
3237
+ body: JSON.stringify(company),
3238
+ });
3239
+ }
3240
+ /**
3241
+ * Update an existing company
3242
+ */
3243
+ async updateCompany(companyId, updates) {
3244
+ return this.request(`/api/workspaces/${this.workspaceId}/companies/${companyId}`, {
3245
+ method: 'PUT',
3246
+ body: JSON.stringify(updates),
3247
+ });
3248
+ }
3249
+ /**
3250
+ * Delete a company
3251
+ */
3252
+ async deleteCompany(companyId) {
3253
+ return this.request(`/api/workspaces/${this.workspaceId}/companies/${companyId}`, {
3254
+ method: 'DELETE',
3255
+ });
3256
+ }
3257
+ /**
3258
+ * Get contacts belonging to a company
3259
+ */
3260
+ async getCompanyContacts(companyId, params) {
3261
+ const queryParams = new URLSearchParams();
3262
+ if (params?.page)
3263
+ queryParams.set('page', params.page.toString());
3264
+ if (params?.limit)
3265
+ queryParams.set('limit', params.limit.toString());
3266
+ const query = queryParams.toString();
3267
+ const endpoint = `/api/workspaces/${this.workspaceId}/companies/${companyId}/contacts${query ? `?${query}` : ''}`;
3268
+ return this.request(endpoint);
3269
+ }
3270
+ /**
3271
+ * Get deals/opportunities belonging to a company
3272
+ */
3273
+ async getCompanyDeals(companyId, params) {
3274
+ const queryParams = new URLSearchParams();
3275
+ if (params?.page)
3276
+ queryParams.set('page', params.page.toString());
3277
+ if (params?.limit)
3278
+ queryParams.set('limit', params.limit.toString());
3279
+ const query = queryParams.toString();
3280
+ const endpoint = `/api/workspaces/${this.workspaceId}/companies/${companyId}/deals${query ? `?${query}` : ''}`;
3281
+ return this.request(endpoint);
3282
+ }
3283
+ // ============================================
3284
+ // PIPELINES API
3285
+ // ============================================
3286
+ /**
3287
+ * Get all pipelines
3288
+ */
3289
+ async getPipelines() {
3290
+ return this.request(`/api/workspaces/${this.workspaceId}/pipelines`);
3291
+ }
3292
+ /**
3293
+ * Get a single pipeline by ID
3294
+ */
3295
+ async getPipeline(pipelineId) {
3296
+ return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${pipelineId}`);
3297
+ }
3298
+ /**
3299
+ * Create a new pipeline
3300
+ */
3301
+ async createPipeline(pipeline) {
3302
+ return this.request(`/api/workspaces/${this.workspaceId}/pipelines`, {
3303
+ method: 'POST',
3304
+ body: JSON.stringify(pipeline),
3305
+ });
3306
+ }
3307
+ /**
3308
+ * Update an existing pipeline
3309
+ */
3310
+ async updatePipeline(pipelineId, updates) {
3311
+ return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${pipelineId}`, {
3312
+ method: 'PUT',
3313
+ body: JSON.stringify(updates),
3314
+ });
3315
+ }
3316
+ /**
3317
+ * Delete a pipeline
3318
+ */
3319
+ async deletePipeline(pipelineId) {
3320
+ return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${pipelineId}`, {
3321
+ method: 'DELETE',
3322
+ });
3323
+ }
3324
+ // ============================================
3325
+ // TASKS API
3326
+ // ============================================
3327
+ /**
3328
+ * Get all tasks with pagination
3329
+ */
3330
+ async getTasks(params) {
3331
+ const queryParams = new URLSearchParams();
3332
+ if (params?.page)
3333
+ queryParams.set('page', params.page.toString());
3334
+ if (params?.limit)
3335
+ queryParams.set('limit', params.limit.toString());
3336
+ if (params?.status)
3337
+ queryParams.set('status', params.status);
3338
+ if (params?.priority)
3339
+ queryParams.set('priority', params.priority);
3340
+ if (params?.contactId)
3341
+ queryParams.set('contactId', params.contactId);
3342
+ if (params?.companyId)
3343
+ queryParams.set('companyId', params.companyId);
3344
+ if (params?.opportunityId)
3345
+ queryParams.set('opportunityId', params.opportunityId);
3346
+ const query = queryParams.toString();
3347
+ const endpoint = `/api/workspaces/${this.workspaceId}/tasks${query ? `?${query}` : ''}`;
3348
+ return this.request(endpoint);
3349
+ }
3350
+ /**
3351
+ * Get a single task by ID
3352
+ */
3353
+ async getTask(taskId) {
3354
+ return this.request(`/api/workspaces/${this.workspaceId}/tasks/${taskId}`);
3355
+ }
3356
+ /**
3357
+ * Create a new task
3358
+ */
3359
+ async createTask(task) {
3360
+ return this.request(`/api/workspaces/${this.workspaceId}/tasks`, {
3361
+ method: 'POST',
3362
+ body: JSON.stringify(task),
3363
+ });
3364
+ }
3365
+ /**
3366
+ * Update an existing task
3367
+ */
3368
+ async updateTask(taskId, updates) {
3369
+ return this.request(`/api/workspaces/${this.workspaceId}/tasks/${taskId}`, {
3370
+ method: 'PUT',
3371
+ body: JSON.stringify(updates),
3372
+ });
3373
+ }
3374
+ /**
3375
+ * Mark a task as completed
3376
+ */
3377
+ async completeTask(taskId) {
3378
+ return this.request(`/api/workspaces/${this.workspaceId}/tasks/${taskId}/complete`, {
3379
+ method: 'PATCH',
3380
+ });
3381
+ }
3382
+ /**
3383
+ * Delete a task
3384
+ */
3385
+ async deleteTask(taskId) {
3386
+ return this.request(`/api/workspaces/${this.workspaceId}/tasks/${taskId}`, {
3387
+ method: 'DELETE',
3388
+ });
3389
+ }
3390
+ // ============================================
3391
+ // ACTIVITIES API
3392
+ // ============================================
3393
+ /**
3394
+ * Get activities for a contact
3395
+ */
3396
+ async getContactActivities(contactId, params) {
3397
+ const queryParams = new URLSearchParams();
3398
+ if (params?.page)
3399
+ queryParams.set('page', params.page.toString());
3400
+ if (params?.limit)
3401
+ queryParams.set('limit', params.limit.toString());
3402
+ if (params?.type)
3403
+ queryParams.set('type', params.type);
3404
+ const query = queryParams.toString();
3405
+ const endpoint = `/api/workspaces/${this.workspaceId}/contacts/${contactId}/activities${query ? `?${query}` : ''}`;
3406
+ return this.request(endpoint);
3407
+ }
3408
+ /**
3409
+ * Get activities for an opportunity/deal
3410
+ */
3411
+ async getOpportunityActivities(opportunityId, params) {
3412
+ const queryParams = new URLSearchParams();
3413
+ if (params?.page)
3414
+ queryParams.set('page', params.page.toString());
3415
+ if (params?.limit)
3416
+ queryParams.set('limit', params.limit.toString());
3417
+ if (params?.type)
3418
+ queryParams.set('type', params.type);
3419
+ const query = queryParams.toString();
3420
+ const endpoint = `/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}/activities${query ? `?${query}` : ''}`;
3421
+ return this.request(endpoint);
3422
+ }
3423
+ /**
3424
+ * Create a new activity
3425
+ */
3426
+ async createActivity(activity) {
3427
+ // Determine the correct endpoint based on related entity
3428
+ let endpoint;
3429
+ if (activity.opportunityId) {
3430
+ endpoint = `/api/workspaces/${this.workspaceId}/opportunities/${activity.opportunityId}/activities`;
3431
+ }
3432
+ else if (activity.contactId) {
3433
+ endpoint = `/api/workspaces/${this.workspaceId}/contacts/${activity.contactId}/activities`;
3434
+ }
3435
+ else {
3436
+ endpoint = `/api/workspaces/${this.workspaceId}/activities`;
3437
+ }
3438
+ return this.request(endpoint, {
3439
+ method: 'POST',
3440
+ body: JSON.stringify(activity),
3441
+ });
3442
+ }
3443
+ /**
3444
+ * Update an existing activity
3445
+ */
3446
+ async updateActivity(activityId, updates) {
3447
+ return this.request(`/api/workspaces/${this.workspaceId}/activities/${activityId}`, {
3448
+ method: 'PATCH',
3449
+ body: JSON.stringify(updates),
3450
+ });
3451
+ }
3452
+ /**
3453
+ * Delete an activity
3454
+ */
3455
+ async deleteActivity(activityId) {
3456
+ return this.request(`/api/workspaces/${this.workspaceId}/activities/${activityId}`, {
3457
+ method: 'DELETE',
3458
+ });
3459
+ }
3460
+ /**
3461
+ * Log a call activity
3462
+ */
3463
+ async logCall(data) {
3464
+ return this.createActivity({
3465
+ type: 'call',
3466
+ title: `${data.direction === 'inbound' ? 'Inbound' : 'Outbound'} Call`,
3467
+ direction: data.direction,
3468
+ duration: data.duration,
3469
+ outcome: data.outcome,
3470
+ description: data.notes,
3471
+ contactId: data.contactId,
3472
+ opportunityId: data.opportunityId,
3473
+ });
3474
+ }
3475
+ /**
3476
+ * Log a meeting activity
3477
+ */
3478
+ async logMeeting(data) {
3479
+ return this.createActivity({
3480
+ type: 'meeting',
3481
+ title: data.title,
3482
+ duration: data.duration,
3483
+ outcome: data.outcome,
3484
+ description: data.notes,
3485
+ contactId: data.contactId,
3486
+ opportunityId: data.opportunityId,
3487
+ });
3488
+ }
3489
+ /**
3490
+ * Add a note to a contact or opportunity
3491
+ */
3492
+ async addNote(data) {
3493
+ return this.createActivity({
3494
+ type: 'note',
3495
+ title: 'Note',
3496
+ description: data.content,
3497
+ contactId: data.contactId,
3498
+ opportunityId: data.opportunityId,
3499
+ });
3500
+ }
3501
+ // ============================================
3502
+ // EMAIL TEMPLATES API
3503
+ // ============================================
3504
+ /**
3505
+ * Get all email templates
3506
+ */
3507
+ async getEmailTemplates(params) {
3508
+ const queryParams = new URLSearchParams();
3509
+ if (params?.page)
3510
+ queryParams.set('page', params.page.toString());
3511
+ if (params?.limit)
3512
+ queryParams.set('limit', params.limit.toString());
3513
+ const query = queryParams.toString();
3514
+ const endpoint = `/api/workspaces/${this.workspaceId}/email-templates${query ? `?${query}` : ''}`;
3515
+ return this.request(endpoint);
3516
+ }
3517
+ /**
3518
+ * Get a single email template by ID
3519
+ */
3520
+ async getEmailTemplate(templateId) {
3521
+ return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${templateId}`);
3522
+ }
3523
+ /**
3524
+ * Create a new email template
3525
+ */
3526
+ async createEmailTemplate(template) {
3527
+ return this.request(`/api/workspaces/${this.workspaceId}/email-templates`, {
3528
+ method: 'POST',
3529
+ body: JSON.stringify(template),
3530
+ });
3531
+ }
3532
+ /**
3533
+ * Update an email template
3534
+ */
3535
+ async updateEmailTemplate(templateId, updates) {
3536
+ return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${templateId}`, {
3537
+ method: 'PUT',
3538
+ body: JSON.stringify(updates),
3539
+ });
3540
+ }
3541
+ /**
3542
+ * Delete an email template
3543
+ */
3544
+ async deleteEmailTemplate(templateId) {
3545
+ return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${templateId}`, {
3546
+ method: 'DELETE',
3547
+ });
3548
+ }
3549
+ /**
3550
+ * Send an email using a template
3551
+ */
3552
+ async sendEmail(data) {
3553
+ return this.request(`/api/workspaces/${this.workspaceId}/emails/send`, {
3554
+ method: 'POST',
3555
+ body: JSON.stringify(data),
3556
+ });
3557
+ }
3558
+ // ============================================
3559
+ // READ-BACK / DATA RETRIEVAL API
3560
+ // ============================================
3561
+ /**
3562
+ * Get a contact by email address.
3563
+ * Returns the first matching contact from a search query.
3564
+ */
3565
+ async getContactByEmail(email) {
3566
+ this.validateRequired('email', email, 'getContactByEmail');
3567
+ const queryParams = new URLSearchParams({ search: email, limit: '1' });
3568
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts?${queryParams.toString()}`);
3569
+ }
3570
+ /**
3571
+ * Get activity timeline for a contact
3572
+ */
3573
+ async getContactActivity(contactId, params) {
3574
+ this.validateRequired('contactId', contactId, 'getContactActivity');
3575
+ const queryParams = new URLSearchParams();
3576
+ if (params?.page)
3577
+ queryParams.set('page', params.page.toString());
3578
+ if (params?.limit)
3579
+ queryParams.set('limit', params.limit.toString());
3580
+ if (params?.type)
3581
+ queryParams.set('type', params.type);
3582
+ if (params?.startDate)
3583
+ queryParams.set('startDate', params.startDate);
3584
+ if (params?.endDate)
3585
+ queryParams.set('endDate', params.endDate);
3586
+ const query = queryParams.toString();
3587
+ const endpoint = `/api/workspaces/${this.workspaceId}/contacts/${contactId}/activities${query ? `?${query}` : ''}`;
3588
+ return this.request(endpoint);
3589
+ }
3590
+ /**
3591
+ * Get engagement metrics for a contact (via their linked visitor data)
3592
+ */
3593
+ async getContactEngagement(contactId) {
3594
+ this.validateRequired('contactId', contactId, 'getContactEngagement');
3595
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}/engagement`);
3596
+ }
3597
+ /**
3598
+ * Get a full timeline for a contact including events, activities, and opportunities
3599
+ */
3600
+ async getContactTimeline(contactId, params) {
3601
+ this.validateRequired('contactId', contactId, 'getContactTimeline');
3602
+ const queryParams = new URLSearchParams();
3603
+ if (params?.page)
3604
+ queryParams.set('page', params.page.toString());
3605
+ if (params?.limit)
3606
+ queryParams.set('limit', params.limit.toString());
3607
+ const query = queryParams.toString();
3608
+ const endpoint = `/api/workspaces/${this.workspaceId}/contacts/${contactId}/timeline${query ? `?${query}` : ''}`;
3609
+ return this.request(endpoint);
3610
+ }
3611
+ /**
3612
+ * Search contacts with advanced filters
3613
+ */
3614
+ async searchContacts(query, filters) {
3615
+ const queryParams = new URLSearchParams();
3616
+ queryParams.set('search', query);
3617
+ if (filters?.status)
3618
+ queryParams.set('status', filters.status);
3619
+ if (filters?.lifecycleStage)
3620
+ queryParams.set('lifecycleStage', filters.lifecycleStage);
3621
+ if (filters?.source)
3622
+ queryParams.set('source', filters.source);
3623
+ if (filters?.tags)
3624
+ queryParams.set('tags', filters.tags.join(','));
3625
+ if (filters?.page)
3626
+ queryParams.set('page', filters.page.toString());
3627
+ if (filters?.limit)
3628
+ queryParams.set('limit', filters.limit.toString());
3629
+ const qs = queryParams.toString();
3630
+ const endpoint = `/api/workspaces/${this.workspaceId}/contacts${qs ? `?${qs}` : ''}`;
3631
+ return this.request(endpoint);
3632
+ }
3633
+ // ============================================
3634
+ // WEBHOOK MANAGEMENT API
3635
+ // ============================================
3636
+ /**
3637
+ * List all webhook subscriptions
3638
+ */
3639
+ async listWebhooks(params) {
3640
+ const queryParams = new URLSearchParams();
3641
+ if (params?.page)
3642
+ queryParams.set('page', params.page.toString());
3643
+ if (params?.limit)
3644
+ queryParams.set('limit', params.limit.toString());
3645
+ const query = queryParams.toString();
3646
+ return this.request(`/api/workspaces/${this.workspaceId}/webhooks${query ? `?${query}` : ''}`);
3647
+ }
3648
+ /**
3649
+ * Create a new webhook subscription
3650
+ */
3651
+ async createWebhook(data) {
3652
+ return this.request(`/api/workspaces/${this.workspaceId}/webhooks`, {
3653
+ method: 'POST',
3654
+ body: JSON.stringify(data),
3655
+ });
3656
+ }
3657
+ /**
3658
+ * Delete a webhook subscription
3659
+ */
3660
+ async deleteWebhook(webhookId) {
3661
+ this.validateRequired('webhookId', webhookId, 'deleteWebhook');
3662
+ return this.request(`/api/workspaces/${this.workspaceId}/webhooks/${webhookId}`, {
3663
+ method: 'DELETE',
3664
+ });
3665
+ }
3666
+ // ============================================
3667
+ // EVENT TRIGGERS API (delegated to triggers manager)
3668
+ // ============================================
3669
+ /**
3670
+ * Get all event triggers
3671
+ */
3672
+ async getEventTriggers() {
3673
+ return this.triggers.getTriggers();
3674
+ }
3675
+ /**
3676
+ * Create a new event trigger
3677
+ */
3678
+ async createEventTrigger(trigger) {
3679
+ return this.triggers.createTrigger(trigger);
3680
+ }
3681
+ /**
3682
+ * Update an event trigger
3683
+ */
3684
+ async updateEventTrigger(triggerId, updates) {
3685
+ return this.triggers.updateTrigger(triggerId, updates);
3686
+ }
3687
+ /**
3688
+ * Delete an event trigger
3689
+ */
3690
+ async deleteEventTrigger(triggerId) {
3691
+ return this.triggers.deleteTrigger(triggerId);
3692
+ }
3693
+ }
3694
+
3695
+ /**
3696
+ * Clianta SDK - Main Tracker Class
3697
+ * @see SDK_VERSION in core/config.ts
3698
+ */
3699
+ /**
3700
+ * Main Clianta Tracker Class
3701
+ */
3702
+ class Tracker {
3703
+ constructor(workspaceId, userConfig = {}) {
3704
+ this.plugins = [];
3705
+ this.isInitialized = false;
3706
+ /** contactId after a successful identify() call */
3707
+ this.contactId = null;
3708
+ /** Pending identify retry on next flush */
3709
+ this.pendingIdentify = null;
3710
+ /** Registered event schemas for validation */
3711
+ this.eventSchemas = new Map();
3712
+ if (!workspaceId) {
3713
+ throw new Error('[Clianta] Workspace ID is required');
3714
+ }
3715
+ this.workspaceId = workspaceId;
3716
+ this.config = mergeConfig(userConfig);
3717
+ // Setup debug mode
3718
+ logger.enabled = this.config.debug;
3719
+ logger.info(`Initializing SDK v${SDK_VERSION}`, { workspaceId });
3720
+ // Initialize consent manager
3721
+ this.consentManager = new ConsentManager({
3722
+ ...this.config.consent,
3723
+ onConsentChange: (state, previous) => {
3724
+ this.onConsentChange(state, previous);
3725
+ },
3726
+ });
3727
+ // Initialize transport and queue
3728
+ this.transport = new Transport({ apiEndpoint: this.config.apiEndpoint });
3729
+ this.queue = new EventQueue(this.transport, {
3730
+ batchSize: this.config.batchSize,
3731
+ flushInterval: this.config.flushInterval,
3732
+ });
3733
+ // Get or create visitor and session IDs based on mode
3734
+ this.visitorId = this.createVisitorId();
3735
+ this.sessionId = this.createSessionId();
3736
+ logger.debug('IDs created', { visitorId: this.visitorId, sessionId: this.sessionId });
3737
+ // Security warnings
3738
+ if (this.config.apiEndpoint.startsWith('http://') &&
3739
+ typeof window !== 'undefined' &&
3740
+ !window.location.hostname.includes('localhost') &&
3741
+ !window.location.hostname.includes('127.0.0.1')) {
3742
+ logger.warn('apiEndpoint uses HTTP — events and visitor data will be sent unencrypted. Use HTTPS in production.');
3743
+ }
3744
+ if (this.config.apiKey && typeof window !== 'undefined') {
3745
+ logger.warn('API key is exposed in client-side code. Use API keys only in server-side (Node.js) environments.');
3746
+ }
3747
+ // Initialize plugins
3748
+ this.initPlugins();
3749
+ this.isInitialized = true;
3750
+ logger.info('SDK initialized successfully');
3751
+ }
3752
+ /**
3753
+ * Create visitor ID based on storage mode
3754
+ */
3755
+ createVisitorId() {
3756
+ // Anonymous mode: use temporary ID until consent
3757
+ if (this.config.consent.anonymousMode && !this.consentManager.hasExplicit()) {
3758
+ const key = STORAGE_KEYS.VISITOR_ID + '_anon';
3759
+ let anonId = getSessionStorage(key);
3760
+ if (!anonId) {
3761
+ anonId = 'anon_' + generateUUID();
3762
+ setSessionStorage(key, anonId);
3763
+ }
3764
+ return anonId;
3765
+ }
3766
+ // Cookie-less mode: use sessionStorage only
3767
+ if (this.config.cookielessMode) {
3768
+ let visitorId = getSessionStorage(STORAGE_KEYS.VISITOR_ID);
3769
+ if (!visitorId) {
3770
+ visitorId = generateUUID();
3771
+ setSessionStorage(STORAGE_KEYS.VISITOR_ID, visitorId);
3772
+ }
3773
+ return visitorId;
3774
+ }
3775
+ // Normal mode
3776
+ return getOrCreateVisitorId(this.config.useCookies);
3777
+ }
3778
+ /**
3779
+ * Create session ID
3780
+ */
3781
+ createSessionId() {
3782
+ return getOrCreateSessionId(this.config.sessionTimeout);
3783
+ }
3784
+ /**
3785
+ * Handle consent state changes
3786
+ */
3787
+ onConsentChange(state, previous) {
3788
+ logger.debug('Consent changed:', { from: previous, to: state });
3789
+ // If analytics consent was just granted
3790
+ if (state.analytics && !previous.analytics) {
3791
+ // Upgrade from anonymous ID to persistent ID
3792
+ if (this.config.consent.anonymousMode) {
3793
+ this.visitorId = getOrCreateVisitorId(this.config.useCookies);
3794
+ logger.info('Upgraded from anonymous to persistent visitor ID');
3795
+ }
3796
+ // Flush buffered events
3797
+ const buffered = this.consentManager.flushBuffer();
3798
+ for (const event of buffered) {
3799
+ // Update event with new visitor ID
3800
+ event.visitorId = this.visitorId;
3801
+ this.queue.push(event);
3802
+ }
3803
+ }
3804
+ }
3805
+ /**
3806
+ * Initialize enabled plugins
3807
+ * Handles both sync and async plugin init methods
3808
+ */
3809
+ initPlugins() {
3810
+ const pluginsToLoad = this.config.plugins;
3811
+ // Skip pageView plugin if autoPageView is disabled
3812
+ const filteredPlugins = this.config.autoPageView
3813
+ ? pluginsToLoad
3814
+ : pluginsToLoad.filter((p) => p !== 'pageView');
3815
+ for (const pluginName of filteredPlugins) {
3816
+ try {
3817
+ const plugin = getPlugin(pluginName);
3818
+ // Handle both sync and async init (fire-and-forget for async)
3819
+ const result = plugin.init(this);
3820
+ if (result instanceof Promise) {
3821
+ result.catch((error) => {
3822
+ logger.error(`Async plugin init failed: ${pluginName}`, error);
3823
+ });
3824
+ }
3825
+ this.plugins.push(plugin);
3826
+ logger.debug(`Plugin loaded: ${pluginName}`);
3827
+ }
3828
+ catch (error) {
3829
+ logger.error(`Failed to load plugin: ${pluginName}`, error);
3830
+ }
3831
+ }
3832
+ }
3833
+ /**
3834
+ * Track a custom event
3835
+ */
3836
+ track(eventType, eventName, properties = {}) {
3837
+ if (!this.isInitialized) {
3838
+ logger.warn('SDK not initialized, event dropped');
3839
+ return;
3840
+ }
3841
+ const event = {
3842
+ workspaceId: this.workspaceId,
3843
+ visitorId: this.visitorId,
3844
+ sessionId: this.sessionId,
3845
+ eventType: eventType,
3846
+ eventName,
3847
+ url: typeof window !== 'undefined' ? window.location.href : '',
3848
+ referrer: typeof document !== 'undefined' ? document.referrer || undefined : undefined,
3849
+ properties: {
3850
+ ...properties,
3851
+ eventId: generateUUID(), // Unique ID for deduplication on retry
3852
+ websiteDomain: typeof window !== 'undefined' ? window.location.hostname : undefined,
3853
+ },
3854
+ device: getDeviceInfo(),
3855
+ ...getUTMParams(),
3856
+ timestamp: new Date().toISOString(),
3857
+ sdkVersion: SDK_VERSION,
3858
+ };
3859
+ // Attach contactId if known (from a prior identify() call)
3860
+ if (this.contactId) {
3861
+ event.contactId = this.contactId;
3862
+ }
3863
+ // Validate event against registered schema (debug mode only)
3864
+ this.validateEventSchema(eventType, properties);
3865
+ // Check consent before tracking
3866
+ if (!this.consentManager.canTrack()) {
3867
+ // Buffer event for later if waitForConsent is enabled
3868
+ if (this.config.consent.waitForConsent) {
3869
+ this.consentManager.bufferEvent(event);
3870
+ return;
3871
+ }
3872
+ // Otherwise drop the event
3873
+ logger.debug('Event dropped (no consent):', eventName);
3874
+ return;
3875
+ }
3876
+ this.queue.push(event);
3877
+ logger.debug('Event tracked:', eventName, properties);
3878
+ }
3879
+ /**
3880
+ * Track a page view
3881
+ */
3882
+ page(name, properties = {}) {
3883
+ const pageName = name || (typeof document !== 'undefined' ? document.title : 'Page View');
3884
+ this.track('page_view', pageName, {
3885
+ ...properties,
3886
+ path: typeof window !== 'undefined' ? window.location.pathname : '',
3887
+ });
3888
+ }
3889
+ /**
3890
+ * Identify a visitor.
3891
+ * Links the anonymous visitorId to a CRM contact and returns the contactId.
3892
+ * All subsequent track() calls will include the contactId automatically.
3893
+ */
3894
+ async identify(email, traits = {}) {
3895
+ if (!email) {
3896
+ logger.warn('Email is required for identification');
3897
+ return null;
3898
+ }
3899
+ if (!isValidEmail(email)) {
3900
+ logger.warn('Invalid email format, identification skipped:', email);
3901
+ return null;
3902
+ }
3903
+ logger.info('Identifying visitor:', email);
3904
+ const result = await this.transport.sendIdentify({
3905
+ workspaceId: this.workspaceId,
3906
+ visitorId: this.visitorId,
3907
+ email,
3908
+ properties: traits,
3909
+ });
3910
+ if (result.success) {
3911
+ logger.info('Visitor identified successfully, contactId:', result.contactId);
3912
+ // Store contactId so all future track() calls include it
3913
+ this.contactId = result.contactId ?? null;
3914
+ this.pendingIdentify = null;
3915
+ return this.contactId;
3916
+ }
3917
+ else {
3918
+ logger.error('Failed to identify visitor:', result.error);
3919
+ // Store for retry on next flush
3920
+ this.pendingIdentify = { email, traits };
3921
+ return null;
3922
+ }
3923
+ }
3924
+ /**
3925
+ * Send a server-side inbound event via the API key endpoint.
3926
+ * Convenience proxy to CRMClient.sendEvent() — requires apiKey in config.
3927
+ */
3928
+ async sendEvent(payload) {
3929
+ const apiKey = this.config.apiKey;
3930
+ if (!apiKey) {
3931
+ logger.error('sendEvent() requires an apiKey in the SDK config');
3932
+ return { success: false, contactCreated: false, event: payload.event, error: 'No API key configured' };
3933
+ }
3934
+ const client = new CRMClient(this.config.apiEndpoint, this.workspaceId, undefined, apiKey);
3935
+ return client.sendEvent(payload);
3936
+ }
3937
+ /**
3938
+ * Get the current visitor's profile from the CRM.
3939
+ * Returns visitor data and linked contact info if identified.
3940
+ * Only returns data for the current visitor (privacy-safe for frontend).
3941
+ */
3942
+ async getVisitorProfile() {
3943
+ if (!this.isInitialized) {
3944
+ logger.warn('SDK not initialized');
3945
+ return null;
3946
+ }
3947
+ const result = await this.transport.fetchData(`/api/public/track/visitor/${this.workspaceId}/${this.visitorId}/profile`);
3948
+ if (result.success && result.data) {
3949
+ logger.debug('Visitor profile fetched:', result.data);
3950
+ return result.data;
3951
+ }
3952
+ logger.warn('Failed to fetch visitor profile:', result.error);
3953
+ return null;
3954
+ }
3955
+ /**
3956
+ * Get the current visitor's recent activity/events.
3957
+ * Returns paginated list of tracking events for this visitor.
3958
+ */
3959
+ async getVisitorActivity(options) {
3960
+ if (!this.isInitialized) {
3961
+ logger.warn('SDK not initialized');
3962
+ return null;
3963
+ }
3964
+ const params = {};
3965
+ if (options?.page)
3966
+ params.page = options.page.toString();
3967
+ if (options?.limit)
3968
+ params.limit = options.limit.toString();
3969
+ if (options?.eventType)
3970
+ params.eventType = options.eventType;
3971
+ if (options?.startDate)
3972
+ params.startDate = options.startDate;
3973
+ if (options?.endDate)
3974
+ params.endDate = options.endDate;
3975
+ const result = await this.transport.fetchData(`/api/public/track/visitor/${this.workspaceId}/${this.visitorId}/activity`, params);
3976
+ if (result.success && result.data) {
3977
+ return result.data;
3978
+ }
3979
+ logger.warn('Failed to fetch visitor activity:', result.error);
3980
+ return null;
3981
+ }
3982
+ /**
3983
+ * Get a summarized journey timeline for the current visitor.
3984
+ * Includes top pages, sessions, time spent, and recent activities.
3985
+ */
3986
+ async getVisitorTimeline() {
3987
+ if (!this.isInitialized) {
3988
+ logger.warn('SDK not initialized');
3989
+ return null;
3990
+ }
3991
+ const result = await this.transport.fetchData(`/api/public/track/visitor/${this.workspaceId}/${this.visitorId}/timeline`);
3992
+ if (result.success && result.data) {
3993
+ return result.data;
3994
+ }
3995
+ logger.warn('Failed to fetch visitor timeline:', result.error);
3996
+ return null;
3997
+ }
3998
+ /**
3999
+ * Get engagement metrics for the current visitor.
4000
+ * Includes time on site, page views, bounce rate, and engagement score.
4001
+ */
4002
+ async getVisitorEngagement() {
4003
+ if (!this.isInitialized) {
4004
+ logger.warn('SDK not initialized');
4005
+ return null;
4006
+ }
4007
+ const result = await this.transport.fetchData(`/api/public/track/visitor/${this.workspaceId}/${this.visitorId}/engagement`);
4008
+ if (result.success && result.data) {
4009
+ return result.data;
4010
+ }
4011
+ logger.warn('Failed to fetch visitor engagement:', result.error);
4012
+ return null;
4013
+ }
4014
+ /**
4015
+ * Retry pending identify call
4016
+ */
4017
+ async retryPendingIdentify() {
4018
+ if (!this.pendingIdentify)
4019
+ return;
4020
+ const { email, traits } = this.pendingIdentify;
4021
+ this.pendingIdentify = null;
4022
+ await this.identify(email, traits);
4023
+ }
4024
+ /**
4025
+ * Update consent state
4026
+ */
4027
+ consent(state) {
4028
+ this.consentManager.update(state);
4029
+ }
4030
+ /**
4031
+ * Get current consent state
4032
+ */
4033
+ getConsentState() {
4034
+ return this.consentManager.getState();
4035
+ }
4036
+ /**
4037
+ * Toggle debug mode
4038
+ */
4039
+ debug(enabled) {
4040
+ logger.enabled = enabled;
4041
+ logger.info(`Debug mode ${enabled ? 'enabled' : 'disabled'}`);
4042
+ }
4043
+ /**
4044
+ * Register a schema for event validation.
4045
+ * When debug mode is enabled, events will be validated against registered schemas.
4046
+ *
4047
+ * @example
4048
+ * tracker.registerEventSchema('purchase', {
4049
+ * productId: 'string',
4050
+ * price: 'number',
4051
+ * quantity: 'number',
4052
+ * });
4053
+ */
4054
+ registerEventSchema(eventType, schema) {
4055
+ this.eventSchemas.set(eventType, schema);
4056
+ logger.debug('Event schema registered:', eventType);
4057
+ }
4058
+ /**
4059
+ * Validate event properties against a registered schema (debug mode only)
4060
+ */
4061
+ validateEventSchema(eventType, properties) {
4062
+ if (!this.config.debug)
4063
+ return;
4064
+ const schema = this.eventSchemas.get(eventType);
4065
+ if (!schema)
4066
+ return;
4067
+ for (const [key, expectedType] of Object.entries(schema)) {
4068
+ const value = properties[key];
4069
+ if (value === undefined) {
4070
+ logger.warn(`[Schema] Missing property "${key}" for event type "${eventType}"`);
4071
+ continue;
4072
+ }
4073
+ let valid = false;
4074
+ switch (expectedType) {
4075
+ case 'string':
4076
+ valid = typeof value === 'string';
4077
+ break;
4078
+ case 'number':
4079
+ valid = typeof value === 'number';
4080
+ break;
4081
+ case 'boolean':
4082
+ valid = typeof value === 'boolean';
4083
+ break;
4084
+ case 'object':
4085
+ valid = typeof value === 'object' && !Array.isArray(value);
4086
+ break;
4087
+ case 'array':
4088
+ valid = Array.isArray(value);
4089
+ break;
4090
+ }
4091
+ if (!valid) {
4092
+ logger.warn(`[Schema] Property "${key}" for event "${eventType}" expected ${expectedType}, got ${typeof value}`);
4093
+ }
4094
+ }
4095
+ }
4096
+ /**
4097
+ * Get visitor ID
4098
+ */
4099
+ getVisitorId() {
4100
+ return this.visitorId;
4101
+ }
4102
+ /**
4103
+ * Get session ID
4104
+ */
4105
+ getSessionId() {
4106
+ return this.sessionId;
4107
+ }
4108
+ /**
4109
+ * Get workspace ID
4110
+ */
4111
+ getWorkspaceId() {
4112
+ return this.workspaceId;
4113
+ }
4114
+ /**
4115
+ * Get current configuration
4116
+ */
4117
+ getConfig() {
4118
+ return { ...this.config };
4119
+ }
4120
+ /**
4121
+ * Force flush event queue
4122
+ */
4123
+ async flush() {
4124
+ await this.retryPendingIdentify();
4125
+ await this.queue.flush();
4126
+ }
4127
+ /**
4128
+ * Reset visitor and session (for logout)
4129
+ */
4130
+ reset() {
4131
+ logger.info('Resetting visitor data');
4132
+ resetIds(this.config.useCookies);
4133
+ this.visitorId = this.createVisitorId();
4134
+ this.sessionId = this.createSessionId();
4135
+ this.contactId = null;
4136
+ this.pendingIdentify = null;
4137
+ this.queue.clear();
4138
+ }
4139
+ /**
4140
+ * Delete all stored user data (GDPR right-to-erasure)
4141
+ */
4142
+ deleteData() {
4143
+ logger.info('Deleting all user data (GDPR request)');
4144
+ // Clear queue
4145
+ this.queue.clear();
4146
+ // Reset consent
4147
+ this.consentManager.reset();
4148
+ // Clear all stored IDs
4149
+ resetIds(this.config.useCookies);
4150
+ // Clear session storage items
4151
+ if (typeof sessionStorage !== 'undefined') {
4152
+ try {
4153
+ sessionStorage.removeItem(STORAGE_KEYS.VISITOR_ID);
4154
+ sessionStorage.removeItem(STORAGE_KEYS.VISITOR_ID + '_anon');
4155
+ sessionStorage.removeItem(STORAGE_KEYS.SESSION_ID);
4156
+ sessionStorage.removeItem(STORAGE_KEYS.SESSION_TIMESTAMP);
4157
+ }
4158
+ catch {
4159
+ // Ignore errors
4160
+ }
4161
+ }
4162
+ // Clear localStorage items
4163
+ if (typeof localStorage !== 'undefined') {
4164
+ try {
4165
+ localStorage.removeItem(STORAGE_KEYS.VISITOR_ID);
4166
+ localStorage.removeItem(STORAGE_KEYS.CONSENT);
4167
+ localStorage.removeItem(STORAGE_KEYS.EVENT_QUEUE);
4168
+ }
4169
+ catch {
4170
+ // Ignore errors
4171
+ }
4172
+ }
4173
+ // Generate new IDs
4174
+ this.visitorId = this.createVisitorId();
4175
+ this.sessionId = this.createSessionId();
4176
+ logger.info('All user data deleted');
4177
+ }
4178
+ // ============================================
4179
+ // PUBLIC CRM METHODS (no API key required)
4180
+ // ============================================
4181
+ /**
4182
+ * Create or update a contact by email (upsert).
4183
+ * Secured by domain whitelist — no API key needed.
4184
+ */
4185
+ async createContact(data) {
4186
+ return this.publicCrmRequest('/api/public/crm/contacts', 'POST', {
4187
+ workspaceId: this.workspaceId,
4188
+ ...data,
4189
+ });
4190
+ }
4191
+ /**
4192
+ * Update an existing contact by ID (limited fields only).
4193
+ */
4194
+ async updateContact(contactId, data) {
4195
+ return this.publicCrmRequest(`/api/public/crm/contacts/${contactId}`, 'PUT', {
4196
+ workspaceId: this.workspaceId,
4197
+ ...data,
4198
+ });
4199
+ }
4200
+ /**
4201
+ * Submit a form — creates/updates contact from form data.
4202
+ */
4203
+ async submitForm(formId, data) {
4204
+ const payload = {
4205
+ ...data,
4206
+ metadata: {
4207
+ ...data.metadata,
4208
+ visitorId: this.visitorId,
4209
+ sessionId: this.sessionId,
4210
+ pageUrl: typeof window !== 'undefined' ? window.location.href : undefined,
4211
+ referrer: typeof document !== 'undefined' ? document.referrer || undefined : undefined,
4212
+ },
4213
+ };
4214
+ return this.publicCrmRequest(`/api/public/crm/forms/${formId}/submit`, 'POST', payload);
4215
+ }
4216
+ /**
4217
+ * Log an activity linked to a contact (append-only).
4218
+ */
4219
+ async logActivity(data) {
4220
+ return this.publicCrmRequest('/api/public/crm/activities', 'POST', {
4221
+ workspaceId: this.workspaceId,
4222
+ ...data,
4223
+ });
4224
+ }
4225
+ /**
4226
+ * Create an opportunity (e.g., from "Request Demo" forms).
4227
+ */
4228
+ async createOpportunity(data) {
4229
+ return this.publicCrmRequest('/api/public/crm/opportunities', 'POST', {
4230
+ workspaceId: this.workspaceId,
4231
+ ...data,
4232
+ });
4233
+ }
4234
+ /**
4235
+ * Internal helper for public CRM API calls.
4236
+ */
4237
+ async publicCrmRequest(path, method, body) {
4238
+ const url = `${this.config.apiEndpoint}${path}`;
4239
+ try {
4240
+ const response = await fetch(url, {
4241
+ method,
4242
+ headers: { 'Content-Type': 'application/json' },
4243
+ body: JSON.stringify(body),
4244
+ });
4245
+ const data = await response.json().catch(() => ({}));
4246
+ if (response.ok) {
4247
+ logger.debug(`Public CRM ${method} ${path} succeeded`);
4248
+ return { success: true, data: data.data ?? data, status: response.status };
4249
+ }
4250
+ logger.error(`Public CRM ${method} ${path} failed (${response.status}):`, data.message);
4251
+ return { success: false, error: data.message, status: response.status };
4252
+ }
4253
+ catch (error) {
4254
+ logger.error(`Public CRM ${method} ${path} error:`, error);
4255
+ return { success: false, error: error.message };
4256
+ }
4257
+ }
4258
+ /**
4259
+ * Destroy tracker and cleanup
4260
+ */
4261
+ async destroy() {
4262
+ logger.info('Destroying tracker');
4263
+ // Flush any remaining events (await to ensure completion)
4264
+ await this.queue.flush();
4265
+ // Destroy plugins
4266
+ for (const plugin of this.plugins) {
4267
+ if (plugin.destroy) {
4268
+ plugin.destroy();
4269
+ }
4270
+ }
4271
+ this.plugins = [];
4272
+ // Destroy queue
4273
+ this.queue.destroy();
4274
+ this.isInitialized = false;
4275
+ }
4276
+ }
4277
+
4278
+ /**
4279
+ * Clianta SDK
4280
+ * Professional CRM and tracking SDK for lead generation
4281
+ * @see SDK_VERSION in core/config.ts
4282
+ */
4283
+ // Global instance cache
4284
+ let globalInstance = null;
4285
+ /**
4286
+ * Initialize or get the Clianta tracker instance
4287
+ *
4288
+ * @example
4289
+ * // Simple initialization
4290
+ * const tracker = clianta('your-workspace-id');
4291
+ *
4292
+ * @example
4293
+ * // With configuration
4294
+ * const tracker = clianta('your-workspace-id', {
4295
+ * debug: true,
4296
+ * plugins: ['pageView', 'forms', 'scroll'],
4297
+ * });
4298
+ *
4299
+ * @example
4300
+ * // With consent configuration
4301
+ * const tracker = clianta('your-workspace-id', {
4302
+ * consent: {
4303
+ * waitForConsent: true,
4304
+ * anonymousMode: true,
4305
+ * },
4306
+ * cookielessMode: true, // GDPR-friendly mode
4307
+ * });
4308
+ */
4309
+ function clianta(workspaceId, config) {
4310
+ // Return existing instance if same workspace
4311
+ if (globalInstance && globalInstance.getWorkspaceId() === workspaceId) {
4312
+ return globalInstance;
4313
+ }
4314
+ // Destroy existing instance if workspace changed
4315
+ if (globalInstance) {
4316
+ globalInstance.destroy();
4317
+ }
4318
+ // Create new instance
4319
+ globalInstance = new Tracker(workspaceId, config);
4320
+ return globalInstance;
4321
+ }
4322
+ // Attach to window for <script> usage
4323
+ if (typeof window !== 'undefined') {
4324
+ window.clianta = clianta;
4325
+ window.Clianta = {
4326
+ clianta,
4327
+ Tracker,
4328
+ CRMClient,
4329
+ ConsentManager,
4330
+ EventTriggersManager,
4331
+ };
4332
+ }
4333
+
4334
+ /**
4335
+ * Clianta SDK - Angular Integration
4336
+ *
4337
+ * Provides helpers for Angular 16+ integration.
4338
+ * Since Angular uses decorators and DI that require @angular/core as a dependency,
4339
+ * this module provides a factory pattern that Angular users wrap in their own service.
4340
+ *
4341
+ * @example
4342
+ * // In your Angular service:
4343
+ * import { Injectable, OnDestroy } from '@angular/core';
4344
+ * import { createCliantaTracker, type CliantaTrackerInstance } from '@clianta/sdk/angular';
4345
+ *
4346
+ * @Injectable({ providedIn: 'root' })
4347
+ * export class CliantaService implements OnDestroy {
4348
+ * private instance: CliantaTrackerInstance;
4349
+ *
4350
+ * constructor() {
4351
+ * this.instance = createCliantaTracker({
4352
+ * projectId: environment.cliantaProjectId,
4353
+ * apiEndpoint: environment.cliantaApiEndpoint,
4354
+ * debug: !environment.production,
4355
+ * });
4356
+ * }
4357
+ *
4358
+ * get tracker() { return this.instance.tracker; }
4359
+ *
4360
+ * track(eventType: string, eventName: string, properties?: Record<string, unknown>) {
4361
+ * this.instance.tracker?.track(eventType, eventName, properties);
4362
+ * }
4363
+ *
4364
+ * identify(email: string, traits?: Record<string, unknown>) {
4365
+ * return this.instance.tracker?.identify(email, traits);
4366
+ * }
4367
+ *
4368
+ * ngOnDestroy() {
4369
+ * this.instance.destroy();
4370
+ * }
4371
+ * }
4372
+ */
4373
+ /**
4374
+ * Create a Clianta tracker instance for use in Angular services.
4375
+ *
4376
+ * @param config - Configuration including projectId
4377
+ * @returns Object with tracker instance and destroy method
4378
+ *
4379
+ * @example
4380
+ * const instance = createCliantaTracker({
4381
+ * projectId: 'your-project-id',
4382
+ * apiEndpoint: environment.cliantaApiEndpoint || 'http://localhost:5000',
4383
+ * });
4384
+ *
4385
+ * instance.tracker?.track('page_view', 'Home Page');
4386
+ * // On cleanup:
4387
+ * instance.destroy();
4388
+ */
4389
+ function createCliantaTracker(config) {
4390
+ if (!config.projectId) {
4391
+ console.error('[Clianta] Missing projectId in Angular config');
4392
+ return { tracker: null, destroy: () => { } };
4393
+ }
4394
+ const { projectId, ...options } = config;
4395
+ const tracker = clianta(projectId, options);
4396
+ return {
4397
+ tracker,
4398
+ destroy: async () => {
4399
+ await tracker.destroy();
4400
+ },
4401
+ };
4402
+ }
4403
+ /**
4404
+ * Create a track function bound to a tracker instance.
4405
+ * Useful as a shorthand in Angular components.
4406
+ *
4407
+ * @example
4408
+ * const track = createTrackFn(instance.tracker);
4409
+ * track('button_click', 'CTA Button', { location: 'header' });
4410
+ */
4411
+ function createTrackFn(tracker) {
4412
+ return (eventType, eventName, properties) => {
4413
+ tracker?.track(eventType, eventName, properties);
4414
+ };
4415
+ }
4416
+ /**
4417
+ * Create an identify function bound to a tracker instance.
4418
+ *
4419
+ * @example
4420
+ * const identify = createIdentifyFn(instance.tracker);
4421
+ * identify('user@example.com', { firstName: 'John' });
4422
+ */
4423
+ function createIdentifyFn(tracker) {
4424
+ return (email, traits) => {
4425
+ return tracker?.identify(email, traits);
4426
+ };
4427
+ }
4428
+
4429
+ exports.createCliantaTracker = createCliantaTracker;
4430
+ exports.createIdentifyFn = createIdentifyFn;
4431
+ exports.createTrackFn = createTrackFn;
4432
+ //# sourceMappingURL=angular.cjs.js.map