-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
2129 lines (1884 loc) · 66.2 KB
/
index.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
const ReactNative = require('react-native')
const ReactNativeDeviceInfo = require('react-native-device-info')
var Config = {
DEBUG: true,
LIB_VERSION: '0.0.1'
};
const HEIGHT = ReactNative.Dimensions.get('window').height;
const WIDTH = ReactNative.Dimensions.get('window').width;
var document = {
addEventListener(_, callback) {
requestAnimationFrame(callback);
},
readyState: 'complete',
referrer: '',
};
var window = {};
/*
* Saved references to long variable names, so that closure compiler can
* minimize file size.
*/
var ArrayProto = Array.prototype;
var FuncProto = Function.prototype;
var ObjProto = Object.prototype;
var slice = ArrayProto.slice;
var toString = ObjProto.toString;
var hasOwnProperty = ObjProto.hasOwnProperty;
var document$1 = document;
var nativeBind = FuncProto.bind;
var nativeForEach = ArrayProto.forEach;
var nativeIndexOf = ArrayProto.indexOf;
var nativeIsArray = Array.isArray;
var breaker = {};
var _ = {};
// Console override
var console$1 = {
/** @type {function(...[*])} */
log(...args) {
if (Config.DEBUG) {
console.log(...args);
}
},
/** @type {function(...[*])} */
error(...args) {
if (Config.DEBUG) {
console.error('Mixpanel error:', ...args);
}
},
/** @type {function(...[*])} */
critical(...args) {
console.error(...args);
}
};
// UNDERSCORE
// Embed part of the Underscore Library
_.bind = function(func, context) {
var args, bound;
if (nativeBind && func.bind === nativeBind) {
return nativeBind.apply(func, slice.call(arguments, 1));
}
if (typeof func !== 'function') {
throw new TypeError();
}
args = slice.call(arguments, 2);
bound = function() {
if (!(this instanceof bound)) {
return func.apply(context, args.concat(slice.call(arguments)));
}
var ctor = {};
ctor.prototype = func.prototype;
var self = new ctor();
ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return self;
};
return bound;
};
/**
* @param {*=} obj
* @param {function(...[*])=} iterator
* @param {Object=} context
*/
_.each = function(obj, iterator, context) {
if (obj === null || obj === undefined) {
return;
}
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) {
return;
}
}
} else {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) {
return;
}
}
}
}
};
_.escapeHTML = function(s) {
var escaped = s;
if (escaped && _.isString(escaped)) {
escaped = escaped
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
return escaped;
};
_.extend = function(obj) {
_.each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (source[prop] !== void 0) {
obj[prop] = source[prop];
}
}
});
return obj;
};
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
_.isArguments = function(obj) {
return !!(obj && hasOwnProperty.call(obj, 'callee'));
};
_.identity = function(value) {
return value;
};
_.include = function(obj, target) {
var found = false;
if (obj === null) {
return found;
}
if (nativeIndexOf && obj.indexOf === nativeIndexOf) {
return obj.indexOf(target) != -1;
}
_.each(obj, function(value) {
if (found || (found = (value === target))) {
return breaker;
}
});
return found;
};
_.isObject = function(obj) {
return (obj === Object(obj) && !_.isArray(obj));
};
_.isEmptyObject = function(obj) {
if (_.isObject(obj)) {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
return false;
};
_.isUndefined = function(obj) {
return obj === void 0;
};
_.isString = function(obj) {
return toString.call(obj) === '[object String]';
};
_.isDate = function(obj) {
return toString.call(obj) === '[object Date]';
};
_.isNumber = function(obj) {
return toString.call(obj) === '[object Number]';
};
_.encodeDates = function(obj) {
_.each(obj, function(v, k) {
if (_.isDate(v)) {
obj[k] = _.formatDate(v);
} else if (_.isObject(v)) {
obj[k] = _.encodeDates(v); // recurse
}
});
return obj;
};
_.formatDate = function(d) {
// YYYY-MM-DDTHH:MM:SS in UTC
function pad(n) {
return n < 10 ? '0' + n : n;
}
return d.getUTCFullYear() + '-' +
pad(d.getUTCMonth() + 1) + '-' +
pad(d.getUTCDate()) + 'T' +
pad(d.getUTCHours()) + ':' +
pad(d.getUTCMinutes()) + ':' +
pad(d.getUTCSeconds());
};
_.safewrap = function(f) {
return function() {
try {
return f.apply(this, arguments);
} catch (e) {
console$1.critical('Implementation error. Please contact [email protected].');
}
};
};
_.safewrap_class = function(klass, functions) {
for (var i = 0; i < functions.length; i++) {
klass.prototype[functions[i]] = _.safewrap(klass.prototype[functions[i]]);
}
};
_.strip_empty_properties = function(p) {
var ret = {};
_.each(p, function(v, k) {
if (_.isString(v) && v.length > 0) {
ret[k] = v;
}
});
return ret;
};
/*
* this function returns a copy of object after truncating it. If
* passed an Array or Object it will iterate through obj and
* truncate all the values recursively.
*/
_.truncate = function(obj, length) {
var ret;
if (typeof(obj) === 'string') {
ret = obj.slice(0, length);
} else if (_.isArray(obj)) {
ret = [];
_.each(obj, function(val) {
ret.push(_.truncate(val, length));
});
} else if (_.isObject(obj)) {
ret = {};
_.each(obj, function(val, key) {
ret[key] = _.truncate(val, length);
});
} else {
ret = obj;
}
return ret;
};
_.JSONEncode = function(object) {
try {
return JSON.stringify(object);
}
catch (err) {
console$1.error(err);
}
return ''
};
_.JSONDecode = function(string) {
try {
return JSON.parse(string);
}
catch (err) {
console$1.error(err)
}
return null
};
_.base64Encode = function(data) {
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = '',
tmp_arr = [];
if (!data) {
return data;
}
data = _.utf8Encode(data);
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
switch (data.length % 3) {
case 1:
enc = enc.slice(0, -2) + '==';
break;
case 2:
enc = enc.slice(0, -1) + '=';
break;
}
return enc;
};
_.utf8Encode = function(string) {
string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
var utftext = '',
start,
end;
var stringl = 0,
n;
start = end = 0;
stringl = string.length;
for (n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;
if (c1 < 128) {
end++;
} else if ((c1 > 127) && (c1 < 2048)) {
enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128);
} else {
enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
}
if (enc !== null) {
if (end > start) {
utftext += string.substring(start, end);
}
utftext += enc;
start = end = n + 1;
}
}
if (end > start) {
utftext += string.substring(start, string.length);
}
return utftext;
};
// https://stackoverflow.com/a/8809472/1360105
_.UUID = function() {
var d = Date.now();
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
};
/**
* @param {Object=} formdata
* @param {string=} arg_separator
*/
_.HTTPBuildQuery = function(formdata, arg_separator) {
var use_val, use_key, tmp_arr = [];
if (_.isUndefined(arg_separator)) {
arg_separator = '&';
}
_.each(formdata, function(val, key) {
use_val = encodeURIComponent(val.toString());
use_key = encodeURIComponent(key);
tmp_arr[tmp_arr.length] = use_key + '=' + use_val;
});
return tmp_arr.join(arg_separator);
};
_.getQueryParam = function(url, param) {
// Expects a raw URL
param = param.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
var regexS = '[\\?&]' + param + '=([^&#]*)',
regex = new RegExp(regexS),
results = regex.exec(url);
if (results === null || (results && typeof(results[1]) !== 'string' && results[1].length)) {
return '';
} else {
return decodeURIComponent(results[1]).replace(/\+/g, ' ');
}
};
// _.localStorage
_.localStorage = {
error(err) {
console$1.error('localStorage error: %o', err);
},
get(key) {
return ReactNative.AsyncStorage.getItem(key)
.catch(_.localStorage.error);
},
parse(key) {
return _.localStorage.get(key)
.then(value => _.JSONDecode(value) || {})
.catch(_.localStorage.error);
},
set(key, value) {
return ReactNative.AsyncStorage.setItem(key, value)
.catch(_.localStorage.error);
},
remove(key) {
return ReactNative.AsyncStorage.removeItem(key)
.catch(_.localStorage.error);
}
};
_.info = {
campaignParams: function() {
var campaign_keywords = 'utm_source utm_medium utm_campaign utm_content utm_term'.split(' '),
kw = '',
params = {};
_.each(campaign_keywords, function(kwkey) {
kw = _.getQueryParam(document$1.URL, kwkey);
if (kw.length) {
params[kwkey] = kw;
}
});
return params;
},
searchEngine: function(referrer) {
if (referrer.search('https?://(.*)google.([^/?]*)') === 0) {
return 'google';
} else if (referrer.search('https?://(.*)bing.com') === 0) {
return 'bing';
} else if (referrer.search('https?://(.*)yahoo.com') === 0) {
return 'yahoo';
} else if (referrer.search('https?://(.*)duckduckgo.com') === 0) {
return 'duckduckgo';
} else {
return null;
}
},
searchInfo: function(referrer) {
var search = _.info.searchEngine(referrer),
param = (search != 'yahoo') ? 'q' : 'p',
ret = {};
if (search !== null) {
ret['$search_engine'] = search;
var keyword = _.getQueryParam(referrer, param);
if (keyword.length) {
ret['mp_keyword'] = keyword;
}
}
return ret;
},
os: function() {
if (ReactNative.Platform.OS === 'ios') {
return 'iOS';
}
if (ReactNative.Platform.OS === 'android') {
return 'Android';
}
return '';
},
device: function() {
return ReactNativeDeviceInfo.getModel()
},
referringDomain: function(referrer) {
var split = referrer.split('/');
if (split.length >= 3) {
return split[2];
}
return '';
},
properties: function() {
return _.extend(_.strip_empty_properties({
'$os': _.info.os(),
'$referrer': document$1.referrer,
'$referring_domain': _.info.referringDomain(document$1.referrer),
'$device': _.info.device()
}), {
'$screen_height': HEIGHT,
'$screen_width': WIDTH,
'mp_lib': 'react-native',
'$lib_version': Config.LIB_VERSION
});
},
people_properties: function() {
return _.extend(_.strip_empty_properties({
'$os': _.info.os(),
}));
},
pageviewInfo: function() {
return _.strip_empty_properties({
'mp_referrer': document$1.referrer,
'mp_platform': _.info.os()
});
}
};
// EXPORTS (for closure compiler)
_['isObject'] = _.isObject;
_['JSONEncode'] = _.JSONEncode;
_['JSONDecode'] = _.JSONDecode;
_['isEmptyObject'] = _.isEmptyObject;
_['info'] = _.info;
_['info']['device'] = _.info.device;
_['info']['properties'] = _.info.properties;
/*
* Mixpanel JS Library
*
* Copyright 2012, Mixpanel, Inc. All Rights Reserved
* http://mixpanel.com/
*
* Includes portions of Underscore.js
* http://documentcloud.github.com/underscore/
* (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
* Released under the MIT License.
*/
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name mixpanel-2.8.min.js
// ==/ClosureCompiler==
/*
SIMPLE STYLE GUIDE:
this.x === public function
this._x === internal - only use within this file
this.__x === private - only use within the class
Globals should be all caps
*/
var init_type; // MODULE or SNIPPET loader
var mixpanel_master; // main mixpanel instance / object
var INIT_MODULE = 0;
var INIT_SNIPPET = 1;
/*
* Constants
*/
/** @const */ var PRIMARY_INSTANCE_NAME = 'mixpanel';
/** @const */ var SET_QUEUE_KEY = '__mps';
/** @const */ var SET_ONCE_QUEUE_KEY = '__mpso';
/** @const */ var ADD_QUEUE_KEY = '__mpa';
/** @const */ var APPEND_QUEUE_KEY = '__mpap';
/** @const */ var UNION_QUEUE_KEY = '__mpu';
/** @const */ var SET_ACTION = '$set';
/** @const */ var SET_ONCE_ACTION = '$set_once';
/** @const */ var ADD_ACTION = '$add';
/** @const */ var APPEND_ACTION = '$append';
/** @const */ var UNION_ACTION = '$union';
// This key is deprecated, but we want to check for it to see whether aliasing is allowed.
/** @const */ var PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id';
/** @const */ var ALIAS_ID_KEY = '__alias';
/** @const */ var CAMPAIGN_IDS_KEY = '__cmpns';
/** @const */ var EVENT_TIMERS_KEY = '__timers';
/** @const */ var RESERVED_PROPERTIES = [
SET_QUEUE_KEY,
SET_ONCE_QUEUE_KEY,
ADD_QUEUE_KEY,
APPEND_QUEUE_KEY,
UNION_QUEUE_KEY,
PEOPLE_DISTINCT_ID_KEY,
ALIAS_ID_KEY,
CAMPAIGN_IDS_KEY,
EVENT_TIMERS_KEY
];
/*
* Module-level globals
*/
var DEFAULT_CONFIG = {
'api_host': 'https://api.mixpanel.com',
'app_host': 'https://mixpanel.com',
'cdn': 'https://cdn.mxpnl.com',
'persistence_name': '',
'loaded': function() {},
'store_google': true,
'save_referrer': true,
'test': false,
'verbose': false,
'track_pageview': true,
'debug': false,
'disable_persistence': false,
'ip': true,
'property_blacklist': []
};
DEFAULT_CONFIG['decide_host'] = DEFAULT_CONFIG['api_host'];
/**
* Mixpanel Persistence Object
* @constructor
*/
var MixpanelPersistence = function(config) {
this['props'] = {};
this.campaign_params_saved = false;
if (config['persistence_name']) {
this.name = 'mp_' + config['persistence_name'];
} else {
this.name = 'mp_' + config['token'] + '_mixpanel';
}
this.storage = _.localStorage;
this.load()
.then(() => {
this.update_config(config);
this.save();
});
};
MixpanelPersistence.prototype.properties = function() {
var p = {};
// Filter out reserved properties
_.each(this['props'], function(v, k) {
if (!_.include(RESERVED_PROPERTIES, k)) {
p[k] = v;
}
});
return p;
};
MixpanelPersistence.prototype.load = function() {
if (this.disabled) { return; }
return this.storage.parse(this.name)
.then((entry) => {
if (entry) {
this['props'] = _.extend({}, entry);
}
});
};
MixpanelPersistence.prototype.save = function() {
if (this.disabled) { return; }
this.storage.set(
this.name,
_.JSONEncode(this['props'])
);
};
MixpanelPersistence.prototype.remove = function() {
this.storage.remove(this.name);
};
// removes the storage entry and deletes all loaded data
// forced name for tests
MixpanelPersistence.prototype.clear = function() {
this.remove();
this['props'] = {};
};
/**
* @param {Object} props
* @param {*=} default_value
* @param {number=} days
*/
MixpanelPersistence.prototype.register_once = function(props, default_value, days) {
if (_.isObject(props)) {
if (typeof(default_value) === 'undefined') { default_value = 'None'; }
this.expire_days = (typeof(days) === 'undefined') ? this.default_expiry : days;
_.each(props, function(val, prop) {
if (!this['props'][prop] || this['props'][prop] === default_value) {
this['props'][prop] = val;
}
}, this);
this.save();
return true;
}
return false;
};
/**
* @param {Object} props
* @param {number=} days
*/
MixpanelPersistence.prototype.register = function(props, days) {
if (_.isObject(props)) {
this.expire_days = (typeof(days) === 'undefined') ? this.default_expiry : days;
_.extend(this['props'], props);
this.save();
return true;
}
return false;
};
MixpanelPersistence.prototype.unregister = function(prop) {
if (prop in this['props']) {
delete this['props'][prop];
this.save();
}
};
MixpanelPersistence.prototype.update_campaign_params = function() {
if (!this.campaign_params_saved) {
this.register_once(_.info.campaignParams());
this.campaign_params_saved = true;
}
};
MixpanelPersistence.prototype.update_search_keyword = function(referrer) {
this.register(_.info.searchInfo(referrer));
};
// EXPORTED METHOD, we test this directly.
MixpanelPersistence.prototype.update_referrer_info = function(referrer) {
// If referrer doesn't exist, we want to note the fact that it was type-in traffic.
this.register_once({
'$initial_referrer': referrer || '$direct',
'$initial_referring_domain': _.info.referringDomain(referrer) || '$direct'
}, '');
};
MixpanelPersistence.prototype.get_referrer_info = function() {
return _.strip_empty_properties({
'$initial_referrer': this['props']['$initial_referrer'],
'$initial_referring_domain': this['props']['$initial_referring_domain']
});
};
// safely fills the passed in object with stored properties,
// does not override any properties defined in both
// returns the passed in object
MixpanelPersistence.prototype.safe_merge = function(props) {
_.each(this['props'], function(val, prop) {
if (!(prop in props)) {
props[prop] = val;
}
});
return props;
};
MixpanelPersistence.prototype.update_config = function(config) {
this.set_disabled(config['disable_persistence']);
};
MixpanelPersistence.prototype.set_disabled = function(disabled) {
this.disabled = disabled;
if (this.disabled) {
this.remove();
}
};
MixpanelPersistence.prototype._add_to_people_queue = function(queue, data) {
var q_key = this._get_queue_key(queue),
q_data = data[queue],
set_q = this._get_or_create_queue(SET_ACTION),
set_once_q = this._get_or_create_queue(SET_ONCE_ACTION),
add_q = this._get_or_create_queue(ADD_ACTION),
union_q = this._get_or_create_queue(UNION_ACTION),
append_q = this._get_or_create_queue(APPEND_ACTION, []);
if (q_key === SET_QUEUE_KEY) {
// Update the set queue - we can override any existing values
_.extend(set_q, q_data);
// if there was a pending increment, override it
// with the set.
this._pop_from_people_queue(ADD_ACTION, q_data);
// if there was a pending union, override it
// with the set.
this._pop_from_people_queue(UNION_ACTION, q_data);
} else if (q_key === SET_ONCE_QUEUE_KEY) {
// only queue the data if there is not already a set_once call for it.
_.each(q_data, function(v, k) {
if (!(k in set_once_q)) {
set_once_q[k] = v;
}
});
} else if (q_key === ADD_QUEUE_KEY) {
_.each(q_data, function(v, k) {
// If it exists in the set queue, increment
// the value
if (k in set_q) {
set_q[k] += v;
} else {
// If it doesn't exist, update the add
// queue
if (!(k in add_q)) {
add_q[k] = 0;
}
add_q[k] += v;
}
}, this);
} else if (q_key === UNION_QUEUE_KEY) {
_.each(q_data, function(v, k) {
if (_.isArray(v)) {
if (!(k in union_q)) {
union_q[k] = [];
}
// We may send duplicates, the server will dedup them.
union_q[k] = union_q[k].concat(v);
}
});
} else if (q_key === APPEND_QUEUE_KEY) {
append_q.push(q_data);
}
console$1.log('MIXPANEL PEOPLE REQUEST (QUEUED, PENDING IDENTIFY):');
console$1.log(data);
this.save();
};
MixpanelPersistence.prototype._pop_from_people_queue = function(queue, data) {
var q = this._get_queue(queue);
if (!_.isUndefined(q)) {
_.each(data, function(v, k) {
delete q[k];
}, this);
this.save();
}
};
MixpanelPersistence.prototype._get_queue_key = function(queue) {
if (queue === SET_ACTION) {
return SET_QUEUE_KEY;
} else if (queue === SET_ONCE_ACTION) {
return SET_ONCE_QUEUE_KEY;
} else if (queue === ADD_ACTION) {
return ADD_QUEUE_KEY;
} else if (queue === APPEND_ACTION) {
return APPEND_QUEUE_KEY;
} else if (queue === UNION_ACTION) {
return UNION_QUEUE_KEY;
} else {
console$1.error('Invalid queue:', queue);
}
};
MixpanelPersistence.prototype._get_queue = function(queue) {
return this['props'][this._get_queue_key(queue)];
};
MixpanelPersistence.prototype._get_or_create_queue = function(queue, default_val) {
var key = this._get_queue_key(queue);
default_val = _.isUndefined(default_val) ? {} : default_val;
return this['props'][key] || (this['props'][key] = default_val);
};
MixpanelPersistence.prototype.set_event_timer = function(event_name, timestamp) {
var timers = this['props'][EVENT_TIMERS_KEY] || {};
timers[event_name] = timestamp;
this['props'][EVENT_TIMERS_KEY] = timers;
this.save();
};
MixpanelPersistence.prototype.remove_event_timer = function(event_name) {
var timers = this['props'][EVENT_TIMERS_KEY] || {};
var timestamp = timers[event_name];
if (!_.isUndefined(timestamp)) {
delete this['props'][EVENT_TIMERS_KEY][event_name];
this.save();
}
return timestamp;
};
/**
* Mixpanel Library Object
* @constructor
*/
var MixpanelLib = function() {};
/**
* Mixpanel People Object
* @constructor
*/
var MixpanelPeople = function() {};
/**
* create_mplib(token:string, config:object, name:string)
*
* This function is used by the init method of MixpanelLib objects
* as well as the main initializer at the end of the JSLib (that
* initializes document.mixpanel as well as any additional instances
* declared before this file has loaded).
*/
var create_mplib = function(token, config, name) {
var instance,
target = (name === PRIMARY_INSTANCE_NAME) ? mixpanel_master : mixpanel_master[name];
if (target && init_type === INIT_MODULE) {
instance = target;
} else {
if (target && !_.isArray(target)) {
console$1.error('You have already initialized ' + name);
return;
}
instance = new MixpanelLib();
}
instance._init(token, config, name);
instance['people'] = new MixpanelPeople();
instance['people']._init(instance);
// if any instance on the page has debug = true, we set the
// global debug to be true
Config.DEBUG = Config.DEBUG || instance.get_config('debug');
// if target is not defined, we called init after the lib already
// loaded, so there won't be an array of things to execute
if (!_.isUndefined(target) && _.isArray(target)) {
// Crunch through the people queue first - we queue this data up &
// flush on identify, so it's better to do all these operations first
instance._execute_array.call(instance['people'], target['people']);
instance._execute_array(target);
}
return instance;
};
// Initialization methods
/**
* This function initializes a new instance of the Mixpanel tracking object.
* All new instances are added to the main mixpanel object as sub properties (such as
* mixpanel.library_name) and also returned by this function. To define a
* second instance on the page, you would call:
*
* mixpanel.init('new token', { your: 'config' }, 'library_name');
*
* and use it like so:
*
* mixpanel.library_name.track(...);
*
* @param {String} token Your Mixpanel API token
* @param {Object} [config] A dictionary of config options to override
* @param {String} [name] The name for the new mixpanel instance that you want created
*/
MixpanelLib.prototype.init = function (token, config, name) {
if (_.isUndefined(name)) {