-
Notifications
You must be signed in to change notification settings - Fork 17
/
clevertap.js
9271 lines (7537 loc) · 329 KB
/
clevertap.js
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
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.clevertap = factory());
}(this, (function () { 'use strict';
var id = 0;
function _classPrivateFieldLooseKey(name) {
return "__private_" + id++ + "_" + name;
}
function _classPrivateFieldLooseBase(receiver, privateKey) {
if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
throw new TypeError("attempted to use private field on non-instance");
}
return receiver;
}
const TARGET_DOMAIN = 'clevertap-prod.com';
const TARGET_PROTOCOL = 'https:';
const DEFAULT_REGION = 'eu1';
var _accountId = _classPrivateFieldLooseKey("accountId");
var _region = _classPrivateFieldLooseKey("region");
var _targetDomain = _classPrivateFieldLooseKey("targetDomain");
var _dcSdkversion = _classPrivateFieldLooseKey("dcSdkversion");
var _token = _classPrivateFieldLooseKey("token");
class Account {
constructor() {
let {
id
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let region = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
let targetDomain = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TARGET_DOMAIN;
let token = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
Object.defineProperty(this, _accountId, {
writable: true,
value: void 0
});
Object.defineProperty(this, _region, {
writable: true,
value: ''
});
Object.defineProperty(this, _targetDomain, {
writable: true,
value: TARGET_DOMAIN
});
Object.defineProperty(this, _dcSdkversion, {
writable: true,
value: ''
});
Object.defineProperty(this, _token, {
writable: true,
value: ''
});
this.id = id;
if (region) {
this.region = region;
}
if (targetDomain) {
this.targetDomain = targetDomain;
}
if (token) {
this.token = token;
}
}
get id() {
return _classPrivateFieldLooseBase(this, _accountId)[_accountId];
}
set id(accountId) {
_classPrivateFieldLooseBase(this, _accountId)[_accountId] = accountId;
}
get region() {
return _classPrivateFieldLooseBase(this, _region)[_region];
}
set region(region) {
_classPrivateFieldLooseBase(this, _region)[_region] = region;
}
get dcSDKVersion() {
return _classPrivateFieldLooseBase(this, _dcSdkversion)[_dcSdkversion];
}
set dcSDKVersion(dcSDKVersion) {
_classPrivateFieldLooseBase(this, _dcSdkversion)[_dcSdkversion] = dcSDKVersion;
}
get targetDomain() {
return _classPrivateFieldLooseBase(this, _targetDomain)[_targetDomain];
}
set targetDomain(targetDomain) {
_classPrivateFieldLooseBase(this, _targetDomain)[_targetDomain] = targetDomain;
}
get token() {
return _classPrivateFieldLooseBase(this, _token)[_token];
}
set token(token) {
_classPrivateFieldLooseBase(this, _token)[_token] = token;
}
get finalTargetDomain() {
if (this.region) {
return "".concat(this.region, ".").concat(this.targetDomain);
} else {
if (this.targetDomain === TARGET_DOMAIN) {
return "".concat(DEFAULT_REGION, ".").concat(this.targetDomain);
}
return this.targetDomain;
}
}
get dataPostPEURL() {
return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/defineVars");
}
get dataPostURL() {
return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/a?t=96");
}
get recorderURL() {
return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/r?r=1");
}
get emailURL() {
return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/e?r=1");
}
}
const unsupportedKeyCharRegex = new RegExp('^\\s+|\\\.|\:|\\\$|\'|\"|\\\\|\\s+$', 'g');
const unsupportedValueCharRegex = new RegExp("^\\s+|\'|\"|\\\\|\\s+$", 'g');
const singleQuoteRegex = new RegExp('\'', 'g');
const CLEAR = 'clear';
const CHARGED_ID = 'Charged ID';
const CHARGEDID_COOKIE_NAME = 'WZRK_CHARGED_ID';
const GCOOKIE_NAME = 'WZRK_G';
const KCOOKIE_NAME = 'WZRK_K';
const CAMP_COOKIE_NAME = 'WZRK_CAMP';
const CAMP_COOKIE_G = 'WZRK_CAMP_G'; // cookie for storing campaign details against guid
const SCOOKIE_PREFIX = 'WZRK_S';
const SCOOKIE_EXP_TIME_IN_SECS = 60 * 20; // 20 mins
const EV_COOKIE = 'WZRK_EV';
const META_COOKIE = 'WZRK_META';
const PR_COOKIE = 'WZRK_PR';
const ARP_COOKIE = 'WZRK_ARP';
const LCOOKIE_NAME = 'WZRK_L';
const GLOBAL = 'global'; // used for email unsubscribe also
const DISPLAY = 'display';
const WEBPUSH_LS_KEY = 'WZRK_WPR';
const OPTOUT_KEY = 'optOut';
const CT_OPTOUT_KEY = 'ct_optout';
const OPTOUT_COOKIE_ENDSWITH = ':OO';
const USEIP_KEY = 'useIP';
const LRU_CACHE = 'WZRK_X';
const LRU_CACHE_SIZE = 100;
const IS_OUL = 'isOUL';
const EVT_PUSH = 'push';
const EVT_PING = 'ping';
const COOKIE_EXPIRY = 86400 * 365; // 1 Year in seconds
const MAX_TRIES = 200; // API tries
const FIRST_PING_FREQ_IN_MILLIS = 2 * 60 * 1000; // 2 mins
const CONTINUOUS_PING_FREQ_IN_MILLIS = 5 * 60 * 1000; // 5 mins
const GROUP_SUBSCRIPTION_REQUEST_ID = '2';
const categoryLongKey = 'cUsY';
const WZRK_PREFIX = 'wzrk_';
const WZRK_ID = 'wzrk_id';
const NOTIFICATION_VIEWED = 'Notification Viewed';
const NOTIFICATION_CLICKED = 'Notification Clicked';
const FIRE_PUSH_UNREGISTERED = 'WZRK_FPU';
const PUSH_SUBSCRIPTION_DATA = 'WZRK_PSD'; // PUSH SUBSCRIPTION DATA FOR REGISTER/UNREGISTER TOKEN
const COMMAND_INCREMENT = '$incr';
const COMMAND_DECREMENT = '$decr';
const COMMAND_SET = '$set';
const COMMAND_ADD = '$add';
const COMMAND_REMOVE = '$remove';
const COMMAND_DELETE = '$delete';
const WEBINBOX_CONFIG = 'WZRK_INBOX_CONFIG';
const WEBINBOX = 'WZRK_INBOX';
const MAX_INBOX_MSG = 15;
const VARIABLES = 'WZRK_PE';
const PUSH_DELAY_MS = 1000;
const MAX_DELAY_FREQUENCY = 1000 * 60 * 10;
const WZRK_FETCH = 'wzrk_fetch';
const WEBPUSH_CONFIG = 'WZRK_PUSH_CONFIG';
const SYSTEM_EVENTS = ['Stayed', 'UTM Visited', 'App Launched', 'Notification Sent', NOTIFICATION_VIEWED, NOTIFICATION_CLICKED];
const isString = input => {
return typeof input === 'string' || input instanceof String;
};
const isObject = input => {
// TODO: refine
return Object.prototype.toString.call(input) === '[object Object]';
};
const isDateObject = input => {
return typeof input === 'object' && input instanceof Date;
};
const isObjectEmpty = obj => {
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
};
const isConvertibleToNumber = n => {
return !isNaN(parseFloat(n)) && isFinite(n);
};
const isNumber = n => {
return /^-?[\d.]+(?:e-?\d+)?$/.test(n) && typeof n === 'number';
};
const isValueValid = value => {
if (value === null || value === undefined || value === 'undefined') {
return false;
}
return true;
};
const removeUnsupportedChars = (o, logger) => {
// keys can't be greater than 1024 chars, values can't be greater than 1024 chars
if (typeof o === 'object') {
for (const key in o) {
if (o.hasOwnProperty(key)) {
const sanitizedVal = removeUnsupportedChars(o[key], logger);
let sanitizedKey;
sanitizedKey = sanitize(key, unsupportedKeyCharRegex);
if (sanitizedKey.length > 1024) {
sanitizedKey = sanitizedKey.substring(0, 1024);
logger.reportError(520, sanitizedKey + '... length exceeded 1024 chars. Trimmed.');
}
delete o[key];
o[sanitizedKey] = sanitizedVal;
}
}
} else {
let val;
if (isString(o)) {
val = sanitize(o, unsupportedValueCharRegex);
if (val.length > 1024) {
val = val.substring(0, 1024);
logger.reportError(521, val + '... length exceeded 1024 chars. Trimmed.');
}
} else {
val = o;
}
return val;
}
return o;
};
const sanitize = (input, regex) => {
return input.replace(regex, '');
};
const getToday = () => {
const today = new Date();
return today.getFullYear() + '' + today.getMonth() + '' + today.getDay();
};
const getNow = () => {
return Math.floor(new Date().getTime() / 1000);
};
const convertToWZRKDate = dateObj => {
return '$D_' + Math.round(dateObj.getTime() / 1000);
};
const setDate = dt => {
// expecting yyyymmdd format either as a number or a string
if (isDateValid(dt)) {
return '$D_' + dt;
}
};
const isDateValid = date => {
const matches = /^(\d{4})(\d{2})(\d{2})$/.exec(date);
if (matches == null) return false;
const d = matches[3];
const m = matches[2] - 1;
const y = matches[1];
const composedDate = new Date(y, m, d); // eslint-disable-next-line eqeqeq
return composedDate.getDate() == d && composedDate.getMonth() == m && composedDate.getFullYear() == y;
};
class StorageManager {
static save(key, value) {
if (!key || !value) {
return false;
}
if (this._isLocalStorageSupported()) {
localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value));
return true;
}
}
static read(key) {
if (!key) {
return false;
}
let data = null;
if (this._isLocalStorageSupported()) {
data = localStorage.getItem(key);
}
if (data != null) {
try {
data = JSON.parse(data);
} catch (e) {}
}
return data;
}
static remove(key) {
if (!key) {
return false;
}
if (this._isLocalStorageSupported()) {
localStorage.removeItem(key);
return true;
}
}
static removeCookie(name, domain) {
let cookieStr = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
if (domain) {
cookieStr = cookieStr + ' domain=' + domain + '; path=/';
}
document.cookie = cookieStr;
}
static createCookie(name, value, seconds, domain) {
let expires = '';
let domainStr = '';
if (seconds) {
const date = new Date();
date.setTime(date.getTime() + seconds * 1000);
expires = '; expires=' + date.toGMTString();
}
if (domain) {
domainStr = '; domain=' + domain;
}
value = encodeURIComponent(value);
document.cookie = name + '=' + value + expires + domainStr + '; path=/';
}
static readCookie(name) {
const nameEQ = name + '=';
const ca = document.cookie.split(';');
for (let idx = 0; idx < ca.length; idx++) {
let c = ca[idx];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
} // eslint-disable-next-line eqeqeq
if (c.indexOf(nameEQ) == 0) {
return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
}
return null;
}
static _isLocalStorageSupported() {
return 'localStorage' in window && window.localStorage !== null && typeof window.localStorage.setItem === 'function';
}
static saveToLSorCookie(property, value) {
if (value == null) {
return;
}
try {
if (this._isLocalStorageSupported()) {
this.save(property, encodeURIComponent(JSON.stringify(value)));
} else {
if (property === GCOOKIE_NAME) {
this.createCookie(property, encodeURIComponent(value), 0, window.location.hostname);
} else {
this.createCookie(property, encodeURIComponent(JSON.stringify(value)), 0, window.location.hostname);
}
}
$ct.globalCache[property] = value;
} catch (e) {}
}
static readFromLSorCookie(property) {
let data;
if ($ct.globalCache.hasOwnProperty(property)) {
return $ct.globalCache[property];
}
if (this._isLocalStorageSupported()) {
data = this.read(property);
} else {
data = this.readCookie(property);
}
if (data !== null && data !== undefined && !(typeof data.trim === 'function' && data.trim() === '')) {
let value;
try {
value = JSON.parse(decodeURIComponent(data));
} catch (err) {
value = decodeURIComponent(data);
}
$ct.globalCache[property] = value;
return value;
}
}
static createBroadCookie(name, value, seconds, domain) {
// sets cookie on the base domain. e.g. if domain is baz.foo.bar.com, set cookie on ".bar.com"
// To update an existing "broad domain" cookie, we need to know what domain it was actually set on.
// since a retrieved cookie never tells which domain it was set on, we need to set another test cookie
// to find out which "broadest" domain the cookie was set on. Then delete the test cookie, and use that domain
// for updating the actual cookie.
if (domain) {
let broadDomain = $ct.broadDomain;
if (broadDomain == null) {
// if we don't know the broadDomain yet, then find out
const domainParts = domain.split('.');
let testBroadDomain = '';
for (let idx = domainParts.length - 1; idx >= 0; idx--) {
if (idx === 0) {
testBroadDomain = domainParts[idx] + testBroadDomain;
} else {
testBroadDomain = '.' + domainParts[idx] + testBroadDomain;
} // only needed if the cookie already exists and needs to be updated. See note above.
if (this.readCookie(name)) {
// no guarantee that browser will delete cookie, hence create short lived cookies
var testCookieName = 'test_' + name + idx;
this.createCookie(testCookieName, value, 10, testBroadDomain); // self-destruct after 10 seconds
if (!this.readCookie(testCookieName)) {
// if test cookie not set, then the actual cookie wouldn't have been set on this domain either.
continue;
} else {
// else if cookie set, then delete the test and the original cookie
this.removeCookie(testCookieName, testBroadDomain);
}
}
this.createCookie(name, value, seconds, testBroadDomain);
const tempCookie = this.readCookie(name); // eslint-disable-next-line eqeqeq
if (tempCookie == value) {
broadDomain = testBroadDomain;
$ct.broadDomain = broadDomain;
break;
}
}
} else {
this.createCookie(name, value, seconds, broadDomain);
}
} else {
this.createCookie(name, value, seconds, domain);
}
}
static getMetaProp(property) {
const metaObj = this.readFromLSorCookie(META_COOKIE);
if (metaObj != null) {
return metaObj[property];
}
}
static setMetaProp(property, value) {
if (this._isLocalStorageSupported()) {
let wzrkMetaObj = this.readFromLSorCookie(META_COOKIE);
if (wzrkMetaObj == null) {
wzrkMetaObj = {};
}
if (value === undefined) {
delete wzrkMetaObj[property];
} else {
wzrkMetaObj[property] = value;
}
this.saveToLSorCookie(META_COOKIE, wzrkMetaObj);
}
}
static getAndClearMetaProp(property) {
const value = this.getMetaProp(property);
this.setMetaProp(property, undefined);
return value;
}
static setInstantDeleteFlagInK() {
let k = this.readFromLSorCookie(KCOOKIE_NAME);
if (k == null) {
k = {};
}
k.flag = true;
this.saveToLSorCookie(KCOOKIE_NAME, k);
}
static backupEvent(data, reqNo, logger) {
let backupArr = this.readFromLSorCookie(LCOOKIE_NAME);
if (typeof backupArr === 'undefined') {
backupArr = {};
}
backupArr[reqNo] = {
q: data
};
this.saveToLSorCookie(LCOOKIE_NAME, backupArr);
logger.debug("stored in ".concat(LCOOKIE_NAME, " reqNo : ").concat(reqNo, " -> ").concat(data));
}
static removeBackup(respNo, logger) {
const backupMap = this.readFromLSorCookie(LCOOKIE_NAME);
if (typeof backupMap !== 'undefined' && backupMap !== null && typeof backupMap[respNo] !== 'undefined') {
logger.debug("del event: ".concat(respNo, " data-> ").concat(backupMap[respNo].q));
delete backupMap[respNo];
this.saveToLSorCookie(LCOOKIE_NAME, backupMap);
}
}
}
const $ct = {
globalCache: {
gcookie: null,
REQ_N: 0,
RESP_N: 0
},
LRU_CACHE: null,
globalProfileMap: undefined,
globalEventsMap: undefined,
blockRequest: false,
isOptInRequest: false,
broadDomain: null,
webPushEnabled: null,
campaignDivMap: {},
currentSessionId: null,
wiz_counter: 0,
// to keep track of number of times we load the body
notifApi: {
notifEnabledFromApi: false
},
// helper variable to handle race condition and check when notifications were called
unsubGroups: [],
updatedCategoryLong: null,
inbox: null,
isPrivacyArrPushed: false,
privacyArray: [],
offline: false,
location: null,
dismissSpamControl: false,
globalUnsubscribe: true,
flutterVersion: null,
variableStore: {},
pushConfig: null // domain: window.location.hostname, url -> getHostName()
// gcookie: -> device
};
var _keyOrder = _classPrivateFieldLooseKey("keyOrder");
var _deleteFromObject = _classPrivateFieldLooseKey("deleteFromObject");
class LRUCache {
constructor(max) {
Object.defineProperty(this, _deleteFromObject, {
value: _deleteFromObject2
});
Object.defineProperty(this, _keyOrder, {
writable: true,
value: void 0
});
this.max = max;
let lruCache = StorageManager.readFromLSorCookie(LRU_CACHE);
if (lruCache) {
const tempLruCache = {};
_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder] = [];
lruCache = lruCache.cache;
for (const entry in lruCache) {
if (lruCache.hasOwnProperty(entry)) {
tempLruCache[lruCache[entry][0]] = lruCache[entry][1];
_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder].push(lruCache[entry][0]);
}
}
this.cache = tempLruCache;
} else {
this.cache = {};
_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder] = [];
}
}
get(key) {
const item = this.cache[key];
if (item) {
this.cache = _classPrivateFieldLooseBase(this, _deleteFromObject)[_deleteFromObject](key, this.cache);
this.cache[key] = item;
_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder].push(key);
}
this.saveCacheToLS(this.cache);
return item;
}
set(key, value) {
const item = this.cache[key];
const allKeys = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder];
if (item != null) {
this.cache = _classPrivateFieldLooseBase(this, _deleteFromObject)[_deleteFromObject](key, this.cache);
} else if (allKeys.length === this.max) {
this.cache = _classPrivateFieldLooseBase(this, _deleteFromObject)[_deleteFromObject](allKeys[0], this.cache);
}
this.cache[key] = value;
if (_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder][_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder] - 1] !== key) {
_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder].push(key);
}
this.saveCacheToLS(this.cache);
}
saveCacheToLS(cache) {
const objToArray = [];
const allKeys = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder];
for (const index in allKeys) {
if (allKeys.hasOwnProperty(index)) {
const temp = [];
temp.push(allKeys[index]);
temp.push(cache[allKeys[index]]);
objToArray.push(temp);
}
}
StorageManager.saveToLSorCookie(LRU_CACHE, {
cache: objToArray
});
}
getKey(value) {
if (value === null) {
return null;
}
const allKeys = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder];
for (const index in allKeys) {
if (allKeys.hasOwnProperty(index)) {
if (this.cache[allKeys[index]] === value) {
return allKeys[index];
}
}
}
return null;
}
getSecondLastKey() {
const keysArr = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder];
if (keysArr != null && keysArr.length > 1) {
return keysArr[keysArr.length - 2];
}
return -1;
}
getLastKey() {
const keysLength = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder].length;
if (keysLength) {
return _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder][keysLength - 1];
}
}
}
var _deleteFromObject2 = function _deleteFromObject2(key, obj) {
const allKeys = JSON.parse(JSON.stringify(_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder]));
const newCache = {};
let indexToDelete;
for (const index in allKeys) {
if (allKeys.hasOwnProperty(index)) {
if (allKeys[index] !== key) {
newCache[allKeys[index]] = obj[allKeys[index]];
} else {
indexToDelete = index;
}
}
}
allKeys.splice(indexToDelete, 1);
_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder] = JSON.parse(JSON.stringify(allKeys));
return newCache;
};
var _logger = _classPrivateFieldLooseKey("logger");
var _request = _classPrivateFieldLooseKey("request");
var _device = _classPrivateFieldLooseKey("device");
var _session = _classPrivateFieldLooseKey("session");
class CleverTapAPI {
constructor(_ref) {
let {
logger,
request,
device,
session
} = _ref;
Object.defineProperty(this, _logger, {
writable: true,
value: void 0
});
Object.defineProperty(this, _request, {
writable: true,
value: void 0
});
Object.defineProperty(this, _device, {
writable: true,
value: void 0
});
Object.defineProperty(this, _session, {
writable: true,
value: void 0
});
_classPrivateFieldLooseBase(this, _logger)[_logger] = logger;
_classPrivateFieldLooseBase(this, _request)[_request] = request;
_classPrivateFieldLooseBase(this, _device)[_device] = device;
_classPrivateFieldLooseBase(this, _session)[_session] = session;
}
/**
*
* @param {string} global gcookie
* @param {string} session
* @param {boolean} resume sent true in case of an OUL request from client side, which is returned as it is by server
* @param {number} respNumber the index of the request in backupmanager
* @param {boolean} optOutResponse
* @returns
*/
s(global, session, resume, respNumber, optOutResponse) {
let oulReq = false;
let newGuid = false; // for a scenario when OUL request is true from client side
// but resume is returned as false from server end
// we maintan a OulReqN var in the window object
// and compare with respNumber to determine the response of an OUL request
if (window.isOULInProgress) {
if (resume || respNumber !== 'undefined' && respNumber === window.oulReqN) {
window.isOULInProgress = false;
oulReq = true;
}
} // call back function used to store global and session ids for the user
if (typeof respNumber === 'undefined') {
respNumber = 0;
}
StorageManager.removeBackup(respNumber, _classPrivateFieldLooseBase(this, _logger)[_logger]);
if (respNumber > $ct.globalCache.REQ_N) {
// request for some other user so ignore
return;
}
if (!isValueValid(_classPrivateFieldLooseBase(this, _device)[_device].gcookie)) {
if (global) {
newGuid = true;
}
}
if (!isValueValid(_classPrivateFieldLooseBase(this, _device)[_device].gcookie) || resume || typeof optOutResponse === 'boolean') {
const sessionObj = _classPrivateFieldLooseBase(this, _session)[_session].getSessionCookieObject();
/* If the received session is less than the session in the cookie,
then don't update guid as it will be response for old request
*/
if (window.isOULInProgress || sessionObj.s && session < sessionObj.s) {
return;
}
_classPrivateFieldLooseBase(this, _logger)[_logger].debug("Cookie was ".concat(_classPrivateFieldLooseBase(this, _device)[_device].gcookie, " set to ").concat(global));
_classPrivateFieldLooseBase(this, _device)[_device].gcookie = global;
if (!isValueValid(_classPrivateFieldLooseBase(this, _device)[_device].gcookie)) {
// clear useIP meta prop
StorageManager.getAndClearMetaProp(USEIP_KEY);
}
if (global && StorageManager._isLocalStorageSupported()) {
if ($ct.LRU_CACHE == null) {
$ct.LRU_CACHE = new LRUCache(LRU_CACHE_SIZE);
}
const kIdFromLS = StorageManager.readFromLSorCookie(KCOOKIE_NAME);
let guidFromLRUCache;
if (kIdFromLS != null && kIdFromLS.id) {
guidFromLRUCache = $ct.LRU_CACHE.cache[kIdFromLS.id];
if (resume) {
if (!guidFromLRUCache) {
StorageManager.saveToLSorCookie(FIRE_PUSH_UNREGISTERED, true); // replace login identity in OUL request
// with the gcookie returned in exchange
$ct.LRU_CACHE.set(kIdFromLS.id, global);
}
}
}
StorageManager.saveToLSorCookie(GCOOKIE_NAME, global); // lastk provides the guid
const lastK = $ct.LRU_CACHE.getSecondLastKey();
if (StorageManager.readFromLSorCookie(FIRE_PUSH_UNREGISTERED) && lastK !== -1) {
const lastGUID = $ct.LRU_CACHE.cache[lastK]; // fire the request directly via fireRequest to unregister the token
// then other requests with the updated guid should follow
_classPrivateFieldLooseBase(this, _request)[_request].unregisterTokenForGuid(lastGUID);
}
}
StorageManager.createBroadCookie(GCOOKIE_NAME, global, COOKIE_EXPIRY, window.location.hostname);
StorageManager.saveToLSorCookie(GCOOKIE_NAME, global);
}
if (StorageManager._isLocalStorageSupported()) {
_classPrivateFieldLooseBase(this, _session)[_session].manageSession(session);
} // session cookie
const obj = _classPrivateFieldLooseBase(this, _session)[_session].getSessionCookieObject(); // for the race-condition where two responses come back with different session ids. don't write the older session id.
if (typeof obj.s === 'undefined' || obj.s <= session) {
obj.s = session;
obj.t = getNow(); // time of last response from server
_classPrivateFieldLooseBase(this, _session)[_session].setSessionCookieObject(obj);
} // set blockRequest to false only if the device has a valid gcookie
if (isValueValid(_classPrivateFieldLooseBase(this, _device)[_device].gcookie)) {
$ct.blockRequest = false;
} // only process the backup events after an OUL request or a new guid is recieved
if ((oulReq || newGuid) && !_classPrivateFieldLooseBase(this, _request)[_request].processingBackup) {
_classPrivateFieldLooseBase(this, _request)[_request].processBackupEvents();
}
$ct.globalCache.RESP_N = respNumber;
}
}
var _logger$1 = _classPrivateFieldLooseKey("logger");
class DeviceManager {
constructor(_ref) {
let {
logger
} = _ref;
Object.defineProperty(this, _logger$1, {
writable: true,
value: void 0
});
this.gcookie = void 0;
_classPrivateFieldLooseBase(this, _logger$1)[_logger$1] = logger;
this.gcookie = this.getGuid();
}
getGuid() {
let guid = null;
if (isValueValid(this.gcookie)) {
return this.gcookie;
}
if (StorageManager._isLocalStorageSupported()) {
const value = StorageManager.read(GCOOKIE_NAME);
if (isValueValid(value)) {
try {
guid = JSON.parse(decodeURIComponent(value));
} catch (e) {
_classPrivateFieldLooseBase(this, _logger$1)[_logger$1].debug('Cannot parse Gcookie from localstorage - must be encoded ' + value); // assumming guids are of size 32. supporting both formats.
// guid can have encodedURIComponent or be without it.
// 1.56e4078ed15749928c042479ec2b4d47 - breaks on JSON.parse(decodeURIComponent())
// 2.%2256e4078ed15749928c042479ec2b4d47%22
if (value.length === 32) {
guid = value;
StorageManager.saveToLSorCookie(GCOOKIE_NAME, value);
} else {
_classPrivateFieldLooseBase(this, _logger$1)[_logger$1].error('Illegal guid ' + value);
}
} // Persist to cookie storage if not present there.
if (isValueValid(guid)) {
StorageManager.createBroadCookie(GCOOKIE_NAME, guid, COOKIE_EXPIRY, window.location.hostname);
}
}
}
if (!isValueValid(guid)) {
guid = StorageManager.readCookie(GCOOKIE_NAME);
if (isValueValid(guid) && (guid.indexOf('%') === 0 || guid.indexOf('\'') === 0 || guid.indexOf('"') === 0)) {
guid = null;
}
if (isValueValid(guid)) {
StorageManager.saveToLSorCookie(GCOOKIE_NAME, guid);
}
}
return guid;
}
}
const DATA_NOT_SENT_TEXT = 'This property has been ignored.';
const CLEVERTAP_ERROR_PREFIX = 'CleverTap error:'; // Formerly wzrk_error_txt
const EMBED_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Incorrect embed script.");
const EVENT_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Event structure not valid. ").concat(DATA_NOT_SENT_TEXT);
const GENDER_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Gender value should one of the following: m,f,o,u,male,female,unknown,others (case insensitive). ").concat(DATA_NOT_SENT_TEXT);
const EMPLOYED_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Employed value should be either Y or N. ").concat(DATA_NOT_SENT_TEXT);