@usermaven/sdk-js 1.0.0 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -221,10 +221,1506 @@ function createLogger(logLevel) {
221
221
  return logger;
222
222
  }
223
223
 
224
+ var Config$1 = {
225
+ DEBUG: false,
226
+ LIB_VERSION: '1.0.0',
227
+ };
228
+
229
+ /* eslint camelcase: "off", eqeqeq: "off" */
230
+
231
+ /*
232
+ * Saved references to long variable names, so that closure compiler can
233
+ * minimize file size.
234
+ */
235
+
236
+ const ArrayProto = Array.prototype,
237
+ FuncProto = Function.prototype,
238
+ ObjProto = Object.prototype,
239
+ slice = ArrayProto.slice,
240
+ toString = ObjProto.toString,
241
+ hasOwnProperty = ObjProto.hasOwnProperty,
242
+ win = typeof window !== 'undefined' ? window : {},
243
+ navigator$1 = win.navigator || { userAgent: '' },
244
+ document$1 = win.document || {},
245
+ userAgent = navigator$1.userAgent;
246
+
247
+ const nativeBind = FuncProto.bind,
248
+ nativeForEach = ArrayProto.forEach,
249
+ nativeIndexOf = ArrayProto.indexOf,
250
+ nativeIsArray = Array.isArray,
251
+ breaker = {};
252
+
253
+ var _ = {
254
+ trim: function (str) {
255
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
256
+ return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '')
257
+ },
258
+ };
259
+
260
+ // Console override
261
+ var console$1 = {
262
+ /** @type {function(...*)} */
263
+ log: function () {
264
+ },
265
+ /** @type {function(...*)} */
266
+ error: function () {
267
+ },
268
+ /** @type {function(...*)} */
269
+ critical: function () {
270
+ if (!_.isUndefined(window.console) && window.console) {
271
+ var args = ['UserMaven error:', ...arguments];
272
+ try {
273
+ window.console.error.apply(window.console, args);
274
+ } catch (err) {
275
+ _.each(args, function (arg) {
276
+ window.console.error(arg);
277
+ });
278
+ }
279
+ }
280
+ },
281
+ };
282
+
283
+ // UNDERSCORE
284
+ // Embed part of the Underscore Library
285
+ _.bind = function (func, context) {
286
+ var args, bound;
287
+ if (nativeBind && func.bind === nativeBind) {
288
+ return nativeBind.apply(func, slice.call(arguments, 1))
289
+ }
290
+ if (!_.isFunction(func)) {
291
+ throw new TypeError()
292
+ }
293
+ args = slice.call(arguments, 2);
294
+ bound = function () {
295
+ if (!(this instanceof bound)) {
296
+ return func.apply(context, args.concat(slice.call(arguments)))
297
+ }
298
+ var ctor = {};
299
+ ctor.prototype = func.prototype;
300
+ var self = new ctor();
301
+ ctor.prototype = null;
302
+ var result = func.apply(self, args.concat(slice.call(arguments)));
303
+ if (Object(result) === result) {
304
+ return result
305
+ }
306
+ return self
307
+ };
308
+ return bound
309
+ };
310
+
311
+ _.bind_instance_methods = function (obj) {
312
+ for (var func in obj) {
313
+ if (typeof obj[func] === 'function') {
314
+ obj[func] = _.bind(obj[func], obj);
315
+ }
316
+ }
317
+ };
318
+
319
+ /**
320
+ * @param {*=} obj
321
+ * @param {function(...*)=} iterator
322
+ * @param {Object=} context
323
+ */
324
+ _.each = function (obj, iterator, context) {
325
+ if (obj === null || obj === undefined) {
326
+ return
327
+ }
328
+ if (nativeForEach && obj.forEach === nativeForEach) {
329
+ obj.forEach(iterator, context);
330
+ } else if (obj.length === +obj.length) {
331
+ for (var i = 0, l = obj.length; i < l; i++) {
332
+ if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) {
333
+ return
334
+ }
335
+ }
336
+ } else {
337
+ for (var key in obj) {
338
+ if (hasOwnProperty.call(obj, key)) {
339
+ if (iterator.call(context, obj[key], key, obj) === breaker) {
340
+ return
341
+ }
342
+ }
343
+ }
344
+ }
345
+ };
346
+
347
+ _.extend = function (obj) {
348
+ _.each(slice.call(arguments, 1), function (source) {
349
+ for (var prop in source) {
350
+ if (source[prop] !== void 0) {
351
+ obj[prop] = source[prop];
352
+ }
353
+ }
354
+ });
355
+ return obj
356
+ };
357
+
358
+ _.isArray =
359
+ nativeIsArray ||
360
+ function (obj) {
361
+ return toString.call(obj) === '[object Array]'
362
+ };
363
+
364
+ // from a comment on http://dbj.org/dbj/?p=286
365
+ // fails on only one very rare and deliberate custom object:
366
+ // var bomb = { toString : undefined, valueOf: function(o) { return "function BOMBA!"; }};
367
+ _.isFunction = function (f) {
368
+ try {
369
+ return /^\s*\bfunction\b/.test(f)
370
+ } catch (x) {
371
+ return false
372
+ }
373
+ };
374
+
375
+ _.include = function (obj, target) {
376
+ var found = false;
377
+ if (obj === null) {
378
+ return found
379
+ }
380
+ if (nativeIndexOf && obj.indexOf === nativeIndexOf) {
381
+ return obj.indexOf(target) != -1
382
+ }
383
+ _.each(obj, function (value) {
384
+ if (found || (found = value === target)) {
385
+ return breaker
386
+ }
387
+ });
388
+ return found
389
+ };
390
+
391
+ _.includes = function (str, needle) {
392
+ return str.indexOf(needle) !== -1
393
+ };
394
+
395
+ // Underscore Addons
396
+ _.isObject = function (obj) {
397
+ return obj === Object(obj) && !_.isArray(obj)
398
+ };
399
+
400
+ _.isEmptyObject = function (obj) {
401
+ if (_.isObject(obj)) {
402
+ for (var key in obj) {
403
+ if (hasOwnProperty.call(obj, key)) {
404
+ return false
405
+ }
406
+ }
407
+ return true
408
+ }
409
+ return false
410
+ };
411
+
412
+ _.isUndefined = function (obj) {
413
+ return obj === void 0
414
+ };
415
+
416
+ _.isString = function (obj) {
417
+ return toString.call(obj) == '[object String]'
418
+ };
419
+
420
+ _.isDate = function (obj) {
421
+ return toString.call(obj) == '[object Date]'
422
+ };
423
+
424
+ _.isNumber = function (obj) {
425
+ return toString.call(obj) == '[object Number]'
426
+ };
427
+
428
+ _.encodeDates = function (obj) {
429
+ _.each(obj, function (v, k) {
430
+ if (_.isDate(v)) {
431
+ obj[k] = _.formatDate(v);
432
+ } else if (_.isObject(v)) {
433
+ obj[k] = _.encodeDates(v); // recurse
434
+ }
435
+ });
436
+ return obj
437
+ };
438
+
439
+ _.timestamp = function () {
440
+ Date.now =
441
+ Date.now ||
442
+ function () {
443
+ return +new Date()
444
+ };
445
+ return Date.now()
446
+ };
447
+
448
+ _.formatDate = function (d) {
449
+ // YYYY-MM-DDTHH:MM:SS in UTC
450
+ function pad(n) {
451
+ return n < 10 ? '0' + n : n
452
+ }
453
+ return (
454
+ d.getUTCFullYear() +
455
+ '-' +
456
+ pad(d.getUTCMonth() + 1) +
457
+ '-' +
458
+ pad(d.getUTCDate()) +
459
+ 'T' +
460
+ pad(d.getUTCHours()) +
461
+ ':' +
462
+ pad(d.getUTCMinutes()) +
463
+ ':' +
464
+ pad(d.getUTCSeconds())
465
+ )
466
+ };
467
+
468
+ _.safewrap = function (f) {
469
+ return function () {
470
+ try {
471
+ return f.apply(this, arguments)
472
+ } catch (e) {
473
+ console$1.critical('Implementation error. Please turn on debug and contact support@usermaven.com.');
474
+ }
475
+ }
476
+ };
477
+
478
+ _.safewrap_class = function (klass, functions) {
479
+ for (var i = 0; i < functions.length; i++) {
480
+ klass.prototype[functions[i]] = _.safewrap(klass.prototype[functions[i]]);
481
+ }
482
+ };
483
+
484
+ _.safewrap_instance_methods = function (obj) {
485
+ for (var func in obj) {
486
+ if (typeof obj[func] === 'function') {
487
+ obj[func] = _.safewrap(obj[func]);
488
+ }
489
+ }
490
+ };
491
+
492
+ _.strip_empty_properties = function (p) {
493
+ var ret = {};
494
+ _.each(p, function (v, k) {
495
+ if (_.isString(v) && v.length > 0) {
496
+ ret[k] = v;
497
+ }
498
+ });
499
+ return ret
500
+ };
501
+
502
+ // Deep copies an object.
503
+ // It handles cycles by replacing all references to them with `undefined`
504
+ // Also supports customizing native values
505
+ const COPY_IN_PROGRESS_ATTRIBUTE =
506
+ typeof Symbol !== 'undefined' ? Symbol('__deepCircularCopyInProgress__') : '__deepCircularCopyInProgress__';
507
+
508
+ function deepCircularCopy(value, customizer) {
509
+ if (value !== Object(value)) return customizer ? customizer(value) : value // primitive value
510
+
511
+ if (value[COPY_IN_PROGRESS_ATTRIBUTE]) return undefined
512
+
513
+ value[COPY_IN_PROGRESS_ATTRIBUTE] = true;
514
+ let result;
515
+
516
+ if (_.isArray(value)) {
517
+ result = [];
518
+ _.each(value, (it) => {
519
+ result.push(deepCircularCopy(it, customizer));
520
+ });
521
+ } else {
522
+ result = {};
523
+ _.each(value, (val, key) => {
524
+ if (key !== COPY_IN_PROGRESS_ATTRIBUTE) {
525
+ result[key] = deepCircularCopy(val, customizer);
526
+ }
527
+ });
528
+ }
529
+ delete value[COPY_IN_PROGRESS_ATTRIBUTE];
530
+ return result
531
+ }
532
+
533
+ _.copyAndTruncateStrings = (object, maxStringLength) =>
534
+ deepCircularCopy(
535
+ object,
536
+ (value) => {
537
+ if (typeof value === 'string' && maxStringLength !== null) {
538
+ value = value.slice(0, maxStringLength);
539
+ }
540
+ return value
541
+ });
542
+
543
+ _.base64Encode = function (data) {
544
+ var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
545
+ var o1,
546
+ o2,
547
+ o3,
548
+ h1,
549
+ h2,
550
+ h3,
551
+ h4,
552
+ bits,
553
+ i = 0,
554
+ ac = 0,
555
+ enc = '',
556
+ tmp_arr = [];
557
+
558
+ if (!data) {
559
+ return data
560
+ }
561
+
562
+ data = _.utf8Encode(data);
563
+
564
+ do {
565
+ // pack three octets into four hexets
566
+ o1 = data.charCodeAt(i++);
567
+ o2 = data.charCodeAt(i++);
568
+ o3 = data.charCodeAt(i++);
569
+
570
+ bits = (o1 << 16) | (o2 << 8) | o3;
571
+
572
+ h1 = (bits >> 18) & 0x3f;
573
+ h2 = (bits >> 12) & 0x3f;
574
+ h3 = (bits >> 6) & 0x3f;
575
+ h4 = bits & 0x3f;
576
+
577
+ // use hexets to index into b64, and append result to encoded string
578
+ tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
579
+ } while (i < data.length)
580
+
581
+ enc = tmp_arr.join('');
582
+
583
+ switch (data.length % 3) {
584
+ case 1:
585
+ enc = enc.slice(0, -2) + '==';
586
+ break
587
+ case 2:
588
+ enc = enc.slice(0, -1) + '=';
589
+ break
590
+ }
591
+
592
+ return enc
593
+ };
594
+
595
+ _.utf8Encode = function (string) {
596
+ string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
597
+
598
+ var utftext = '',
599
+ start,
600
+ end;
601
+ var stringl = 0,
602
+ n;
603
+
604
+ start = end = 0;
605
+ stringl = string.length;
606
+
607
+ for (n = 0; n < stringl; n++) {
608
+ var c1 = string.charCodeAt(n);
609
+ var enc = null;
610
+
611
+ if (c1 < 128) {
612
+ end++;
613
+ } else if (c1 > 127 && c1 < 2048) {
614
+ enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128);
615
+ } else {
616
+ enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
617
+ }
618
+ if (enc !== null) {
619
+ if (end > start) {
620
+ utftext += string.substring(start, end);
621
+ }
622
+ utftext += enc;
623
+ start = end = n + 1;
624
+ }
625
+ }
626
+
627
+ if (end > start) {
628
+ utftext += string.substring(start, string.length);
629
+ }
630
+
631
+ return utftext
632
+ };
633
+
634
+ _.UUID = (function () {
635
+ // Time/ticks information
636
+ // 1*new Date() is a cross browser version of Date.now()
637
+ var T = function () {
638
+ var d = 1 * new Date(),
639
+ i = 0;
640
+
641
+ // this while loop figures how many browser ticks go by
642
+ // before 1*new Date() returns a new number, ie the amount
643
+ // of ticks that go by per millisecond
644
+ while (d == 1 * new Date()) {
645
+ i++;
646
+ }
647
+
648
+ return d.toString(16) + i.toString(16)
649
+ };
650
+
651
+ // Math.Random entropy
652
+ var R = function () {
653
+ return Math.random().toString(16).replace('.', '')
654
+ };
655
+
656
+ // User agent entropy
657
+ // This function takes the user agent string, and then xors
658
+ // together each sequence of 8 bytes. This produces a final
659
+ // sequence of 8 bytes which it returns as hex.
660
+ var UA = function () {
661
+ var ua = userAgent,
662
+ i,
663
+ ch,
664
+ buffer = [],
665
+ ret = 0;
666
+
667
+ function xor(result, byte_array) {
668
+ var j,
669
+ tmp = 0;
670
+ for (j = 0; j < byte_array.length; j++) {
671
+ tmp |= buffer[j] << (j * 8);
672
+ }
673
+ return result ^ tmp
674
+ }
675
+
676
+ for (i = 0; i < ua.length; i++) {
677
+ ch = ua.charCodeAt(i);
678
+ buffer.unshift(ch & 0xff);
679
+ if (buffer.length >= 4) {
680
+ ret = xor(ret, buffer);
681
+ buffer = [];
682
+ }
683
+ }
684
+
685
+ if (buffer.length > 0) {
686
+ ret = xor(ret, buffer);
687
+ }
688
+
689
+ return ret.toString(16)
690
+ };
691
+
692
+ return function () {
693
+ var se = (window.screen.height * window.screen.width).toString(16);
694
+ return T() + '-' + R() + '-' + UA() + '-' + se + '-' + T()
695
+ }
696
+ })();
697
+
698
+ // _.isBlockedUA()
699
+ // This is to block various web spiders from executing our JS and
700
+ // sending false captureing data
701
+ _.isBlockedUA = function (ua) {
702
+ if (/(google web preview|baiduspider|yandexbot|bingbot|googlebot|yahoo! slurp)/i.test(ua)) {
703
+ return true
704
+ }
705
+ return false
706
+ };
707
+
708
+ /**
709
+ * @param {Object=} formdata
710
+ * @param {string=} arg_separator
711
+ */
712
+ _.HTTPBuildQuery = function (formdata, arg_separator) {
713
+ var use_val,
714
+ use_key,
715
+ tph_arr = [];
716
+
717
+ if (_.isUndefined(arg_separator)) {
718
+ arg_separator = '&';
719
+ }
720
+
721
+ _.each(formdata, function (val, key) {
722
+ use_val = encodeURIComponent(val.toString());
723
+ use_key = encodeURIComponent(key);
724
+ tph_arr[tph_arr.length] = use_key + '=' + use_val;
725
+ });
726
+
727
+ return tph_arr.join(arg_separator)
728
+ };
729
+
730
+ _.getQueryParam = function (url, param) {
731
+ // Expects a raw URL
732
+
733
+ param = param.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
734
+ var regexS = '[\\?&]' + param + '=([^&#]*)',
735
+ regex = new RegExp(regexS),
736
+ results = regex.exec(url);
737
+ if (results === null || (results && typeof results[1] !== 'string' && results[1].length)) {
738
+ return ''
739
+ } else {
740
+ var result = results[1];
741
+ try {
742
+ result = decodeURIComponent(result);
743
+ } catch (err) {
744
+ }
745
+ return result.replace(/\+/g, ' ')
746
+ }
747
+ };
748
+
749
+ _.getHashParam = function (hash, param) {
750
+ var matches = hash.match(new RegExp(param + '=([^&]*)'));
751
+ return matches ? matches[1] : null
752
+ };
753
+
754
+ _.register_event = (function () {
755
+ // written by Dean Edwards, 2005
756
+ // with input from Tino Zijdel - crisp@xs4all.nl
757
+ // with input from Carl Sverre - mail@carlsverre.com
758
+ // http://dean.edwards.name/weblog/2005/10/add-event/
759
+ // https://gist.github.com/1930440
760
+
761
+ /**
762
+ * @param {Object} element
763
+ * @param {string} type
764
+ * @param {function(...*)} handler
765
+ * @param {boolean=} oldSchool
766
+ * @param {boolean=} useCapture
767
+ */
768
+ var register_event = function (element, type, handler, oldSchool, useCapture) {
769
+ if (!element) {
770
+ return
771
+ }
772
+
773
+ if (element.addEventListener && !oldSchool) {
774
+ element.addEventListener(type, handler, !!useCapture);
775
+ } else {
776
+ var ontype = 'on' + type;
777
+ var old_handler = element[ontype]; // can be undefined
778
+ element[ontype] = makeHandler(element, handler, old_handler);
779
+ }
780
+ };
781
+
782
+ function makeHandler(element, new_handler, old_handlers) {
783
+ var handler = function (event) {
784
+ event = event || fixEvent(window.event);
785
+
786
+ // this basically happens in firefox whenever another script
787
+ // overwrites the onload callback and doesn't pass the event
788
+ // object to previously defined callbacks. All the browsers
789
+ // that don't define window.event implement addEventListener
790
+ // so the dom_loaded handler will still be fired as usual.
791
+ if (!event) {
792
+ return undefined
793
+ }
794
+
795
+ var ret = true;
796
+ var old_result, new_result;
797
+
798
+ if (_.isFunction(old_handlers)) {
799
+ old_result = old_handlers(event);
800
+ }
801
+ new_result = new_handler.call(element, event);
802
+
803
+ if (false === old_result || false === new_result) {
804
+ ret = false;
805
+ }
806
+
807
+ return ret
808
+ };
809
+
810
+ return handler
811
+ }
812
+
813
+ function fixEvent(event) {
814
+ if (event) {
815
+ event.preventDefault = fixEvent.preventDefault;
816
+ event.stopPropagation = fixEvent.stopPropagation;
817
+ }
818
+ return event
819
+ }
820
+ fixEvent.preventDefault = function () {
821
+ this.returnValue = false;
822
+ };
823
+ fixEvent.stopPropagation = function () {
824
+ this.cancelBubble = true;
825
+ };
826
+
827
+ return register_event
828
+ })();
829
+
830
+ _.info = {
831
+ campaignParams: function () {
832
+ var campaign_keywords = 'utm_source utm_medium utm_campaign utm_content utm_term gclid'.split(' '),
833
+ kw = '',
834
+ params = {};
835
+ _.each(campaign_keywords, function (kwkey) {
836
+ kw = _.getQueryParam(document$1.URL, kwkey);
837
+ if (kw.length) {
838
+ params[kwkey] = kw;
839
+ }
840
+ });
841
+
842
+ return params
843
+ },
844
+
845
+ searchEngine: function (referrer) {
846
+ if (referrer.search('https?://(.*)google.([^/?]*)') === 0) {
847
+ return 'google'
848
+ } else if (referrer.search('https?://(.*)bing.com') === 0) {
849
+ return 'bing'
850
+ } else if (referrer.search('https?://(.*)yahoo.com') === 0) {
851
+ return 'yahoo'
852
+ } else if (referrer.search('https?://(.*)duckduckgo.com') === 0) {
853
+ return 'duckduckgo'
854
+ } else {
855
+ return null
856
+ }
857
+ },
858
+
859
+ searchInfo: function (referrer) {
860
+ var search = _.info.searchEngine(referrer),
861
+ param = search != 'yahoo' ? 'q' : 'p',
862
+ ret = {};
863
+
864
+ if (search !== null) {
865
+ ret['$search_engine'] = search;
866
+
867
+ var keyword = _.getQueryParam(referrer, param);
868
+ if (keyword.length) {
869
+ ret['ph_keyword'] = keyword;
870
+ }
871
+ }
872
+
873
+ return ret
874
+ },
875
+
876
+ /**
877
+ * This function detects which browser is running this script.
878
+ * The order of the checks are important since many user agents
879
+ * include key words used in later checks.
880
+ */
881
+ browser: function (user_agent, vendor, opera) {
882
+ vendor = vendor || ''; // vendor is undefined for at least IE9
883
+ if (opera || _.includes(user_agent, ' OPR/')) {
884
+ if (_.includes(user_agent, 'Mini')) {
885
+ return 'Opera Mini'
886
+ }
887
+ return 'Opera'
888
+ } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) {
889
+ return 'BlackBerry'
890
+ } else if (_.includes(user_agent, 'IEMobile') || _.includes(user_agent, 'WPDesktop')) {
891
+ return 'Internet Explorer Mobile'
892
+ } else if (_.includes(user_agent, 'SamsungBrowser/')) {
893
+ // https://developer.samsung.com/internet/user-agent-string-format
894
+ return 'Samsung Internet'
895
+ } else if (_.includes(user_agent, 'Edge') || _.includes(user_agent, 'Edg/')) {
896
+ return 'Microsoft Edge'
897
+ } else if (_.includes(user_agent, 'FBIOS')) {
898
+ return 'Facebook Mobile'
899
+ } else if (_.includes(user_agent, 'Chrome')) {
900
+ return 'Chrome'
901
+ } else if (_.includes(user_agent, 'CriOS')) {
902
+ return 'Chrome iOS'
903
+ } else if (_.includes(user_agent, 'UCWEB') || _.includes(user_agent, 'UCBrowser')) {
904
+ return 'UC Browser'
905
+ } else if (_.includes(user_agent, 'FxiOS')) {
906
+ return 'Firefox iOS'
907
+ } else if (_.includes(vendor, 'Apple')) {
908
+ if (_.includes(user_agent, 'Mobile')) {
909
+ return 'Mobile Safari'
910
+ }
911
+ return 'Safari'
912
+ } else if (_.includes(user_agent, 'Android')) {
913
+ return 'Android Mobile'
914
+ } else if (_.includes(user_agent, 'Konqueror')) {
915
+ return 'Konqueror'
916
+ } else if (_.includes(user_agent, 'Firefox')) {
917
+ return 'Firefox'
918
+ } else if (_.includes(user_agent, 'MSIE') || _.includes(user_agent, 'Trident/')) {
919
+ return 'Internet Explorer'
920
+ } else if (_.includes(user_agent, 'Gecko')) {
921
+ return 'Mozilla'
922
+ } else {
923
+ return ''
924
+ }
925
+ },
926
+
927
+ /**
928
+ * This function detects which browser version is running this script,
929
+ * parsing major and minor version (e.g., 42.1). User agent strings from:
930
+ * http://www.useragentstring.com/pages/useragentstring.php
931
+ */
932
+ browserVersion: function (userAgent, vendor, opera) {
933
+ var browser = _.info.browser(userAgent, vendor, opera);
934
+ var versionRegexs = {
935
+ 'Internet Explorer Mobile': /rv:(\d+(\.\d+)?)/,
936
+ 'Microsoft Edge': /Edge?\/(\d+(\.\d+)?)/,
937
+ Chrome: /Chrome\/(\d+(\.\d+)?)/,
938
+ 'Chrome iOS': /CriOS\/(\d+(\.\d+)?)/,
939
+ 'UC Browser': /(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,
940
+ Safari: /Version\/(\d+(\.\d+)?)/,
941
+ 'Mobile Safari': /Version\/(\d+(\.\d+)?)/,
942
+ Opera: /(Opera|OPR)\/(\d+(\.\d+)?)/,
943
+ Firefox: /Firefox\/(\d+(\.\d+)?)/,
944
+ 'Firefox iOS': /FxiOS\/(\d+(\.\d+)?)/,
945
+ Konqueror: /Konqueror:(\d+(\.\d+)?)/,
946
+ BlackBerry: /BlackBerry (\d+(\.\d+)?)/,
947
+ 'Android Mobile': /android\s(\d+(\.\d+)?)/,
948
+ 'Samsung Internet': /SamsungBrowser\/(\d+(\.\d+)?)/,
949
+ 'Internet Explorer': /(rv:|MSIE )(\d+(\.\d+)?)/,
950
+ Mozilla: /rv:(\d+(\.\d+)?)/,
951
+ };
952
+ var regex = versionRegexs[browser];
953
+ if (regex === undefined) {
954
+ return null
955
+ }
956
+ var matches = userAgent.match(regex);
957
+ if (!matches) {
958
+ return null
959
+ }
960
+ return parseFloat(matches[matches.length - 2])
961
+ },
962
+
963
+ os: function () {
964
+ var a = userAgent;
965
+ if (/Windows/i.test(a)) {
966
+ if (/Phone/.test(a) || /WPDesktop/.test(a)) {
967
+ return 'Windows Phone'
968
+ }
969
+ return 'Windows'
970
+ } else if (/(iPhone|iPad|iPod)/.test(a)) {
971
+ return 'iOS'
972
+ } else if (/Android/.test(a)) {
973
+ return 'Android'
974
+ } else if (/(BlackBerry|PlayBook|BB10)/i.test(a)) {
975
+ return 'BlackBerry'
976
+ } else if (/Mac/i.test(a)) {
977
+ return 'Mac OS X'
978
+ } else if (/Linux/.test(a)) {
979
+ return 'Linux'
980
+ } else if (/CrOS/.test(a)) {
981
+ return 'Chrome OS'
982
+ } else {
983
+ return ''
984
+ }
985
+ },
986
+
987
+ device: function (user_agent) {
988
+ if (/Windows Phone/i.test(user_agent) || /WPDesktop/.test(user_agent)) {
989
+ return 'Windows Phone'
990
+ } else if (/iPad/.test(user_agent)) {
991
+ return 'iPad'
992
+ } else if (/iPod/.test(user_agent)) {
993
+ return 'iPod Touch'
994
+ } else if (/iPhone/.test(user_agent)) {
995
+ return 'iPhone'
996
+ } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) {
997
+ return 'BlackBerry'
998
+ } else if (/Android/.test(user_agent) && !/Mobile/.test(user_agent)) {
999
+ return 'Android Tablet'
1000
+ } else if (/Android/.test(user_agent)) {
1001
+ return 'Android'
1002
+ } else {
1003
+ return ''
1004
+ }
1005
+ },
1006
+
1007
+ deviceType: function (user_agent) {
1008
+ const device = this.device(user_agent);
1009
+ if (device === 'iPad' || device === 'Android Tablet') {
1010
+ return 'Tablet'
1011
+ } else if (device) {
1012
+ return 'Mobile'
1013
+ } else {
1014
+ return 'Desktop'
1015
+ }
1016
+ },
1017
+
1018
+ referringDomain: function (referrer) {
1019
+ var split = referrer.split('/');
1020
+ if (split.length >= 3) {
1021
+ return split[2]
1022
+ }
1023
+ return ''
1024
+ },
1025
+
1026
+ properties: function () {
1027
+ return _.extend(
1028
+ _.strip_empty_properties({
1029
+ $os: _.info.os(),
1030
+ $browser: _.info.browser(userAgent, navigator$1.vendor, window.opera),
1031
+ $device: _.info.device(userAgent),
1032
+ $device_type: _.info.deviceType(userAgent),
1033
+ }),
1034
+ {
1035
+ $current_url: window.location.href,
1036
+ $host: window.location.host,
1037
+ $pathname: window.location.pathname,
1038
+ $browser_version: _.info.browserVersion(userAgent, navigator$1.vendor, window.opera),
1039
+ $screen_height: window.screen.height,
1040
+ $screen_width: window.screen.width,
1041
+ $viewport_height: window.innerHeight,
1042
+ $viewport_width: window.innerWidth,
1043
+ $lib: 'web',
1044
+ $lib_version: Config$1.LIB_VERSION,
1045
+ $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),
1046
+ $time: _.timestamp() / 1000, // epoch time in seconds
1047
+ }
1048
+ )
1049
+ },
1050
+
1051
+ people_properties: function () {
1052
+ return _.extend(
1053
+ _.strip_empty_properties({
1054
+ $os: _.info.os(),
1055
+ $browser: _.info.browser(userAgent, navigator$1.vendor, window.opera),
1056
+ }),
1057
+ {
1058
+ $browser_version: _.info.browserVersion(userAgent, navigator$1.vendor, window.opera),
1059
+ }
1060
+ )
1061
+ },
1062
+ };
1063
+
1064
+ // EXPORTS (for closure compiler)
1065
+ _['isObject'] = _.isObject;
1066
+ _['isBlockedUA'] = _.isBlockedUA;
1067
+ _['isEmptyObject'] = _.isEmptyObject;
1068
+ _['info'] = _.info;
1069
+ _['info']['device'] = _.info.device;
1070
+ _['info']['browser'] = _.info.browser;
1071
+ _['info']['browserVersion'] = _.info.browserVersion;
1072
+ _['info']['properties'] = _.info.properties;
1073
+
1074
+ var DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i;
1075
+
1076
+ // Methods partially borrowed from quirksmode.org/js/cookies.html
1077
+ const cookieStore = {
1078
+ get: function (name) {
1079
+ try {
1080
+ var nameEQ = name + '=';
1081
+ var ca = document.cookie.split(';');
1082
+ for (var i = 0; i < ca.length; i++) {
1083
+ var c = ca[i];
1084
+ while (c.charAt(0) == ' ') {
1085
+ c = c.substring(1, c.length);
1086
+ }
1087
+ if (c.indexOf(nameEQ) === 0) {
1088
+ return decodeURIComponent(c.substring(nameEQ.length, c.length))
1089
+ }
1090
+ }
1091
+ } catch (err) {}
1092
+ return null
1093
+ },
1094
+
1095
+ parse: function (name) {
1096
+ var cookie;
1097
+ try {
1098
+ cookie = JSON.parse(cookieStore.get(name)) || {};
1099
+ } catch (err) {
1100
+ // noop
1101
+ }
1102
+ return cookie
1103
+ },
1104
+
1105
+ set: function (name, value, days, cross_subdomain, is_secure) {
1106
+ try {
1107
+ var cdomain = '',
1108
+ expires = '',
1109
+ secure = '';
1110
+
1111
+ if (cross_subdomain) {
1112
+ var matches = document.location.hostname.match(DOMAIN_MATCH_REGEX),
1113
+ domain = matches ? matches[0] : '';
1114
+
1115
+ cdomain = domain ? '; domain=.' + domain : '';
1116
+ }
1117
+
1118
+ if (days) {
1119
+ var date = new Date();
1120
+ date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
1121
+ expires = '; expires=' + date.toGMTString();
1122
+ }
1123
+
1124
+ if (is_secure) {
1125
+ secure = '; secure';
1126
+ }
1127
+
1128
+ var new_cookie_val =
1129
+ name + '=' + encodeURIComponent(JSON.stringify(value)) + expires + '; path=/' + cdomain + secure;
1130
+ document.cookie = new_cookie_val;
1131
+ return new_cookie_val
1132
+ } catch (err) {
1133
+ return
1134
+ }
1135
+ },
1136
+
1137
+ remove: function (name, cross_subdomain) {
1138
+ try {
1139
+ cookieStore.set(name, '', -1, cross_subdomain);
1140
+ } catch (err) {
1141
+ return
1142
+ }
1143
+ },
1144
+ };
1145
+
1146
+ var _localStorage_supported = null;
1147
+ const localStore = {
1148
+ is_supported: function () {
1149
+ if (_localStorage_supported !== null) {
1150
+ return _localStorage_supported
1151
+ }
1152
+
1153
+ var supported = true;
1154
+ if (window) {
1155
+ try {
1156
+ var key = '__mplssupport__',
1157
+ val = 'xyz';
1158
+ localStore.set(key, val);
1159
+ if (localStore.get(key) !== '"xyz"') {
1160
+ supported = false;
1161
+ }
1162
+ localStore.remove(key);
1163
+ } catch (err) {
1164
+ supported = false;
1165
+ }
1166
+ } else {
1167
+ supported = false;
1168
+ }
1169
+
1170
+ _localStorage_supported = supported;
1171
+ return supported
1172
+ },
1173
+
1174
+ error: function (msg) {
1175
+ },
1176
+
1177
+ get: function (name) {
1178
+ try {
1179
+ return window.localStorage.getItem(name)
1180
+ } catch (err) {
1181
+ localStore.error(err);
1182
+ }
1183
+ return null
1184
+ },
1185
+
1186
+ parse: function (name) {
1187
+ try {
1188
+ return JSON.parse(localStore.get(name)) || {}
1189
+ } catch (err) {
1190
+ // noop
1191
+ }
1192
+ return null
1193
+ },
1194
+
1195
+ set: function (name, value) {
1196
+ try {
1197
+ window.localStorage.setItem(name, JSON.stringify(value));
1198
+ } catch (err) {
1199
+ localStore.error(err);
1200
+ }
1201
+ },
1202
+
1203
+ remove: function (name) {
1204
+ try {
1205
+ window.localStorage.removeItem(name);
1206
+ } catch (err) {
1207
+ localStore.error(err);
1208
+ }
1209
+ },
1210
+ };
1211
+
1212
+ // Use localstorage for most data but still use cookie for distinct_id
1213
+ // This solves issues with cookies having too much data in them causing headers too large
1214
+ // Also makes sure we don't have to send a ton of data to the server
1215
+ const localPlusCookieStore = {
1216
+ ...localStore,
1217
+ parse: function (name) {
1218
+ try {
1219
+ let extend = {};
1220
+ try {
1221
+ // See if there's a cookie stored with data.
1222
+ extend = cookieStore.parse(name) || {};
1223
+ if (extend['distinct_id']) {
1224
+ cookieStore.set(name, { distinct_id: extend['distinct_id'] });
1225
+ }
1226
+ } catch (err) {}
1227
+ const value = _.extend(extend, JSON.parse(localStore.get(name) || '{}'));
1228
+ localStore.set(name, value);
1229
+ return value
1230
+ } catch (err) {
1231
+ // noop
1232
+ }
1233
+ return null
1234
+ },
1235
+
1236
+ set: function (name, value) {
1237
+ try {
1238
+ localStore.set(name, value);
1239
+ if (value.distinct_id) {
1240
+ cookieStore.set(name, { distinct_id: value.distinct_id });
1241
+ }
1242
+ } catch (err) {
1243
+ localStore.error(err);
1244
+ }
1245
+ },
1246
+
1247
+ remove: function (name) {
1248
+ try {
1249
+ window.localStorage.removeItem(name);
1250
+ cookieStore.remove(name);
1251
+ } catch (err) {
1252
+ localStore.error(err);
1253
+ }
1254
+ },
1255
+ };
1256
+
1257
+ const memoryStorage = {};
1258
+
1259
+ // Storage that only lasts the length of the pageview if we don't want to use cookies
1260
+ const memoryStore = {
1261
+ is_supported: function () {
1262
+ return true
1263
+ },
1264
+
1265
+ error: function (msg) {
1266
+ },
1267
+
1268
+ parse: function (name) {
1269
+ return memoryStorage[name] || null
1270
+ },
1271
+
1272
+ set: function (name, value) {
1273
+ memoryStorage[name] = value;
1274
+ },
1275
+
1276
+ remove: function (name) {
1277
+ delete memoryStorage[name];
1278
+ },
1279
+ };
1280
+
1281
+ // Storage that only lasts the length of a tab/window. Survives page refreshes
1282
+ const sessionStore = {
1283
+ sessionStorageSupported: null,
1284
+ is_supported: function () {
1285
+ if (sessionStore.sessionStorageSupported !== null) {
1286
+ return sessionStore.sessionStorageSupported
1287
+ }
1288
+ sessionStore.sessionStorageSupported = true;
1289
+ if (window) {
1290
+ try {
1291
+ let key = '__support__',
1292
+ val = 'xyz';
1293
+ sessionStore.set(key, val);
1294
+ if (sessionStore.get(key) !== '"xyz"') {
1295
+ sessionStore.sessionStorageSupported = false;
1296
+ }
1297
+ sessionStore.remove(key);
1298
+ } catch (err) {
1299
+ sessionStore.sessionStorageSupported = false;
1300
+ }
1301
+ } else {
1302
+ sessionStore.sessionStorageSupported = false;
1303
+ }
1304
+ return sessionStore.sessionStorageSupported
1305
+ },
1306
+ error: function (msg) {
1307
+ if (Config.DEBUG) ;
1308
+ },
1309
+
1310
+ get: function (name) {
1311
+ try {
1312
+ return window.sessionStorage.getItem(name)
1313
+ } catch (err) {
1314
+ sessionStore.error(err);
1315
+ }
1316
+ return null
1317
+ },
1318
+
1319
+ parse: function (name) {
1320
+ try {
1321
+ return JSON.parse(sessionStore.get(name)) || null
1322
+ } catch (err) {
1323
+ // noop
1324
+ }
1325
+ return null
1326
+ },
1327
+
1328
+ set: function (name, value) {
1329
+ try {
1330
+ window.sessionStorage.setItem(name, JSON.stringify(value));
1331
+ } catch (err) {
1332
+ sessionStore.error(err);
1333
+ }
1334
+ },
1335
+
1336
+ remove: function (name) {
1337
+ try {
1338
+ window.sessionStorage.removeItem(name);
1339
+ } catch (err) {
1340
+ sessionStore.error(err);
1341
+ }
1342
+ },
1343
+ };
1344
+
1345
+ /* eslint camelcase: "off" */
1346
+
1347
+ /*
1348
+ * Constants
1349
+ */
1350
+ /** @const */ var SET_QUEUE_KEY = '__mps';
1351
+ /** @const */ var SET_ONCE_QUEUE_KEY = '__mpso';
1352
+ /** @const */ var UNSET_QUEUE_KEY = '__mpus';
1353
+ /** @const */ var ADD_QUEUE_KEY = '__mpa';
1354
+ /** @const */ var APPEND_QUEUE_KEY = '__mpap';
1355
+ /** @const */ var REMOVE_QUEUE_KEY = '__mpr';
1356
+ /** @const */ var UNION_QUEUE_KEY = '__mpu';
1357
+ /** @const */ var CAMPAIGN_IDS_KEY = '__cmpns';
1358
+ /** @const */ var EVENT_TIMERS_KEY = '__timers';
1359
+ /** @const */ var SESSION_RECORDING_ENABLED = '$session_recording_enabled';
1360
+ /** @const */ var SESSION_ID = '$sesid';
1361
+ /** @const */ var ENABLED_FEATURE_FLAGS = '$enabled_feature_flags';
1362
+ /** @const */ var RESERVED_PROPERTIES = [
1363
+ SET_QUEUE_KEY,
1364
+ SET_ONCE_QUEUE_KEY,
1365
+ UNSET_QUEUE_KEY,
1366
+ ADD_QUEUE_KEY,
1367
+ APPEND_QUEUE_KEY,
1368
+ REMOVE_QUEUE_KEY,
1369
+ UNION_QUEUE_KEY,
1370
+ CAMPAIGN_IDS_KEY,
1371
+ EVENT_TIMERS_KEY,
1372
+ SESSION_RECORDING_ENABLED,
1373
+ SESSION_ID,
1374
+ ENABLED_FEATURE_FLAGS,
1375
+ ];
1376
+
1377
+ /**
1378
+ * UserMaven Persistence Object
1379
+ * @constructor
1380
+ */
1381
+ var UserMavenPersistence = function (config) {
1382
+ // clean chars that aren't accepted by the http spec for cookie values
1383
+ // https://datatracker.ietf.org/doc/html/rfc2616#section-2.2
1384
+ let token = '';
1385
+
1386
+ if (config['token']) {
1387
+ token = config['token'].replace(/\+/g, 'PL').replace(/\//g, 'SL').replace(/=/g, 'EQ');
1388
+ }
1389
+
1390
+ this['props'] = {};
1391
+ this.campaign_params_saved = false;
1392
+
1393
+ if (config['persistence_name']) {
1394
+ this.name = 'um_' + config['persistence_name'];
1395
+ } else {
1396
+ this.name = 'um_' + token + '_usermaven';
1397
+ }
1398
+
1399
+ var storage_type = config['persistence'];
1400
+ if (storage_type !== 'cookie' && storage_type.indexOf('localStorage') === -1 && storage_type !== 'memory') {
1401
+ console$1.critical('Unknown persistence type ' + storage_type + '; falling back to cookie');
1402
+ storage_type = config['persistence'] = 'cookie';
1403
+ }
1404
+ if (storage_type === 'localStorage' && localStore.is_supported()) {
1405
+ this.storage = localStore;
1406
+ } else if (storage_type === 'localStorage+cookie' && localPlusCookieStore.is_supported()) {
1407
+ this.storage = localPlusCookieStore;
1408
+ } else if (storage_type === 'memory') {
1409
+ this.storage = memoryStore;
1410
+ } else {
1411
+ this.storage = cookieStore;
1412
+ }
1413
+
1414
+ this.load();
1415
+ this.update_config(config);
1416
+ this.save();
1417
+ };
1418
+
1419
+ UserMavenPersistence.prototype.properties = function () {
1420
+ var p = {};
1421
+ // Filter out reserved properties
1422
+ _.each(this['props'], function (v, k) {
1423
+ if (k === ENABLED_FEATURE_FLAGS && typeof v === 'object') {
1424
+ var keys = Object.keys(v);
1425
+ for (var i = 0; i < keys.length; i++) {
1426
+ p[`$feature/${keys[i]}`] = v[keys[i]];
1427
+ }
1428
+ } else if (!_.include(RESERVED_PROPERTIES, k)) {
1429
+ p[k] = v;
1430
+ }
1431
+ });
1432
+ return p
1433
+ };
1434
+
1435
+ UserMavenPersistence.prototype.load = function () {
1436
+ if (this.disabled) {
1437
+ return
1438
+ }
1439
+
1440
+ var entry = this.storage.parse(this.name);
1441
+
1442
+ if (entry) {
1443
+ this['props'] = _.extend({}, entry);
1444
+ }
1445
+ };
1446
+
1447
+ UserMavenPersistence.prototype.save = function () {
1448
+ if (this.disabled) {
1449
+ return
1450
+ }
1451
+ this.storage.set(this.name, this['props'], this.expire_days, this.cross_subdomain, this.secure);
1452
+ };
1453
+
1454
+ UserMavenPersistence.prototype.remove = function () {
1455
+ // remove both domain and subdomain cookies
1456
+ this.storage.remove(this.name, false);
1457
+ this.storage.remove(this.name, true);
1458
+ };
1459
+
1460
+ // removes the storage entry and deletes all loaded data
1461
+ // forced name for tests
1462
+ UserMavenPersistence.prototype.clear = function () {
1463
+ this.remove();
1464
+ this['props'] = {};
1465
+ };
1466
+
1467
+ /**
1468
+ * @param {Object} props
1469
+ * @param {*=} default_value
1470
+ * @param {number=} days
1471
+ */
1472
+ UserMavenPersistence.prototype.register_once = function (props, default_value, days) {
1473
+ if (_.isObject(props)) {
1474
+ if (typeof default_value === 'undefined') {
1475
+ default_value = 'None';
1476
+ }
1477
+ this.expire_days = typeof days === 'undefined' ? this.default_expiry : days;
1478
+
1479
+ _.each(
1480
+ props,
1481
+ function (val, prop) {
1482
+ if (!this['props'].hasOwnProperty(prop) || this['props'][prop] === default_value) {
1483
+ this['props'][prop] = val;
1484
+ }
1485
+ },
1486
+ this
1487
+ );
1488
+
1489
+ this.save();
1490
+
1491
+ return true
1492
+ }
1493
+ return false
1494
+ };
1495
+
1496
+ /**
1497
+ * @param {Object} props
1498
+ * @param {number=} days
1499
+ */
1500
+ UserMavenPersistence.prototype.register = function (props, days) {
1501
+ if (_.isObject(props)) {
1502
+ this.expire_days = typeof days === 'undefined' ? this.default_expiry : days;
1503
+
1504
+ _.extend(this['props'], props);
1505
+
1506
+ this.save();
1507
+
1508
+ return true
1509
+ }
1510
+ return false
1511
+ };
1512
+
1513
+ UserMavenPersistence.prototype.unregister = function (prop) {
1514
+ if (prop in this['props']) {
1515
+ delete this['props'][prop];
1516
+ this.save();
1517
+ }
1518
+ };
1519
+
1520
+ UserMavenPersistence.prototype.update_campaign_params = function () {
1521
+ if (!this.campaign_params_saved) {
1522
+ this.register(_.info.campaignParams());
1523
+ this.campaign_params_saved = true;
1524
+ }
1525
+ };
1526
+
1527
+ UserMavenPersistence.prototype.update_search_keyword = function (referrer) {
1528
+ this.register(_.info.searchInfo(referrer));
1529
+ };
1530
+
1531
+ // EXPORTED METHOD, we test this directly.
1532
+ UserMavenPersistence.prototype.update_referrer_info = function (referrer) {
1533
+ // If referrer doesn't exist, we want to note the fact that it was type-in traffic.
1534
+ // Register once, so first touch
1535
+ this.register_once(
1536
+ {
1537
+ $initial_referrer: referrer || '$direct',
1538
+ $initial_referring_domain: _.info.referringDomain(referrer) || '$direct',
1539
+ },
1540
+ ''
1541
+ );
1542
+ // Register the current referrer but override if it's different, hence register
1543
+ this.register({
1544
+ $referrer: referrer || this['props']['$referrer'] || '$direct',
1545
+ $referring_domain: _.info.referringDomain(referrer) || this['props']['$referring_domain'] || '$direct',
1546
+ });
1547
+ };
1548
+
1549
+ UserMavenPersistence.prototype.get_referrer_info = function () {
1550
+ return _.strip_empty_properties({
1551
+ $initial_referrer: this['props']['$initial_referrer'],
1552
+ $initial_referring_domain: this['props']['$initial_referring_domain'],
1553
+ })
1554
+ };
1555
+
1556
+ // safely fills the passed in object with stored properties,
1557
+ // does not override any properties defined in both
1558
+ // returns the passed in object
1559
+ UserMavenPersistence.prototype.safe_merge = function (props) {
1560
+ _.each(this['props'], function (val, prop) {
1561
+ if (!(prop in props)) {
1562
+ props[prop] = val;
1563
+ }
1564
+ });
1565
+
1566
+ return props
1567
+ };
1568
+
1569
+ UserMavenPersistence.prototype.update_config = function (config) {
1570
+ this.default_expiry = this.expire_days = config['cookie_expiration'];
1571
+ this.set_disabled(config['disable_persistence']);
1572
+ this.set_cross_subdomain(config['cross_subdomain_cookie']);
1573
+ this.set_secure(config['secure_cookie']);
1574
+ };
1575
+
1576
+ UserMavenPersistence.prototype.set_disabled = function (disabled) {
1577
+ this.disabled = disabled;
1578
+ if (this.disabled) {
1579
+ this.remove();
1580
+ } else {
1581
+ this.save();
1582
+ }
1583
+ };
1584
+
1585
+ UserMavenPersistence.prototype.set_cross_subdomain = function (cross_subdomain) {
1586
+ if (cross_subdomain !== this.cross_subdomain) {
1587
+ this.cross_subdomain = cross_subdomain;
1588
+ this.remove();
1589
+ this.save();
1590
+ }
1591
+ };
1592
+
1593
+ UserMavenPersistence.prototype.get_cross_subdomain = function () {
1594
+ return this.cross_subdomain
1595
+ };
1596
+
1597
+ UserMavenPersistence.prototype.set_secure = function (secure) {
1598
+ if (secure !== this.secure) {
1599
+ this.secure = secure ? true : false;
1600
+ this.remove();
1601
+ this.save();
1602
+ }
1603
+ };
1604
+
1605
+ UserMavenPersistence.prototype.set_event_timer = function (event_name, timestamp) {
1606
+ var timers = this['props'][EVENT_TIMERS_KEY] || {};
1607
+ timers[event_name] = timestamp;
1608
+ this['props'][EVENT_TIMERS_KEY] = timers;
1609
+ this.save();
1610
+ };
1611
+
1612
+ UserMavenPersistence.prototype.remove_event_timer = function (event_name) {
1613
+ var timers = this['props'][EVENT_TIMERS_KEY] || {};
1614
+ var timestamp = timers[event_name];
1615
+ if (!_.isUndefined(timestamp)) {
1616
+ delete this['props'][EVENT_TIMERS_KEY][event_name];
1617
+ this.save();
1618
+ }
1619
+ return timestamp
1620
+ };
1621
+
1622
+ // import { INCREMENTAL_SNAPSHOT_EVENT_TYPE, MUTATION_SOURCE_TYPE } from './extensions/sessionrecording'
1623
+
1624
+ const SESSION_CHANGE_THRESHOLD = 30 * 60 * 1000; // 30 mins
1625
+ /* const SESSION_CHANGE_THRESHOLD = 1 * 60 * 1000 // 1 min */
1626
+
1627
+ class SessionIdManager {
1628
+ constructor(config, persistence) {
1629
+ this.persistence = persistence;
1630
+
1631
+ if (config['persistence_name']) {
1632
+ this.window_id_storage_key = 'um_' + config['persistence_name'] + '_window_id';
1633
+ } else {
1634
+ this.window_id_storage_key = 'um_' + config['token'] + '_window_id';
1635
+ }
1636
+ }
1637
+
1638
+ // Note: this tries to store the windowId in sessionStorage. SessionStorage is unique to the current window/tab,
1639
+ // and persists page loads/reloads. So it's uniquely suited for storing the windowId. This function also respects
1640
+ // when persistence is disabled (by user config) and when sessionStorage is not supported (it *should* be supported on all browsers),
1641
+ // and in that case, it falls back to memory (which sadly, won't persist page loads)
1642
+ _setWindowId(windowId) {
1643
+ if (windowId !== this.windowId) {
1644
+ this.windowId = windowId;
1645
+ if (!this.persistence.disabled && sessionStore.is_supported()) {
1646
+ sessionStore.set(this.window_id_storage_key, windowId);
1647
+ }
1648
+ }
1649
+ }
1650
+
1651
+ _getWindowId() {
1652
+ if (this.windowId) {
1653
+ return this.windowId
1654
+ }
1655
+ if (!this.persistence.disabled && sessionStore.is_supported()) {
1656
+ return sessionStore.parse(this.window_id_storage_key)
1657
+ }
1658
+ return null
1659
+ }
1660
+
1661
+ // Note: 'this.persistence.register' can be disabled in the config.
1662
+ // In that case, this works by storing sessionId and the timestamp in memory.
1663
+ _setSessionId(sessionId, timestamp) {
1664
+ if (sessionId !== this.sessionId || timestamp !== this.timestamp) {
1665
+ this.timestamp = timestamp;
1666
+ this.sessionId = sessionId;
1667
+ this.persistence.register({ [SESSION_ID]: [timestamp, sessionId] });
1668
+ }
1669
+ }
1670
+
1671
+ _getSessionId() {
1672
+ if (this.sessionId && this.timestamp) {
1673
+ return [this.timestamp, this.sessionId]
1674
+ }
1675
+ return this.persistence['props'][SESSION_ID] || [0, null]
1676
+ }
1677
+
1678
+ // Resets the session id by setting it to null. On the subsequent call to getSessionAndWindowId,
1679
+ // new ids will be generated.
1680
+ resetSessionId() {
1681
+ this._setSessionId(null, null);
1682
+ }
1683
+
1684
+ getSessionAndWindowId(timestamp = null, recordingEvent = false) {
1685
+ // Some recording events are triggered by non-user events (e.g. "X minutes ago" text updating on the screen).
1686
+ // We don't want to update the session and window ids in these cases. These events are designated by event
1687
+ // type -> incremental update, and source -> mutation.
1688
+ /* const isUserInteraction = !(
1689
+ recordingEvent &&
1690
+ recordingEvent.type === INCREMENTAL_SNAPSHOT_EVENT_TYPE &&
1691
+ recordingEvent.data?.source === MUTATION_SOURCE_TYPE
1692
+ ) */
1693
+
1694
+ const isUserInteraction = true;
1695
+
1696
+ timestamp = timestamp || new Date().getTime();
1697
+
1698
+ let [lastTimestamp, sessionId] = this._getSessionId();
1699
+ let windowId = this._getWindowId();
1700
+
1701
+ if (!sessionId || (Math.abs(timestamp - lastTimestamp) > SESSION_CHANGE_THRESHOLD)) {
1702
+ sessionId = _.UUID();
1703
+ windowId = _.UUID();
1704
+ } else if (!windowId) {
1705
+ windowId = _.UUID();
1706
+ }
1707
+
1708
+ const newTimestamp = lastTimestamp === 0 || isUserInteraction ? timestamp : lastTimestamp;
1709
+
1710
+ this._setWindowId(windowId);
1711
+ this._setSessionId(sessionId, newTimestamp);
1712
+
1713
+ return {
1714
+ sessionId: sessionId,
1715
+ windowId: windowId,
1716
+ }
1717
+ }
1718
+ }
1719
+
224
1720
  var VERSION_INFO = {
225
1721
  env: 'production',
226
- date: '2022-01-09T16:15:00.168Z',
227
- version: '1.0.0'
1722
+ date: '2022-02-18T12:44:44.465Z',
1723
+ version: '1.0.4'
228
1724
  };
229
1725
  var USERMAVEN_VERSION = "".concat(VERSION_INFO.version, "/").concat(VERSION_INFO.env, "@").concat(VERSION_INFO.date);
230
1726
  var beaconTransport = function (url, json) {
@@ -401,7 +1897,17 @@ var UsermavenClientImpl = /** @class */ (function () {
401
1897
  };
402
1898
  UsermavenClientImpl.prototype.getCtx = function () {
403
1899
  var now = new Date();
404
- return __assign({ event_id: '', user: __assign({ anonymous_id: this.anonymousId }, this.userProperties), ids: this._getIds(), user_agent: navigator.userAgent, utc_time: reformatDate(now.toISOString()), local_tz_offset: now.getTimezoneOffset(), referer: document.referrer, url: window.location.href, page_title: document.title, doc_path: document.location.pathname, doc_host: document.location.hostname, doc_search: window.location.search, screen_resolution: screen.width + 'x' + screen.height, vp_size: Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) + 'x' + Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0), user_language: navigator.language, doc_encoding: document.characterSet }, getDataFromParams(parseQuery()));
1900
+ var _a = this.sessionManager.getSessionAndWindowId(), sessionId = _a.sessionId, windowId = _a.windowId;
1901
+ // extract company details from identity payload
1902
+ var user = __assign({ anonymous_id: this.anonymousId }, this.userProperties);
1903
+ var company = user['company'] || {};
1904
+ delete user['company'];
1905
+ var payload = __assign({ event_id: '', session_id: sessionId, window_id: windowId, user: user, ids: this._getIds(), user_agent: navigator.userAgent, utc_time: reformatDate(now.toISOString()), local_tz_offset: now.getTimezoneOffset(), referer: document.referrer, url: window.location.href, page_title: document.title, doc_path: document.location.pathname, doc_host: document.location.hostname, doc_search: window.location.search, screen_resolution: screen.width + 'x' + screen.height, vp_size: Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) + 'x' + Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0), user_language: navigator.language, doc_encoding: document.characterSet }, getDataFromParams(parseQuery()));
1906
+ // id and name attributes will be checked on backend
1907
+ if (Object.keys(company).length) {
1908
+ payload['company'] = company;
1909
+ }
1910
+ return payload;
405
1911
  };
406
1912
  UsermavenClientImpl.prototype._getIds = function () {
407
1913
  var cookies = getCookies(false);
@@ -421,7 +1927,7 @@ var UsermavenClientImpl = /** @class */ (function () {
421
1927
  getLogger().debug('track event of type', type, data);
422
1928
  var e = this.makeEvent(type, this.compatMode ?
423
1929
  'eventn' :
424
- 'jitsu', payload || {});
1930
+ 'usermaven', payload || {});
425
1931
  return this.sendJson(e);
426
1932
  };
427
1933
  UsermavenClientImpl.prototype.init = function (options) {
@@ -482,6 +1988,7 @@ var UsermavenClientImpl = /** @class */ (function () {
482
1988
  }
483
1989
  getLogger().debug('Restored persistent properties', this.permanentProperties);
484
1990
  }
1991
+ this.manageSession(options);
485
1992
  if (options.capture_3rd_party_cookies === false) {
486
1993
  this._3pCookies = {};
487
1994
  }
@@ -574,6 +2081,29 @@ var UsermavenClientImpl = /** @class */ (function () {
574
2081
  if (this.propsPersistance && persist) {
575
2082
  this.propsPersistance.save(this.permanentProperties);
576
2083
  }
2084
+ if (this.sessionManager) {
2085
+ this.sessionManager.resetSessionId();
2086
+ }
2087
+ };
2088
+ /**
2089
+ * Manage session capability
2090
+ * @param options
2091
+ */
2092
+ UsermavenClientImpl.prototype.manageSession = function (options) {
2093
+ getLogger().debug('Options', options);
2094
+ var defaultConfig = {
2095
+ persistence: options ? options.persistence || 'cookie' : 'cookie',
2096
+ persistence_name: options ? options.persistence_name || 'session' : 'session',
2097
+ };
2098
+ // TODO: Default session name would be session_
2099
+ this.config = _.extend(defaultConfig, this.config || {}, {
2100
+ token: this.apiKey,
2101
+ });
2102
+ getLogger().debug('Default Configuration', this.config);
2103
+ this.persistence = new UserMavenPersistence(this.config);
2104
+ getLogger().debug('Persistence Configuration', this.persistence);
2105
+ this.sessionManager = new SessionIdManager(this.config, this.persistence);
2106
+ getLogger().debug('Session Configuration', this.sessionManager);
577
2107
  };
578
2108
  return UsermavenClientImpl;
579
2109
  }());