-
Notifications
You must be signed in to change notification settings - Fork 2
/
a-normal.js
3848 lines (3301 loc) · 135 KB
/
a-normal.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 __wizrocket() {
var targetDomain = 'wzrkt.com';
// var targetDomain = 'localhost:3838'; //ALWAYS comment this line before deploying
var wz_pr = "https:";
var dataPostURL, recorderURL, emailURL;
var wiz = this;
// var serviceWorkerPath = '/clevertap_sw.js'; // the service worker is placed in the doc root
var doc = document;
var domain = window.location.hostname;
var broadDomain;
var wc = window.console;
var requestTime = 0, seqNo = 0;
var wzrk_error = {}; //to trap input errors
var wiz_counter = 0; // to keep track of number of times we load the body
var globalCache = {};
// to be used for checking whether the script loaded fine and the wiz.init function was called
var onloadcalled = 0; // 1 = fired
var processingBackup = false;
var unsubGroups = []
var updatedCategoryLong;
var categoryLongKey = "cUsY";
var gcookie, scookieObj;
var accountId, region;
var campaignDivMap = {};
var blockRequeust = false, clearCookie = false;
var SCOOKIE_NAME, globalChargedId;
var globalEventsMap, globalProfileMap, currentSessionId;
var storageDelim = "|$|";
var staleEvtMaxTime = 20 * 60; //20 mins
var COOKIE_EXPIRY = 86400 * 365 * 10; //10 years in seconds. Seconds in an days * days in an year * number of years
var LRU_CACHE, LRU_CACHE_SIZE = 100;
var chromeAgent;
var firefoxAgent;
var safariAgent;
// for VAPID web push
function urlBase64ToUint8Array(base64String) {
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/')
;
var rawData = window.atob(base64);
var processedData = []
for (var i=0; i<rawData.length; i++) {
processedData.push(rawData.charCodeAt(i))
}
return new Uint8Array(processedData);
}
var fcmPublicKey = null;
var STRING_CONSTANTS = {
CLEAR: 'clear',
CHARGED_ID: 'Charged ID',
CHARGEDID_COOKIE_NAME: 'WZRK_CHARGED_ID',
GCOOKIE_NAME: 'WZRK_G',
KCOOKIE_NAME: 'WZRK_K',
CAMP_COOKIE_NAME: 'WZRK_CAMP',
SCOOKIE_PREFIX: 'WZRK_S',
EV_COOKIE: 'WZRK_EV',
META_COOKIE: 'WZRK_META',
PR_COOKIE: 'WZRK_PR',
ARP_COOKIE: 'WZRK_ARP',
LCOOKIE_NAME: 'WZRK_L',
NOTIF_COOKIE_NAME: 'WZRK_N',
GLOBAL: 'global',
TOTAL_COUNT: 'tc',
DISPLAY: 'display',
UNDEFINED: 'undefined',
WEBPUSH_LS_KEY: 'WZRK_WPR',
OPTOUT_KEY: 'optOut',
CT_OPTOUT_KEY: 'ct_optout',
OPTOUT_COOKIE_ENDSWITH: ':OO',
USEIP_KEY: 'useIP',
LRU_CACHE: 'WZRK_X',
IS_OUL: "isOUL",
FIRE_PUSH_UNREGISTERED: 'WZRK_FPU',
PUSH_SUBSCRIPTION_DATA: 'WZRK_PSD'
};
// path to reference the JS for our dialog
var wizAlertJSPath = 'https://d2r1yp2w7bby2u.cloudfront.net/js/wzrk_dialog.min.js';
var FIRST_PING_FREQ_IN_MILLIS = 2 * 60 * 1000; // 2 mins
var CONTINUOUS_PING_FREQ_IN_MILLIS = 5 * 60 * 1000; // 5 mins
var TWENTY_MINS = 20 * 60 * 1000;
var SCOOKIE_EXP_TIME_IN_SECS = 60 * 20; // 20 mins
var GROUP_SUBSCRIPTION_REQUEST_ID = "2";
var EVT_PING = "ping", EVT_PUSH = "push";
var wizrocket = window['wizrocket'];
var REQ_N = 0;
var RESP_N = 0;
if (typeof clevertap != STRING_CONSTANTS.UNDEFINED) {
wizrocket = clevertap;
window['wizrocket'] = clevertap;
} else {
window['clevertap'] = wizrocket;
}
var webPushEnabled; // gets set to true on page request, when chrome notifs have been integrated completely
wiz.is_onloadcalled = function () {
return (onloadcalled === 1);
};
// use these to add and remove sweet alert dialogs as necessary
wiz.addWizAlertJS = function () {
var scriptTag = doc.createElement('script');
scriptTag.setAttribute('type', 'text/javascript');
scriptTag.setAttribute('id', 'wzrk-alert-js');
scriptTag.setAttribute('src', wizAlertJSPath);
// add the script tag to the end of the body
document.getElementsByTagName('body')[0].appendChild(scriptTag);
return scriptTag;
};
wiz.removeWizAlertJS = function () {
var scriptTag = doc.getElementById('wzrk-alert-js');
scriptTag.parentNode.removeChild(scriptTag);
};
wiz.enableWebPush = function (enabled, applicationServerKey) {
webPushEnabled = enabled;
if(applicationServerKey != null) {
wiz.setApplicationServerKey(applicationServerKey);
}
if (webPushEnabled && notifApi.notifEnabledFromApi) {
wiz.handleNotificationRegistration(notifApi.displayArgs);
} else if (!webPushEnabled && notifApi.notifEnabledFromApi) {
wc.e('Ensure that web push notifications are fully enabled and integrated before requesting them');
}
};
wiz.setUpWebPushNotifications = function (subscriptionCallback, serviceWorkerPath, apnsWebPushId, apnsServiceUrl) {
if(navigator.userAgent.indexOf('Chrome') !== -1 || navigator.userAgent.indexOf('Firefox') !== -1){
wiz.setUpChromeFirefoxNotifications(subscriptionCallback, serviceWorkerPath);
} else if(navigator.userAgent.indexOf('Safari') !== -1){
wiz.setUpSafariNotifications(subscriptionCallback, apnsWebPushId, apnsServiceUrl);
}
};
/**
* Sets up a service worker for chrome push notifications and sends the data to LC
*/
wiz.setUpSafariNotifications= function (subscriptionCallback, apnsWebPushId, apnsServiceUrl) {
// ensure that proper arguments are passed
if (typeof apnsWebPushId === "undefined") {
wc.e('Ensure that APNS Web Push ID is supplied');
}
if (typeof apnsServiceUrl === "undefined") {
wc.e('Ensure that APNS Web Push service path is supplied');
}
if ('safari' in window && 'pushNotification' in window['safari']) {
window['safari']['pushNotification']['requestPermission'](
apnsServiceUrl,
apnsWebPushId, {}, function (subscription) {
if (subscription['permission'] === 'granted') {
var subscriptionData = JSON.parse(JSON.stringify(subscription));
subscriptionData['endpoint'] = subscription['deviceToken'];
subscriptionData['browser'] = 'Safari';
wiz.saveToLSorCookie(STRING_CONSTANTS.PUSH_SUBSCRIPTION_DATA, subscriptionData);
wiz.registerToken(subscriptionData);
wc.l('Safari Web Push registered. Device Token: ' + subscription['deviceToken']);
} else if (subscription.permission === 'denied') {
wc.l('Error subscribing to Safari web push');
}
});
}
}
/**
* Sets up a service worker for WebPush(chrome/Firefox) push notifications and sends the data to LC
*/
wiz.setUpChromeFirefoxNotifications = function (subscriptionCallback, serviceWorkerPath) {
if ('serviceWorker' in navigator) {
navigator["serviceWorker"]['register'](serviceWorkerPath)['then'](function (registration) {
if (typeof __wzrk_account_id !== "undefined") {
//shopify accounts , since the service worker is not at root, serviceWorker.ready is never resolved.
// hence add a timeout and hope serviceWroker is ready within that time.
return new Promise(resolve => setTimeout(() => resolve(registration), 5000));
}
return navigator['serviceWorker']['ready'];
})['then'](function (serviceWorkerRegistration) {
var subscribeObj = { "userVisibleOnly": true }
if(fcmPublicKey != null) {
subscribeObj["applicationServerKey"] = urlBase64ToUint8Array(fcmPublicKey)
}
serviceWorkerRegistration['pushManager']['subscribe'](subscribeObj)
['then'](function (subscription) {
wc.l('Service Worker registered. Endpoint: ' + subscription['endpoint']);
// convert the subscription keys to strings; this sets it up nicely for pushing to LC
var subscriptionData = JSON.parse(JSON.stringify(subscription));
// remove the common chrome/firefox endpoint at the beginning of the token
if(navigator.userAgent.indexOf('Chrome') !== -1){
subscriptionData['endpoint'] = subscriptionData['endpoint'].split('/').pop();
subscriptionData['browser'] = 'Chrome';
}else if(navigator.userAgent.indexOf('Firefox') !== -1){
subscriptionData['endpoint'] = subscriptionData['endpoint'].split('/').pop();
subscriptionData['browser'] = 'Firefox';
}
var sessionObj = wiz.getSessionCookieObject();
// var shouldSendToken = typeof sessionObj['p'] === STRING_CONSTANTS.UNDEFINED || sessionObj['p'] === 1
// || sessionObj['p'] === 2 || sessionObj['p'] === 3 || sessionObj['p'] === 4 || sessionObj['p'] === 5;
wiz.saveToLSorCookie(STRING_CONSTANTS.PUSH_SUBSCRIPTION_DATA, subscriptionData);
var shouldSendToken = true;
if (shouldSendToken) {
wiz.registerToken(subscriptionData);
}
if (typeof subscriptionCallback !== "undefined" && typeof subscriptionCallback === "function") {
subscriptionCallback();
}
})['catch'](function (error) {
wc.l('Error subscribing: ' + error);
//unsubscribe from webpush if error
serviceWorkerRegistration['pushManager']['getSubscription']()['then'](function (subscription) {
if (subscription !== null) {
subscription['unsubscribe']()['then'](function (successful) {
// You've successfully unsubscribed
wc.l('Unsubscription successful');
})['catch'](function (e) {
// Unsubscription failed
wc.l('Error unsubscribing: ' + e)
})
}
})
});
})['catch'](function (err) {
wc.l('error registering service worker: ' + err);
});
}
};
wiz.registerToken = function (subscriptionData) {
if (!subscriptionData) return;
var payload = subscriptionData;
payload = wiz.addSystemDataToObject(payload, true);
payload = JSON.stringify(payload);
var pageLoadUrl = dataPostURL;
pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", "data");
pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", wiz.compressData(payload));
wiz.fireRequest(pageLoadUrl);
//set in localstorage
if (wzrk_util.isLocalStorageSupported()) {
window['localStorage'].setItem(STRING_CONSTANTS.WEBPUSH_LS_KEY, 'ok');
}
}
wiz.getCleverTapID = function () {
return gcookie;
};
wiz.init = function () {
wc = {
e: function (msg) {
if (window.console) {
var ts = new Date().getTime();
console.error(ts + " " + msg);
}
},
d: function (msg) {
if (window.console && wiz.isDebug()) {
var ts = new Date().getTime();
console.debug(ts + " " + msg);
}
},
l: function (msg) {
if (window.console) {
var ts = new Date().getTime();
console.log(ts + " " + msg);
}
}
};
//delete pcookie
wiz.deleteCookie("WZRK_P", window.location.hostname);
wiz.g(); // load cookies on pageload; this HAS to be the first thing in this method
if (typeof wizrocket['account'][0] == STRING_CONSTANTS.UNDEFINED) {
wc.e(wzrk_msg['embed-error']);
return;
} else {
accountId = wizrocket['account'][0]['id'];
if (typeof accountId == STRING_CONSTANTS.UNDEFINED || accountId == '') {
wc.e(wzrk_msg['embed-error']);
return;
}
SCOOKIE_NAME = STRING_CONSTANTS.SCOOKIE_PREFIX + '_' + accountId;
}
if (typeof wizrocket['region'] != STRING_CONSTANTS.UNDEFINED) {
region = wizrocket['region'];
targetDomain = region + '.' + targetDomain;
}
dataPostURL = wz_pr + '//' + targetDomain + '/a?t=96';
recorderURL = wz_pr + '//' + targetDomain + '/r?r=1';
emailURL = wz_pr + '//' + targetDomain + '/e?r=1';
var currLocation = location.href;
var url_params = wzrk_util.getURLParams(location.href.toLowerCase());
if (typeof url_params['e'] != STRING_CONSTANTS.UNDEFINED && url_params['wzrk_ex'] == '0') {
return;
}
wiz.processBackupEvents();
wiz.overloadArrayPush();
// -- update page count
var obj = wiz.getSessionCookieObject();
var pgCount = (typeof obj['p'] == STRING_CONSTANTS.UNDEFINED) ? 0 : obj['p'];
obj['p'] = ++pgCount;
wiz.setSessionCookieObject(obj);
// -- update page count
var data = {};
//var curr_domain = doc.location.hostname;
var referrer_domain = wzrk_util.getDomain(doc.referrer);
if (domain != referrer_domain) {
var maxLen = 120;
if (referrer_domain != "") { //referrer exists, sending even when session exists as "x.in.com" and "y.in.com" could be separate accounts, but session created on domain "in.com"
referrer_domain = referrer_domain.length > maxLen ? referrer_domain.substring(0, maxLen) : referrer_domain;
data['referrer'] = referrer_domain;
}
var utm_source = url_params['utm_source'] || url_params['wzrk_source'];
if (typeof utm_source != STRING_CONSTANTS.UNDEFINED) {
utm_source = utm_source.length > maxLen ? utm_source.substring(0, maxLen) : utm_source;
data['us'] = utm_source; //utm_source
}
var utm_medium = url_params['utm_medium'] || url_params['wzrk_medium'];
if (typeof utm_medium != STRING_CONSTANTS.UNDEFINED) {
utm_medium = utm_medium.length > maxLen ? utm_medium.substring(0, maxLen) : utm_medium;
data['um'] = utm_medium; //utm_medium
}
var utm_campaign = url_params['utm_campaign'] || url_params['wzrk_campaign'];
if (typeof utm_campaign != STRING_CONSTANTS.UNDEFINED) {
utm_campaign = utm_campaign.length > maxLen ? utm_campaign.substring(0, maxLen) : utm_campaign;
data['uc'] = utm_campaign; //utm_campaign
}
// also independently send wzrk_medium to the backend
if (typeof url_params['wzrk_medium'] != STRING_CONSTANTS.UNDEFINED) {
var wm = url_params['wzrk_medium'];
if (wm.match(/^email$|^social$|^search$/)) {
data['wm'] = wm; //wzrk_medium
}
}
}
data = wiz.addSystemDataToObject(data, undefined);
data['cpg'] = currLocation;
data[STRING_CONSTANTS.CAMP_COOKIE_NAME] = wiz.getCampaignObjForLc();
var pageLoadUrl = dataPostURL;
wiz.addFlags(data);
//send dsync flag when page = 1
if (data['pg'] != STRING_CONSTANTS.UNDEFINED && data['pg'] == 1) {
wiz.overrideDSyncFlag(data);
}
pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", "page");
pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", wiz.compressData(JSON.stringify(data)));
wiz.saveAndFireRequest(pageLoadUrl, false);
// -- ping request logic
var pingRequest = function () {
var pageLoadUrl = dataPostURL;
var data = {};
data = wiz.addSystemDataToObject(data, undefined);
pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", EVT_PING);
pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", wiz.compressData(JSON.stringify(data)));
wiz.saveAndFireRequest(pageLoadUrl, false);
};
setTimeout(function () {
if (pgCount <= 3) { // send ping for up to 3 pages
pingRequest();
}
if (wiz.isPingContinuous()) {
setInterval(function () {
pingRequest();
}, CONTINUOUS_PING_FREQ_IN_MILLIS);
}
}, FIRST_PING_FREQ_IN_MILLIS);
// -- ping request logic
if (typeof wizrocket['session'] == STRING_CONSTANTS.UNDEFINED) {
wizrocket['event']['getDetails'] = function (evtName) {
if (!wzrk_util.isPersonalizationActive()) {
return;
}
if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) {
globalEventsMap = wiz.readFromLSorCookie(STRING_CONSTANTS.EV_COOKIE);
}
if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) {
return;
}
var evtObj = globalEventsMap[evtName];
var respObj = {};
if (typeof evtObj != STRING_CONSTANTS.UNDEFINED) {
respObj['firstTime'] = new Date(evtObj[1] * 1000);
respObj['lastTime'] = new Date(evtObj[2] * 1000);
respObj['count'] = evtObj[0];
return respObj;
}
};
wizrocket['profile']['getAttribute'] = function (propName) {
if (!wzrk_util.isPersonalizationActive()) {
return;
}
if (typeof globalProfileMap == STRING_CONSTANTS.UNDEFINED) {
globalProfileMap = wiz.readFromLSorCookie(STRING_CONSTANTS.PR_COOKIE);
}
if (typeof globalProfileMap != STRING_CONSTANTS.UNDEFINED) {
return globalProfileMap[propName];
}
};
wizrocket['session'] = {};
wizrocket['session']['getTimeElapsed'] = function () {
if (!wzrk_util.isPersonalizationActive()) {
return;
}
if (typeof scookieObj != STRING_CONSTANTS.UNDEFINED) {
scookieObj = wiz.getSessionCookieObject();
}
var sessionStart = scookieObj['s'];
if (typeof sessionStart != STRING_CONSTANTS.UNDEFINED) {
var ts = wzrk_util.getNow();
return Math.floor(ts - sessionStart);
}
};
wizrocket['user'] = {};
wizrocket['user']['getTotalVisits'] = function () {
if (!wzrk_util.isPersonalizationActive()) {
return;
}
var visitCount = wiz.getMetaProp('sc');
if (typeof visitCount == STRING_CONSTANTS.UNDEFINED) {
visitCount = 1;
}
return visitCount;
};
wizrocket['session']['getPageCount'] = function () {
if (!wzrk_util.isPersonalizationActive()) {
return;
}
if (typeof scookieObj != STRING_CONSTANTS.UNDEFINED) {
scookieObj = wiz.getSessionCookieObject();
}
return scookieObj['p'];
};
wizrocket['user']['getLastVisit'] = function () {
if (!wzrk_util.isPersonalizationActive()) {
return;
}
var prevSession = wiz.getMetaProp('ps');
if (typeof prevSession != STRING_CONSTANTS.UNDEFINED) {
return new Date(prevSession * 1000);
}
};
}
onloadcalled = 1; //always the last line in this function
};
wiz.readFromLSorCookie = function (property) {
var data;
if (globalCache.hasOwnProperty(property)) {
return globalCache[property];
}
if (wzrk_util.isLocalStorageSupported()) {
data = window['localStorage'][property];
} else {
data = wiz.readCookie(property);
}
if (typeof data != STRING_CONSTANTS.UNDEFINED && data !== null && data.trim() != '') {
var value = JSON.parse(decodeURIComponent(data));
globalCache[property] = value;
return value;
}
};
wiz.saveToLSorCookie = function (property, val) {
if (typeof val == STRING_CONSTANTS.UNDEFINED || val == null) {
return;
}
try {
if (wzrk_util.isLocalStorageSupported()) {
window['localStorage'][property] = encodeURIComponent(JSON.stringify(val));
} else {
if (property === STRING_CONSTANTS.GCOOKIE_NAME) {
wiz.createCookie(property, encodeURIComponent(val), 0, domain);
} else {
wiz.createCookie(property, encodeURIComponent(JSON.stringify(val)), 0, domain);
}
}
globalCache[property] = val;
} catch (e) {
}
};
var processEvent = function (data) {
wiz.addToLocalEventMap(data['evtName']);
data = wiz.addSystemDataToObject(data, undefined);
wiz.addFlags(data);
data[STRING_CONSTANTS.CAMP_COOKIE_NAME] = wiz.getCampaignObjForLc();
var compressedData = wiz.compressData(JSON.stringify(data));
var pageLoadUrl = dataPostURL;
pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", EVT_PUSH);
pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", compressedData);
wiz.saveAndFireRequest(pageLoadUrl, false);
};
wiz.processEventArray = function (eventArr) {
if (wzrk_util.isArray(eventArr)) {
/** looping since the events could be fired in quick succession, and we could end up
with multiple pushes without getting a chance to process
*/
while (eventArr.length > 0) {
var eventName = eventArr.shift(); // take out name of the event
if (!wzrk_util.isString(eventName)) {
wc.e(wzrk_msg['event-error']);
return;
}
if (eventName.length > 1024) {
eventName = eventName.substring(0, 1024);
wiz.reportError(510, eventName + "... length exceeded 1024 chars. Trimmed.");
}
if (eventName == "Stayed" || eventName == "UTM Visited" || eventName == "App Launched" ||
eventName == "Notification Sent" || eventName == "Notification Viewed" || eventName == "Notification Clicked") {
wiz.reportError(513, eventName + " is a restricted system event. It cannot be used as an event name.");
continue;
}
var data = {};
data['type'] = "event";
data['evtName'] = wzrk_util.sanitize(eventName, unsupportedKeyCharRegex);
if (eventArr.length != 0) {
var eventObj = eventArr.shift();
if (!wzrk_util.isObject(eventObj)) {
eventArr.unshift(eventObj); // put it back if it is not an object
} else {
//check Charged Event vs. other events.
if (eventName == "Charged") {
if (!wiz.isChargedEventStructureValid(eventObj)) {
wiz.reportError(511, "Charged event structure invalid. Not sent.");
continue;
}
} else {
if (!wiz.isEventStructureFlat(eventObj)) {
wiz.reportError(512, eventName + " event structure invalid. Not sent.");
continue;
}
}
data['evtData'] = eventObj;
}
}
processEvent(data);
}
}
};
wiz.addToLocalEventMap = function (evtName) {
if (wzrk_util.isLocalStorageSupported()) {
if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) {
globalEventsMap = wiz.readFromLSorCookie(STRING_CONSTANTS.EV_COOKIE);
if (typeof globalEventsMap == STRING_CONSTANTS.UNDEFINED) {
globalEventsMap = {};
}
}
var nowTs = wzrk_util.getNow();
var evtDetail = globalEventsMap[evtName];
if (typeof evtDetail != STRING_CONSTANTS.UNDEFINED) {
evtDetail[2] = nowTs;
evtDetail[0]++;
} else {
evtDetail = [];
evtDetail.push(1);
evtDetail.push(nowTs);
evtDetail.push(nowTs);
}
globalEventsMap[evtName] = evtDetail;
wiz.saveToLSorCookie(STRING_CONSTANTS.EV_COOKIE, globalEventsMap);
}
};
wiz.addToLocalProfileMap = function (profileObj, override) {
if (wzrk_util.isLocalStorageSupported()) {
if (typeof globalProfileMap == STRING_CONSTANTS.UNDEFINED) {
globalProfileMap = wiz.readFromLSorCookie(STRING_CONSTANTS.PR_COOKIE);
if (typeof globalProfileMap == STRING_CONSTANTS.UNDEFINED) {
globalProfileMap = {};
}
}
//Move props from custom bucket to outside.
if (typeof profileObj['_custom'] != STRING_CONSTANTS.UNDEFINED) {
var keys = profileObj['_custom'];
for (var key in keys) {
if (keys.hasOwnProperty(key)) {
profileObj[key] = keys[key];
}
}
delete profileObj['_custom'];
}
for (var prop in profileObj) {
if (profileObj.hasOwnProperty(prop)) {
if (globalProfileMap.hasOwnProperty(prop) && !override) {
continue;
}
globalProfileMap[prop] = profileObj[prop];
}
}
if (typeof globalProfileMap['_custom'] != STRING_CONSTANTS.UNDEFINED) {
delete globalProfileMap['_custom'];
}
wiz.saveToLSorCookie(STRING_CONSTANTS.PR_COOKIE, globalProfileMap);
}
};
wiz.overrideDSyncFlag = function (data) {
if (wzrk_util.isPersonalizationActive()) {
data['dsync'] = true;
}
};
wiz.addARPToRequest = function (url, skipResARP) {
if(typeof skipResARP !== STRING_CONSTANTS.UNDEFINED && skipResARP === true) {
var _arp = {};
_arp["skipResARP"] = true;
return wiz.addToURL(url, 'arp', wiz.compressData(JSON.stringify(_arp)));
}
if (wzrk_util.isLocalStorageSupported() && typeof window['localStorage'][STRING_CONSTANTS.ARP_COOKIE] != STRING_CONSTANTS.UNDEFINED) {
return wiz.addToURL(url, 'arp', wiz.compressData(JSON.stringify(wiz.readFromLSorCookie(STRING_CONSTANTS.ARP_COOKIE))));
}
return url;
};
wiz.addFlags = function (data) {
//check if cookie should be cleared.
clearCookie = wiz.getAndClearMetaProp(STRING_CONSTANTS.CLEAR);
if (clearCookie !== undefined && clearCookie) {
data['rc'] = true;
wc.d("reset cookie sent in request and cleared from meta for future requests.");
}
if (wzrk_util.isPersonalizationActive()) {
var lastSyncTime = wiz.getMetaProp('lsTime');
var expirySeconds = wiz.getMetaProp('exTs');
//dsync not found in local storage - get data from server
if (typeof lastSyncTime == STRING_CONSTANTS.UNDEFINED || typeof expirySeconds == STRING_CONSTANTS.UNDEFINED) {
data['dsync'] = true;
return;
}
var now = wzrk_util.getNow();
//last sync time has expired - get fresh data from server
if (lastSyncTime + expirySeconds < now) {
data['dsync'] = true;
}
}
};
var unregisterTokenForGuid = function (givenGUID) {
var data = {};
data["type"] = "data";
if (wiz.isValueValid(givenGUID)) {
data["g"] = givenGUID;
}
data["action"] = "unregister";
data["id"] = accountId;
var obj = wiz.getSessionCookieObject();
data["s"] = obj["s"]; //Session cookie
var compressedData = wiz.compressData(JSON.stringify(data));
var pageLoadUrl = dataPostURL;
pageLoadUrl = wiz.addToURL(pageLoadUrl, "type", "data");
pageLoadUrl = wiz.addToURL(pageLoadUrl, "d", compressedData);
wiz.saveToLSorCookie(STRING_CONSTANTS.FIRE_PUSH_UNREGISTERED, false)
wiz.fireRequest(pageLoadUrl, true);
// Register token for the current user
const subscriptionData = wiz.readFromLSorCookie(STRING_CONSTANTS.PUSH_SUBSCRIPTION_DATA);
wiz.registerToken(subscriptionData);
};
var LRU_cache = function (max) {
this.max = max;
var keyOrder;
var LRU_CACHE = wiz.readFromLSorCookie(STRING_CONSTANTS.LRU_CACHE);
if (LRU_CACHE) {
var lru_cache = {};
keyOrder = [];
LRU_CACHE = LRU_CACHE.cache;
for (var entry in LRU_CACHE) {
if(LRU_CACHE.hasOwnProperty(entry)) {
lru_cache[LRU_CACHE[entry][0]] = LRU_CACHE[entry][1];
keyOrder.push(LRU_CACHE[entry][0]);
}
}
this.cache = lru_cache;
} else {
this.cache = {};
keyOrder = [];
}
this.get = function (key) {
var item = this.cache[key];
if (item) {
var temp_val = item;
this.cache = deleteFromObject(key, this.cache);
this.cache[key] = item;
keyOrder.push(key);
}
this.saveCacheToLS(this.cache);
return item;
};
this.set = function (key, value) {
var item = this.cache[key];
var all_keys = keyOrder;
if (item != null) {
this.cache = deleteFromObject(key, this.cache);
} else if (all_keys.length === this.max) {
this.cache = deleteFromObject(
all_keys[0],
this.cache
);
}
this.cache[key] = value;
if (keyOrder[keyOrder.length - 1] !== key) {
keyOrder.push(key);
}
this.saveCacheToLS(this.cache);
};
this.saveCacheToLS = function (cache) {
var obj_to_array = [];
var all_keys = keyOrder;
for (var index in all_keys) {
if(all_keys.hasOwnProperty(index)) {
var temp = [];
temp.push(all_keys[index]);
temp.push(cache[all_keys[index]]);
obj_to_array.push(temp);
}
}
wiz.saveToLSorCookie(STRING_CONSTANTS.LRU_CACHE, {
cache: obj_to_array
});
};
this.getKEY = function (givenVal) {
if (givenVal == null) return null;
var all_keys = keyOrder;
for (var index in all_keys) {
if(all_keys.hasOwnProperty(index)) {
if (
this.cache[all_keys[index]] != null &&
this.cache[all_keys[index]] === givenVal
) {
return all_keys[index];
}
}
}
return null;
};
this.getSecondLastKEY = function () {
var keysArr = keyOrder;
if (keysArr != null && keysArr.length > 1) {
return keysArr[keysArr.length - 2];
} else {
return -1;
}
};
this.getLastKey = function () {
if (keyOrder.length) {
return keyOrder[keyOrder.length - 1];
}
};
var deleteFromObject = function (key, obj) {
var all_keys = JSON.parse(JSON.stringify(keyOrder));
var new_cache = {};
var indexToDelete;
for (var index in all_keys) {
if(all_keys.hasOwnProperty(index)) {
if (all_keys[index] !== key) {
new_cache[all_keys[index]] = obj[all_keys[index]];
} else {
indexToDelete = index;
}
}
}
all_keys.splice(indexToDelete, 1);
keyOrder = JSON.parse(JSON.stringify(all_keys));
return new_cache;
};
};
wiz.getCampaignObjForLc = function () {
var campObj = {};
if (wzrk_util.isLocalStorageSupported()) {
campObj = wzrk_util.getCampaignObject();
var resultObj = [];
var globalObj = campObj['global'];
var today = wzrk_util.getToday();
var dailyObj = campObj[today];
if (typeof globalObj != STRING_CONSTANTS.UNDEFINED) {
var campaignIdArray = Object.keys(globalObj);
for (var index in campaignIdArray) {
if (campaignIdArray.hasOwnProperty(index)) {
var dailyC = 0;
var totalC = 0;
var campaignId = campaignIdArray[index];
if (campaignId == 'tc') {
continue;
}
if (typeof dailyObj != STRING_CONSTANTS.UNDEFINED && typeof dailyObj[campaignId] != STRING_CONSTANTS.UNDEFINED) {
dailyC = dailyObj[campaignId];
}
if (typeof globalObj != STRING_CONSTANTS.UNDEFINED && typeof globalObj[campaignId] != STRING_CONSTANTS.UNDEFINED) {
totalC = globalObj[campaignId];
}
var element = [campaignId, dailyC, totalC];
resultObj.push(element);
}
}
}
var todayC = 0;
if (typeof dailyObj != STRING_CONSTANTS.UNDEFINED && typeof dailyObj['tc'] != STRING_CONSTANTS.UNDEFINED) {
todayC = dailyObj['tc'];
}
resultObj = {"wmp": todayC, 'tlc': resultObj};
return resultObj;
}
};
var handleCookieFromCache = function () {
blockRequeust = false;
wc.d("Block request is false");
if (wzrk_util.isLocalStorageSupported()) {
delete window['localStorage'][STRING_CONSTANTS.PR_COOKIE];
delete window['localStorage'][STRING_CONSTANTS.EV_COOKIE];
delete window['localStorage'][STRING_CONSTANTS.META_COOKIE];
delete window['localStorage'][STRING_CONSTANTS.ARP_COOKIE];
delete window['localStorage'][STRING_CONSTANTS.CAMP_COOKIE_NAME];
delete window['localStorage'][STRING_CONSTANTS.CHARGEDID_COOKIE_NAME];
}
wiz.deleteCookie(STRING_CONSTANTS.CAMP_COOKIE_NAME, domain);
wiz.deleteCookie(SCOOKIE_NAME, broadDomain);
wiz.deleteCookie(STRING_CONSTANTS.ARP_COOKIE, broadDomain);
scookieObj = '';
};
var deleteUser = function () {
blockRequeust = true;
wc.d("Block request is true");
globalCache = {};
if (wzrk_util.isLocalStorageSupported()) {
delete window['localStorage'][STRING_CONSTANTS.GCOOKIE_NAME];
delete window['localStorage'][STRING_CONSTANTS.KCOOKIE_NAME];
delete window['localStorage'][STRING_CONSTANTS.PR_COOKIE];
delete window['localStorage'][STRING_CONSTANTS.EV_COOKIE];
delete window['localStorage'][STRING_CONSTANTS.META_COOKIE];
delete window['localStorage'][STRING_CONSTANTS.ARP_COOKIE];
delete window['localStorage'][STRING_CONSTANTS.CAMP_COOKIE_NAME];
delete window['localStorage'][STRING_CONSTANTS.CHARGEDID_COOKIE_NAME];
}
wiz.deleteCookie(STRING_CONSTANTS.GCOOKIE_NAME, broadDomain);
wiz.deleteCookie(STRING_CONSTANTS.CAMP_COOKIE_NAME, domain);
wiz.deleteCookie(STRING_CONSTANTS.KCOOKIE_NAME, domain);
wiz.deleteCookie(SCOOKIE_NAME, broadDomain);
wiz.deleteCookie(STRING_CONSTANTS.ARP_COOKIE, broadDomain);
gcookie = null;
scookieObj = '';
};
var setInstantDeleteFlagInK = function () {
var k = wiz.readFromLSorCookie(STRING_CONSTANTS.KCOOKIE_NAME);
if (typeof k == STRING_CONSTANTS.UNDEFINED) {
k = {};
}
k['flag'] = true;
wiz.saveToLSorCookie(STRING_CONSTANTS.KCOOKIE_NAME, k);
};
wiz.logout = function () {
wc.d("logout called");
setInstantDeleteFlagInK();
};
wiz.clear = function () {
wc.d("clear called. Reset flag has been set.");
deleteUser();
wiz.setMetaProp(STRING_CONSTANTS.CLEAR, true);
};
/*
We dont set the arp in cache for deregister requests.
For deregister requests we check for 'skipResARP' flag payload. If present we skip it.
Whenever we get 'isOUL' flag true in payload we delete the existing ARP instead of updating it.
*/
wiz.arp = function (jsonMap) {
// For unregister calls dont set arp in LS
if(typeof jsonMap["skipResARP"] !== STRING_CONSTANTS.UNDEFINED && jsonMap["skipResARP"]) {
wc.d("Update ARP Request rejected", jsonMap);
return null;
}
var isOULARP = (typeof jsonMap[STRING_CONSTANTS.IS_OUL] !== STRING_CONSTANTS.UNDEFINED
&& jsonMap[STRING_CONSTANTS.IS_OUL] === true) ? true : false;