-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutmtrack.js
More file actions
1405 lines (1236 loc) · 44.4 KB
/
utmtrack.js
File metadata and controls
1405 lines (1236 loc) · 44.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* UTMTrackJS - Biblioteca para capturar, armazenar e preencher automaticamente parâmetros UTM
* @version 0.9.5
* @author Gabriel Masson
* @license MIT
* @repo https://github.com/gmasson/utmtrackjs
*/
((window) => {
'use strict';
// Verificações de compatibilidade do ambiente
if (typeof window === 'undefined' || typeof document === 'undefined') {
console.warn('UTMTrackJS: Esta biblioteca só funciona em ambiente de navegador.');
return;
}
if (typeof Storage === 'undefined') {
console.warn('UTMTrackJS: localStorage não está disponível neste navegador.');
return;
}
// Constantes da aplicação
const CONSTANTS = Object.freeze({
STORAGE_KEY: 'utmtrackjs_last_params',
VERSION: '0.9.5',
MAX_UTM_LENGTH: 500,
MAX_KEY_LENGTH: 50,
MAX_KEYS: 50,
MAX_PARAMS: 50,
MAX_STORAGE_SIZE: 50000, // 50KB
MAX_URL_LENGTH: 2048,
DEFAULT_MAX_DATA_AGE: 7 * 24 * 60 * 60 * 1000, // 7 dias
THROTTLE_DELAY: 50, // ms
ALLOWED_EVENTS: ['input', 'change', 'focus', 'blur'],
ALLOWED_INPUT_TYPES: ['text', 'hidden', 'search', 'url', 'tel', 'email'],
FORM_ELEMENTS: ['input', 'textarea', 'select'],
CUSTOM_EVENTS: {
UTM_CAPTURED: 'utmtrackjs:captured',
UTM_UPDATED: 'utmtrackjs:updated',
UTM_REMOVED: 'utmtrackjs:removed',
CONFIG_CHANGED: 'utmtrackjs:configChanged'
}
});
// Parâmetros UTM suportados
const DEFAULT_UTM_KEYS = Object.freeze([
// UTM padrão
'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'utm_id',
// UTM estendido
'utm_source_platform', 'utm_creative_format', 'utm_marketing_tactic',
// Click IDs de plataformas
'gclid', 'fbclid', 'msclkid', 'ttclid', 'twclid', 'li_fat_id',
// Salesforce Campaign
'sc_campaign', 'sc_channel', 'sc_content', 'sc_medium', 'sc_outcome',
// MailChimp
'mc_cid', 'mc_eid',
// Piwik/Matomo
'pk_campaign', 'pk_kwd', 'pk_medium', 'pk_source'
]);
// Estado global da aplicação
const AppState = (() => {
const state = {
config: {
updateWithLatest: true,
customUtmKeys: null,
maxDataAge: CONSTANTS.DEFAULT_MAX_DATA_AGE,
loggingEnabled: true
},
runtime: {
domContentLoadedListenerAdded: false,
urlChangeListenerAdded: false,
lastUrl: '',
isInitialized: false,
originalHistory: null,
urlListenersBound: false,
eventListeners: new Set()
}
};
return Object.seal(state);
})();
// Verifica configuração pré-definida pelo usuário
if (typeof window.UTMTrackJSConfig === 'object' && window.UTMTrackJSConfig !== null) {
if (typeof window.UTMTrackJSConfig.updateWithLatest === 'boolean') {
AppState.config.updateWithLatest = window.UTMTrackJSConfig.updateWithLatest;
}
if (typeof window.UTMTrackJSConfig.maxDataAge === 'number' || window.UTMTrackJSConfig.maxDataAge === false) {
AppState.config.maxDataAge = window.UTMTrackJSConfig.maxDataAge;
}
if (Array.isArray(window.UTMTrackJSConfig.customUtmKeys)) {
AppState.config.customUtmKeys = window.UTMTrackJSConfig.customUtmKeys;
}
}
// Classes de erro e resultado
class UTMTrackError extends Error {
constructor(message, code = 'GENERAL') {
super(message);
this.name = 'UTMTrackError';
this.code = code;
}
}
class UTMResult {
constructor(success, data = null, error = null) {
this.success = success;
this.data = data;
this.error = error;
}
static success(data = null) {
return new UTMResult(true, data, null);
}
static failure(error) {
return new UTMResult(false, null, error);
}
}
// Módulo de validação e sanitização
const ValidationModule = {
/**
* Valida chave UTM
* @param {string} key - Chave UTM
* @returns {boolean} True se válida
*/
isValidUtmKey(key) {
if (typeof key !== 'string' || !key.trim()) {
return false;
}
const trimmed = key.trim();
if (trimmed.length > CONSTANTS.MAX_KEY_LENGTH) {
return false;
}
return /^[a-zA-Z0-9_]+$/.test(trimmed);
},
/**
* Sanitiza valor UTM usando whitelist de caracteres seguros
* @param {any} value - Valor a ser sanitizado
* @returns {string|null} Valor sanitizado ou null se inválido
*/
sanitizeUtmValue(value) {
if (value === null || value === undefined) {
return null;
}
let sanitized = String(value).trim();
// Whitelist: letras, números, hífen, underscore, ponto, espaço
sanitized = sanitized.replace(/[^a-zA-Z0-9\-_.\s]/g, '');
sanitized = sanitized.replace(/\s+/g, ' ').trim();
if (sanitized.length > CONSTANTS.MAX_UTM_LENGTH) {
console.warn(`UTMTrackJS: Valor UTM truncado (máximo: ${CONSTANTS.MAX_UTM_LENGTH} caracteres)`);
sanitized = sanitized.substring(0, CONSTANTS.MAX_UTM_LENGTH);
}
return sanitized.length > 0 ? sanitized : null;
},
/**
* Valida valor UTM
* @param {any} value - Valor a ser validado
* @returns {boolean} True se válido
*/
isValidUtmValue(value) {
const sanitized = this.sanitizeUtmValue(value);
return sanitized !== null && sanitized.length > 0;
},
/**
* Valida metadados de timestamp e origem
* @param {Object} utms - Objeto com dados UTM e metadados
* @returns {boolean} True se válidos
*/
validateMetadata(utms) {
const now = Date.now();
const tenYearsAgo = now - (10 * 365 * 24 * 60 * 60 * 1000);
// Valida timestamp
if (typeof utms._timestamp !== 'number' || isNaN(utms._timestamp) ||
utms._timestamp <= 0 || utms._timestamp < tenYearsAgo ||
utms._timestamp > now) {
console.warn('UTMTrackJS: Timestamp inválido detectado.');
return false;
}
// Validação de origem (anti-CSRF)
if (utms._origin && typeof utms._origin === 'string') {
try {
const storedOrigin = new URL(utms._origin).origin;
if (storedOrigin !== window.location.origin) {
console.warn('UTMTrackJS: Origem dos dados não confere. Possível CSRF detectado.');
return false;
}
} catch (urlError) {
console.warn('UTMTrackJS: Origem inválida nos dados armazenados.');
return false;
}
}
// Verifica expiração se habilitada
if (AppState.config.maxDataAge !== false && (now - utms._timestamp) > AppState.config.maxDataAge) {
console.warn('UTMTrackJS: Dados no localStorage expirados.');
return false;
}
return true;
},
/**
* Verifica se dados do localStorage são seguros
* @param {Object} utms - Dados do localStorage
* @returns {boolean} True se seguros
*/
validateStoredData(utms) {
if (typeof utms !== 'object' || utms === null || utms.constructor !== Object) {
console.warn('UTMTrackJS: Estrutura de dados inválida detectada.');
return false;
}
// Proteção contra prototype pollution
if (Object.getPrototypeOf(utms) !== Object.prototype) {
console.warn('UTMTrackJS: Prototype pollution detectado.');
return false;
}
// Verifica propriedades perigosas
const dangerousProps = [
'constructor', '__proto__', 'prototype', 'valueOf', 'toString',
'__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__',
'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable'
];
for (const prop of dangerousProps) {
if (utms.hasOwnProperty(prop) && !['_timestamp', '_data', '_origin', '_version'].includes(prop)) {
console.warn(`UTMTrackJS: Propriedade perigosa detectada: ${prop}`);
return false;
}
}
// Validação adicional contra prototype pollution
if (Object.prototype.toString.call(utms) !== '[object Object]') {
console.warn('UTMTrackJS: Objeto suspeito detectado - possível prototype pollution.');
return false;
}
// Verifica limite de chaves
if (Object.keys(utms).length > CONSTANTS.MAX_KEYS) {
console.warn(`UTMTrackJS: Muitas chaves no localStorage (${Object.keys(utms).length}, máximo: ${CONSTANTS.MAX_KEYS})`);
return false;
}
const hasMetadata = utms._timestamp && utms._data;
const dataToValidate = hasMetadata ? utms._data : utms;
// Valida metadata se presente
if (hasMetadata && !this.validateMetadata(utms)) {
return false;
}
// Proteção adicional nos dados
if (hasMetadata && utms._data) {
if (typeof utms._data !== 'object' || Array.isArray(utms._data) || utms._data === null) {
console.warn('UTMTrackJS: Estrutura de _data inválida.');
return false;
}
if (Object.getPrototypeOf(utms._data) !== Object.prototype) {
console.warn('UTMTrackJS: Prototype pollution detectado nos dados.');
return false;
}
}
// Valida cada chave e valor
for (const [key, value] of Object.entries(dataToValidate)) {
if (!this.isValidUtmKey(key) || typeof value !== 'string' || value.length > CONSTANTS.MAX_UTM_LENGTH) {
console.warn(`UTMTrackJS: Dados inválidos para chave ${key}`);
return false;
}
const sanitized = this.sanitizeUtmValue(value);
if (!sanitized || sanitized !== value) {
console.warn(`UTMTrackJS: Valor comprometido encontrado para chave ${key}`);
return false;
}
}
return true;
}
};
// Módulo de log centralizado
const Log = {
info(...args) { if (AppState.config.loggingEnabled) { try { console.log(...args); } catch(_) {} } },
warn(...args) { if (AppState.config.loggingEnabled) { try { console.warn(...args); } catch(_) {} } },
error(...args) { try { console.error(...args); } catch(_) {} }
};
// Módulo de armazenamento localStorage
const StorageModule = {
// Rate limiting para operações de storage
_lastSaveTime: 0,
_saveThrottle: 100, // ms mínimo entre salvamentos
/**
* Verifica se pode realizar operação de salvamento (rate limiting)
*/
_canSave() {
const now = Date.now();
if (now - this._lastSaveTime < this._saveThrottle) {
return false;
}
this._lastSaveTime = now;
return true;
},
/**
* Obtém dados do localStorage com validação de segurança
* @returns {Object|null} Dados UTM ou null se não existirem/inválidos
*/
getStoredData() {
try {
const savedData = localStorage.getItem(CONSTANTS.STORAGE_KEY);
if (!savedData) {
return null;
}
// Validação prévia para evitar ataques
if (typeof savedData !== 'string' || savedData.length > CONSTANTS.MAX_STORAGE_SIZE) {
console.warn('UTMTrackJS: Dados suspeitos no localStorage.');
this.cleanup();
return null;
}
// Verificação básica de estrutura JSON
const firstChar = savedData.trim().charAt(0);
const lastChar = savedData.trim().charAt(savedData.trim().length - 1);
if (firstChar !== '{' || lastChar !== '}') {
console.warn('UTMTrackJS: Estrutura JSON inválida detectada.');
this.cleanup();
return null;
}
// Parse seguro
let parsed;
try {
parsed = JSON.parse(savedData);
} catch (parseError) {
console.warn('UTMTrackJS: Erro ao fazer parse dos dados JSON.', parseError);
this.cleanup();
return null;
}
if (!ValidationModule.validateStoredData(parsed)) {
console.warn('UTMTrackJS: Dados corrompidos ou inseguros no localStorage. Limpando...');
this.cleanup();
return null;
}
// Se tem metadata, retorna apenas os dados
return parsed._timestamp && parsed._data ? parsed._data : parsed;
} catch (error) {
console.error('UTMTrackJS: Erro ao ler do localStorage.', error);
this.cleanup();
return null;
}
},
/**
* Salva dados no localStorage com metadata de segurança
* @param {Object} data - Dados UTM a serem salvos
* @returns {boolean} True se salvou com sucesso
*/
saveStoredData(data) {
try {
// Rate limiting para evitar spam
if (!this._canSave()) {
console.warn('UTMTrackJS: Operação de salvamento muito frequente. Ignorando.');
return false;
}
if (!data || typeof data !== 'object' || Object.keys(data).length > CONSTANTS.MAX_KEYS) {
throw new UTMTrackError('Dados inválidos ou muitos dados para salvamento.', 'INVALID_DATA');
}
const dataWithMetadata = {
_timestamp: Date.now(),
_data: data,
_origin: window.location.origin,
_version: CONSTANTS.VERSION
};
const serialized = JSON.stringify(dataWithMetadata);
if (serialized.length > CONSTANTS.MAX_STORAGE_SIZE) {
throw new UTMTrackError('Dados muito grandes para salvar no localStorage.', 'SIZE_LIMIT');
}
localStorage.setItem(CONSTANTS.STORAGE_KEY, serialized);
return true;
} catch (error) {
console.error('UTMTrackJS: Erro ao salvar no localStorage.', error);
return false;
}
},
/**
* Limpa dados corrompidos do localStorage
*/
cleanup() {
try {
localStorage.removeItem(CONSTANTS.STORAGE_KEY);
} catch (cleanupError) {
console.error('UTMTrackJS: Erro ao limpar localStorage corrompido.', cleanupError);
}
},
/**
* Verifica uso do localStorage e retorna estatísticas
* @returns {Object} Estatísticas de uso do storage
*/
getStorageStats() {
try {
const data = localStorage.getItem(CONSTANTS.STORAGE_KEY);
if (!data) {
return {
exists: false,
size: 0,
sizeInKB: 0,
percentOfLimit: 0
};
}
const sizeInBytes = new Blob([data]).size;
const sizeInKB = Math.round(sizeInBytes / 1024 * 100) / 100;
const percentOfLimit = Math.round((sizeInBytes / CONSTANTS.MAX_STORAGE_SIZE) * 100);
return {
exists: true,
size: sizeInBytes,
sizeInKB,
percentOfLimit,
maxSizeKB: Math.round(CONSTANTS.MAX_STORAGE_SIZE / 1024)
};
} catch (error) {
console.error('UTMTrackJS: Erro ao calcular estatísticas de storage.', error);
return { error: true };
}
}
};
// Módulo de utilitários e helpers
const UtilsModule = {
/**
* Retorna lista ativa de chaves UTM
* @returns {Array} Array com as chaves UTM ativas
*/
getActiveUtmKeys() {
return AppState.config.customUtmKeys || DEFAULT_UTM_KEYS;
},
/**
* Verifica se CSP permite criação de eventos dinâmicos
*/
_checkCSPCompliance() {
try {
const testEvent = new Event('test');
return true;
} catch (error) {
console.warn('UTMTrackJS: CSP pode estar restringindo criação de eventos.');
return false;
}
},
/**
* Dispara eventos de forma segura (compatível com CSP)
* @param {HTMLElement} element - Elemento onde disparar o evento
* @param {string} eventType - Tipo do evento
* @returns {boolean} True se o evento foi disparado com sucesso
*/
dispatchSafeEvent(element, eventType) {
try {
// Whitelist de eventos permitidos
if (!CONSTANTS.ALLOWED_EVENTS.includes(eventType)) {
console.warn(`UTMTrackJS: Tipo de evento '${eventType}' não é permitido.`);
return false;
}
if (!this._checkCSPCompliance()) {
console.warn('UTMTrackJS: CSP restritivo detectado. Pulando criação de evento.');
return false;
}
if (typeof Event === 'function') {
element.dispatchEvent(new Event(eventType, { bubbles: true }));
} else if (document.createEvent) {
const event = document.createEvent('HTMLEvents');
event.initEvent(eventType, true, false);
element.dispatchEvent(event);
} else {
console.warn('UTMTrackJS: Não foi possível disparar evento - API de eventos não disponível.');
return false;
}
return true;
} catch (eventError) {
console.warn('UTMTrackJS: Não foi possível disparar evento:', eventError);
return false;
}
},
/**
* Dispara eventos customizados do UTMTrackJS
* @param {string} eventType - Tipo do evento customizado
* @param {Object} detail - Detalhes do evento
* @returns {boolean} True se o evento foi disparado com sucesso
*/
dispatchCustomEvent(eventType, detail = {}) {
try {
if (!Object.values(CONSTANTS.CUSTOM_EVENTS).includes(eventType)) {
console.warn(`UTMTrackJS: Tipo de evento customizado '${eventType}' não é reconhecido.`);
return false;
}
// Validação de segurança do detail
if (detail && typeof detail === 'object') {
// Remove propriedades perigosas
const safeDangerousProps = ['constructor', '__proto__', 'prototype'];
for (const prop of safeDangerousProps) {
if (detail.hasOwnProperty(prop)) {
console.warn(`UTMTrackJS: Propriedade perigosa removida do evento: ${prop}`);
delete detail[prop];
}
}
// Limita o tamanho do detail
if (JSON.stringify(detail).length > 10000) {
console.warn('UTMTrackJS: Detail do evento muito grande, limitando...');
detail = { truncated: true, originalSize: 'too_large' };
}
}
const event = new CustomEvent(eventType, {
detail: {
timestamp: Date.now(),
version: CONSTANTS.VERSION,
...detail
},
bubbles: false,
cancelable: false
});
window.dispatchEvent(event);
return true;
} catch (error) {
console.warn('UTMTrackJS: Não foi possível disparar evento customizado:', error);
return false;
}
},
/**
* Throttle function para limitar execução de funções
* @param {Function} func - Função a ser limitada
* @param {number} delay - Delay em milissegundos
* @returns {Function} Função com throttle aplicado
*/
throttle(func, delay) {
let timeoutId;
let lastExecTime = 0;
return function (...args) {
const currentTime = Date.now();
if (currentTime - lastExecTime > delay) {
func.apply(this, args);
lastExecTime = currentTime;
} else {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
lastExecTime = Date.now();
}, delay - (currentTime - lastExecTime));
}
};
}
};
// Módulo de captura de parâmetros UTM
const CaptureModule = {
/**
* Captura parâmetros UTM da URL atual e salva no localStorage
*/
captureAndSave() {
try {
if (typeof URLSearchParams === 'undefined') {
throw new UTMTrackError('URLSearchParams não está disponível neste navegador.', 'NO_URL_SEARCH_PARAMS');
}
const currentUrl = window.location.href;
if (!currentUrl || currentUrl.length > CONSTANTS.MAX_URL_LENGTH) {
throw new UTMTrackError('URL inválida ou muito longa.', 'INVALID_URL');
}
const urlParams = new URLSearchParams(window.location.search);
const utmsFound = {};
let hasUtms = false;
let processedParams = 0;
UtilsModule.getActiveUtmKeys().forEach(key => {
if (processedParams >= CONSTANTS.MAX_PARAMS) {
console.warn('UTMTrackJS: Muitos parâmetros na URL. Limitando processamento.');
return;
}
if (urlParams.has(key)) {
const value = urlParams.get(key);
if (value && typeof value === 'string' && value.length <= 1000) {
const sanitizedValue = ValidationModule.sanitizeUtmValue(value);
if (sanitizedValue) {
utmsFound[key] = sanitizedValue;
hasUtms = true;
processedParams++;
} else {
console.warn(`UTMTrackJS: Valor UTM inválido ignorado para ${key}.`);
}
} else {
console.warn(`UTMTrackJS: Valor UTM muito longo ignorado para ${key}.`);
}
}
});
if (hasUtms) {
const existingUtms = StorageModule.getStoredData() || {};
const updatedUtms = AppState.config.updateWithLatest ?
{ ...existingUtms, ...utmsFound } :
(Object.keys(existingUtms).length === 0 ? utmsFound : existingUtms);
if (AppState.config.updateWithLatest || Object.keys(existingUtms).length === 0) {
StorageModule.saveStoredData(updatedUtms);
// Dispara evento de captura
UtilsModule.dispatchCustomEvent(CONSTANTS.CUSTOM_EVENTS.UTM_CAPTURED, {
capturedUtms: utmsFound,
allUtms: updatedUtms,
url: currentUrl
});
}
}
} catch (error) {
console.error('UTMTrackJS: Erro ao capturar ou salvar UTMs.', error);
}
}
};
// Módulo de preenchimento de elementos
const PopulateModule = {
/**
* Preenche elementos HTML com atributo [data-utmtrackjs] com valores UTM
*/
populateFromAttributes() {
try {
const elements = document.querySelectorAll('[data-utmtrackjs]');
elements.forEach(el => {
try {
const utmKey = el.getAttribute('data-utmtrackjs');
if (!ValidationModule.isValidUtmKey(utmKey)) {
console.warn('UTMTrackJS: Atributo data-utmtrackjs inválido encontrado:', el);
return;
}
const utmValue = PublicAPI.getUtm(utmKey);
if (!utmValue) return;
const safeValue = ValidationModule.sanitizeUtmValue(utmValue);
if (!safeValue) {
console.warn('UTMTrackJS: Valor UTM não é seguro para uso:', utmValue);
return;
}
this.fillElement(el, safeValue);
} catch (elementError) {
console.warn('UTMTrackJS: Erro ao processar elemento:', el, elementError);
}
});
} catch (error) {
console.error('UTMTrackJS: Erro ao preencher elementos com atributos UTM.', error);
}
},
/**
* Preenche um elemento específico com um valor
* @param {HTMLElement} element - Elemento a ser preenchido
* @param {string} value - Valor a ser inserido
*/
fillElement(element, value) {
const tagName = element.tagName.toLowerCase();
if (CONSTANTS.FORM_ELEMENTS.includes(tagName)) {
if (!element.disabled && !element.readOnly) {
const inputType = element.type ? element.type.toLowerCase() : 'text';
if (CONSTANTS.ALLOWED_INPUT_TYPES.includes(inputType)) {
element.value = value;
UtilsModule.dispatchSafeEvent(element, 'input');
} else {
console.warn(`UTMTrackJS: Tipo de input '${inputType}' não é permitido para preenchimento automático`);
}
}
} else {
element.textContent = value;
}
}
};
// Módulo de monitoramento de URL
const URLMonitorModule = {
/**
* Monitora mudanças na URL para atualizar UTMs automaticamente
*/
setup() {
if (AppState.runtime.urlChangeListenerAdded) {
return;
}
try {
Log.info('UTMTrackJS: Configurando monitoramento de mudanças de URL...');
AppState.runtime.lastUrl = window.location.href;
// Monitora mudanças via History API
this.setupHistoryAPIMonitoring();
// Monitora mudanças via popstate e hashchange
this.addSafeEventListener('popstate', this.handleUrlChange);
this.addSafeEventListener('hashchange', this.handleUrlChange);
AppState.runtime.urlChangeListenerAdded = true;
Log.info('UTMTrackJS: Monitoramento de URL configurado com sucesso!');
} catch (error) {
console.error('UTMTrackJS: Erro ao configurar monitoramento de URL.', error);
}
},
/**
* Adiciona event listener de forma segura evitando duplicatas
*/
addSafeEventListener(eventType, handler) {
const listenerKey = `${eventType}_${handler.name}`;
if (!AppState.runtime.eventListeners.has(listenerKey)) {
window.addEventListener(eventType, handler);
AppState.runtime.eventListeners.add(listenerKey);
}
},
/**
* Remove event listener de forma segura
*/
removeSafeEventListener(eventType, handler) {
const listenerKey = `${eventType}_${handler.name}`;
if (AppState.runtime.eventListeners.has(listenerKey)) {
window.removeEventListener(eventType, handler);
AppState.runtime.eventListeners.delete(listenerKey);
}
},
/**
* Configura monitoramento da History API usando interceptação segura
*/
setupHistoryAPIMonitoring() {
if (AppState.runtime.originalHistory) { return; }
// Validação de segurança antes de modificar a History API
if (typeof history.pushState !== 'function' || typeof history.replaceState !== 'function') {
Log.warn('UTMTrackJS: History API não está disponível ou foi comprometida.');
return;
}
AppState.runtime.originalHistory = {
pushState: history.pushState.bind(history),
replaceState: history.replaceState.bind(history)
};
try {
let historyChangeTimeout;
const safeHandleHistoryChange = function() {
clearTimeout(historyChangeTimeout);
historyChangeTimeout = setTimeout(() => {
try {
URLMonitorModule.handleUrlChange();
} catch (error) {
console.error('UTMTrackJS: Erro ao processar mudança de histórico:', error);
}
}, 10); // Debounce de 10ms
};
// Wrapper seguro que preserva a funcionalidade original
const createHistoryWrapper = (originalMethod, methodName) => {
return function(...args) {
try {
const result = originalMethod.apply(this, args);
safeHandleHistoryChange();
return result;
} catch (error) {
console.error(`UTMTrackJS: Erro em ${methodName}:`, error);
throw error;
}
};
};
history.pushState = createHistoryWrapper(AppState.runtime.originalHistory.pushState, 'pushState');
history.replaceState = createHistoryWrapper(AppState.runtime.originalHistory.replaceState, 'replaceState');
} catch (e) {
Log.warn('UTMTrackJS: Falha ao envolver History API, restaurando originais.', e);
AppState.runtime.originalHistory = null;
}
},
disable() {
try {
// Restauração segura da History API
if (AppState.runtime.originalHistory) {
if (typeof AppState.runtime.originalHistory.pushState === 'function') {
history.pushState = AppState.runtime.originalHistory.pushState;
}
if (typeof AppState.runtime.originalHistory.replaceState === 'function') {
history.replaceState = AppState.runtime.originalHistory.replaceState;
}
AppState.runtime.originalHistory = null;
}
// Remove todos os event listeners registrados
this.removeSafeEventListener('popstate', this.handleUrlChange);
this.removeSafeEventListener('hashchange', this.handleUrlChange);
AppState.runtime.urlChangeListenerAdded = false;
AppState.runtime.urlListenersBound = false;
Log.info('UTMTrackJS: Monitoramento de URL desativado.');
return true;
} catch (e) {
console.error('UTMTrackJS: Erro ao desativar monitoramento de URL.', e);
return false;
}
},
/**
* Manipula mudanças de URL com throttling
*/
handleUrlChange: UtilsModule.throttle(() => {
try {
const currentUrl = window.location.href;
Log.info('UTMTrackJS: Detectada mudança de URL de', AppState.runtime.lastUrl, 'para', currentUrl);
if (currentUrl !== AppState.runtime.lastUrl) {
AppState.runtime.lastUrl = currentUrl;
// Só recaptura se updateWithLatest estiver habilitado
if (AppState.config.updateWithLatest) {
Log.info('UTMTrackJS: Recapturando UTMs devido à mudança de URL...');
CaptureModule.captureAndSave();
PopulateModule.populateFromAttributes();
Log.info('UTMTrackJS: UTMs recapturados e elementos atualizados!');
} else {
Log.info('UTMTrackJS: updateWithLatest está desabilitado, ignorando mudança de URL.');
}
}
} catch (error) {
console.error('UTMTrackJS: Erro ao processar mudança de URL.', error);
}
}, CONSTANTS.THROTTLE_DELAY)
};
// API pública da biblioteca
const PublicAPI = {
/**
* Recupera valor de uma chave UTM específica do localStorage
* @param {string} key - Chave UTM a ser recuperada
* @returns {string|null} Valor da UTM ou null se não existir
*/
getUtm(key) {
if (!ValidationModule.isValidUtmKey(key)) {
console.warn('UTMTrackJS: Chave UTM inválida fornecida para getUtm.');
return null;
}
const utms = StorageModule.getStoredData();
return utms ? (utms[key] || null) : null;
},
/**
* Recupera todas as UTMs salvas no localStorage
* @returns {Object|null} Objeto com todas as UTMs ou null se não existirem
*/
getAllUtms() {
const utms = StorageModule.getStoredData();
return utms ? { ...utms } : null;
},
/**
* Remove uma ou todas as UTMs do localStorage
* @param {string} [key] - Chave UTM a ser removida. Se undefined, remove todas
* @returns {boolean} True se removeu com sucesso
*/
removeUtm(key) {
try {
if (key === undefined) {
localStorage.removeItem(CONSTANTS.STORAGE_KEY);
PopulateModule.populateFromAttributes();
return true;
}
if (!ValidationModule.isValidUtmKey(key)) {
console.warn('UTMTrackJS: Chave UTM inválida fornecida para removeUtm:', key);
return false;
}
const utms = StorageModule.getStoredData();
if (!utms || !utms.hasOwnProperty(key)) return true;
const removedValue = utms[key];
delete utms[key];
if (Object.keys(utms).length === 0) {
localStorage.removeItem(CONSTANTS.STORAGE_KEY);
} else {
StorageModule.saveStoredData(utms);
}
PopulateModule.populateFromAttributes();
// Dispara evento de remoção
UtilsModule.dispatchCustomEvent(CONSTANTS.CUSTOM_EVENTS.UTM_REMOVED, {
removedKey: key,
removedValue: removedValue,
remainingUtms: utms
});
return true;
} catch (error) {
console.error('UTMTrackJS: Erro ao remover UTM.', error);
return false;
}
},
/**
* Define um ou múltiplos parâmetros UTM no localStorage
* @param {string|Object} keyOrObject - Chave UTM ou objeto com chaves/valores
* @param {string} [value] - Valor da UTM (se keyOrObject for string)
* @returns {boolean} True se definiu com sucesso
*/
setUtm(keyOrObject, value) {
try {
const existingUtms = StorageModule.getStoredData() || {};
let utmsToSet = {};
if (typeof keyOrObject === 'string') {
if (!ValidationModule.isValidUtmKey(keyOrObject) || !ValidationModule.isValidUtmValue(value)) {
throw new UTMTrackError('Chave ou valor UTM inválido.', 'INVALID_INPUT');
}
if (typeof value === 'object') {
throw new UTMTrackError('Valor não pode ser objeto ou array.', 'INVALID_VALUE_TYPE');
}
const sanitizedValue = ValidationModule.sanitizeUtmValue(value);
if (!sanitizedValue) {
throw new UTMTrackError('Valor inválido após sanitização.', 'INVALID_VALUE');
}
utmsToSet[keyOrObject] = sanitizedValue;
} else if (typeof keyOrObject === 'object' && keyOrObject !== null && !Array.isArray(keyOrObject)) {
for (const [key, val] of Object.entries(keyOrObject)) {
if (!ValidationModule.isValidUtmKey(key)) {
console.warn(`UTMTrackJS: Ignorando chave inválida ${key}`);
continue;
}
if (typeof val === 'object') {
console.warn(`UTMTrackJS: Valor complexo ignorado para chave ${key}`);
continue;
}
if (!ValidationModule.isValidUtmValue(val)) {
console.warn(`UTMTrackJS: Valor inválido para chave ${key}`);
continue;
}
const sanitizedValue = ValidationModule.sanitizeUtmValue(val);
if (sanitizedValue) {
utmsToSet[key] = sanitizedValue;
}
}
if (Object.keys(utmsToSet).length === 0) {
throw new UTMTrackError('Nenhuma UTM válida encontrada no objeto fornecido.', 'NO_VALID_UTMS');
}
} else {
throw new UTMTrackError('Primeiro parâmetro deve ser uma string ou objeto.', 'INVALID_PARAMETER_TYPE');
}