-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathamplitude-client.js
3493 lines (2986 loc) · 131 KB
/
amplitude-client.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
import sinon from 'sinon';
import AmplitudeClient from '../src/amplitude-client.js';
import getUtmData from '../src/utm.js';
import Cookie from '../src/cookie';
import MetadataStorage from '../src/metadata-storage';
import localStorage from '../src/localstorage.js';
import CookieStorage from '../src/cookiestorage.js';
import baseCookie from '../src/base-cookie.js';
import Base64 from '../src/base64.js';
import cookie from '../src/cookie.js';
import utils from '../src/utils.js';
import queryString from 'query-string';
import Identify from '../src/identify.js';
import Revenue from '../src/revenue.js';
import constants from '../src/constants.js';
import { mockCookie, restoreCookie, getCookie } from './mock-cookie';
// maintain for testing backwards compatability
describe('AmplitudeClient', function() {
var apiKey = '000000';
const cookieName = 'amp_' + apiKey.slice(0,6);
const oldCookieName = 'amplitude_id_' + apiKey;
var keySuffix = '_' + apiKey.slice(0,6);
var userId = 'user';
var amplitude;
var server;
beforeEach(function() {
amplitude = new AmplitudeClient();
server = sinon.fakeServer.create();
});
afterEach(function() {
server.restore();
});
it('amplitude object should exist', function() {
assert.isObject(amplitude);
});
function reset() {
localStorage.clear();
sessionStorage.clear();
restoreCookie();
cookie.remove(amplitude.options.cookieName);
cookie.remove(amplitude.options.cookieName + keySuffix);
cookie.remove(amplitude.options.cookieName + '_new_app');
cookie.remove(oldCookieName);
cookie.remove(cookieName);
cookie.remove('amp_');
cookie.reset();
}
describe('init', function() {
beforeEach(function() {
reset();
});
afterEach(function() {
reset();
});
it('should make instanceName case-insensitive', function() {
assert.equal(new AmplitudeClient('APP3')._instanceName, 'app3');
assert.equal(new AmplitudeClient('$DEFAULT_INSTANCE')._instanceName, '$default_instance');
});
it('should invoke onInit callbacks', () => {
const callback = sinon.spy();
amplitude.onInit(callback);
amplitude.onInit(callback);
amplitude.init(apiKey);
assert.isTrue(callback.calledTwice);
});
it('should not invoke onInit callbacks before init is called', () => {
const callback = sinon.spy();
amplitude.onInit(callback);
assert.isFalse(callback.calledOnce);
});
it('should pass the amplitude instance to onInit callbacks', () => {
const callback = sinon.spy();
amplitude.onInit(callback);
amplitude.init(apiKey);
assert.isTrue(callback.calledWith(amplitude));
});
it('should set the Secure flag on cookie with the secureCookie option', () => {
mockCookie();
amplitude.init(apiKey, null, { secureCookie: true });
assert.include(getCookie(cookieName).options, 'Secure');
});
it('should set the SameSite cookie option to Lax by default', () => {
mockCookie();
amplitude.init(apiKey);
assert.include(getCookie(cookieName).options, 'SameSite=Lax');
});
it('should set the sameSite option on a cookie with the sameSiteCookie Option', () => {
mockCookie();
amplitude.init(apiKey, null, {sameSiteCookie: 'Strict'});
assert.include(getCookie(cookieName).options, 'SameSite=Strict');
});
it('should immediately invoke onInit callbacks if already initialized', function() {
let onInitCalled = false;
amplitude.init(apiKey);
amplitude.onInit(() => { onInitCalled = true; });
assert.ok(onInitCalled);
});
it('should clear the onInitQueue', function() {
let onInitCalled = false;
let onInit2Called = false;
amplitude.onInit(() => { onInitCalled = true; });
amplitude.onInit(() => { onInit2Called = true; });
amplitude.init(apiKey);
assert.lengthOf(amplitude._onInit, 0);
});
it('fails on invalid apiKeys', function() {
amplitude.init(null);
assert.equal(amplitude.options.apiKey, undefined);
assert.equal(amplitude.options.deviceId, undefined);
amplitude.init('');
assert.equal(amplitude.options.apiKey, undefined);
assert.equal(amplitude.options.deviceId, undefined);
amplitude.init(apiKey);
assert.equal(amplitude.options.apiKey, apiKey);
assert.lengthOf(amplitude.options.deviceId, 22);
});
it('should accept userId', function() {
amplitude.init(apiKey, userId);
assert.equal(amplitude.options.userId, userId);
});
it('should accept numerical userIds', function() {
const userId = 5;
amplitude.init(apiKey, 5);
assert.equal(amplitude.options.userId, '5');
});
it('should generate a random deviceId', function() {
amplitude.init(apiKey, userId);
assert.lengthOf(amplitude.options.deviceId, 22)
});
it('should validate config values', function() {
var config = {
apiEndpoint: 100, // invalid type
batchEvents: 'True', // invalid type
cookieExpiration: -1, // negative number
cookieName: '', // empty string
eventUploadPeriodMillis: '30', // 30s
eventUploadThreshold: 0, // zero value
bogusKey: false
};
amplitude.init(apiKey, userId, config);
assert.equal(amplitude.options.apiEndpoint, 'api.amplitude.com');
assert.equal(amplitude.options.batchEvents, false);
assert.equal(amplitude.options.cookieExpiration, 3650);
assert.equal(amplitude.options.cookieName, 'amplitude_id');
assert.equal(amplitude.options.eventUploadPeriodMillis, 30000);
assert.equal(amplitude.options.eventUploadThreshold, 30);
assert.equal(amplitude.options.bogusKey, undefined);
});
it('should set the default log level', function() {
const config = {};
amplitude.init(apiKey, userId, config);
assert.equal(utils.getLogLevel(), 2);
});
it('should set log levels', function() {
const config = {
logLevel: 'INFO',
};
amplitude.init(apiKey, userId, config);
assert.equal(utils.getLogLevel(), 3);
});
it('should set cookie', function() {
amplitude.init(apiKey, userId);
const storage = new MetadataStorage({storageKey: cookieName});
const stored = storage.load();
assert.property(stored, 'deviceId');
assert.propertyVal(stored, 'userId', userId);
assert.lengthOf(stored.deviceId, 22);
});
it('should set language', function() {
amplitude.init(apiKey, userId);
assert.property(amplitude.options, 'language');
assert.isNotNull(amplitude.options.language);
});
it('should allow language override', function() {
amplitude.init(apiKey, userId, {language: 'en-GB'});
assert.propertyVal(amplitude.options, 'language', 'en-GB');
});
it ('should not run callback if invalid callback', function() {
amplitude.init(apiKey, userId, null, 'invalid callback');
});
it ('should run valid callbacks', function() {
var counter = 0;
var callback = function() {
counter++;
};
amplitude.init(apiKey, userId, null, callback);
assert.equal(counter, 1);
});
it ('should load the device id from url params if configured', function() {
var deviceId = 'aa_bb_cc_dd';
sinon.stub(amplitude, '_getUrlParams').returns('?utm_source=amplitude&utm_medium=email&gclid=12345&_device_id=aa_bb_cc_dd');
amplitude.init(apiKey, userId, {deviceIdFromUrlParam: true});
assert.equal(amplitude.options.deviceId, deviceId);
const storage = new MetadataStorage({storageKey: cookieName});
const cookieData = storage.load();
assert.equal(cookieData.deviceId, deviceId);
amplitude._getUrlParams.restore();
});
it ('should not load device id from url params if not configured', function() {
var deviceId = 'aa_bb_cc_dd';
sinon.stub(amplitude, '_getUrlParams').returns('?utm_source=amplitude&utm_medium=email&gclid=12345&_device_id=aa_bb_cc_dd');
amplitude.init(apiKey, userId, {deviceIdFromUrlParam: false});
assert.notEqual(amplitude.options.deviceId, deviceId);
const storage = new MetadataStorage({storageKey: cookieName});
const cookieData = storage.load();
assert.notEqual(cookieData.deviceId, deviceId);
amplitude._getUrlParams.restore();
});
it ('should prefer the device id in the config over the url params', function() {
var deviceId = 'dd_cc_bb_aa';
sinon.stub(amplitude, '_getUrlParams').returns('?utm_source=amplitude&utm_medium=email&gclid=12345&_device_id=aa_bb_cc_dd');
amplitude.init(apiKey, userId, {deviceId: deviceId, deviceIdFromUrlParam: true});
assert.equal(amplitude.options.deviceId, deviceId);
const storage = new MetadataStorage({storageKey: cookieName});
const cookieData = storage.load();
assert.equal(cookieData.deviceId, deviceId);
amplitude._getUrlParams.restore();
});
it('should load device id from the cookie', function(){
var now = new Date().getTime();
// deviceId and sequenceNumber not set, init should load value from localStorage
var cookieData = {
deviceId: 'current_device_id',
}
cookie.set(amplitude.options.cookieName + '_' + apiKey, cookieData);
amplitude.init(apiKey);
assert.equal(amplitude.options.deviceId, 'current_device_id');
});
it('should upgrade the new cookie to the old cookie if forceUpgrade is on', function(){
var now = new Date().getTime();
var cookieData = {
deviceId: 'old_device_id',
optOut: false,
sessionId: now,
lastEventTime: now,
eventId: 50,
identifyId: 60
}
cookie.set(oldCookieName, cookieData);
amplitude.init(apiKey, null, { cookieForceUpgrade: true });
const cookieData = cookie.getRaw(cookieName);
assert.equal('old_device_id', cookieData.slice(0, 'old_device_id'.length));
});
it('should delete the old old cookie if forceUpgrade is on', function(){
var now = new Date().getTime();
var cookieData = {
deviceId: 'old_device_id',
optOut: false,
sessionId: now,
lastEventTime: now,
eventId: 50,
identifyId: 60
}
cookie.set(oldCookieName, cookieData);
amplitude.init(apiKey, null, { cookieForceUpgrade: true });
const cookieData = cookie.get(oldCookieName);
assert.isNull(cookieData);
});
it('should use device id from the old cookie if a new cookie does not exist', function(){
var now = new Date().getTime();
var cookieData = {
deviceId: 'old_device_id',
optOut: false,
sessionId: now,
lastEventTime: now,
eventId: 50,
identifyId: 60
}
cookie.set(oldCookieName, cookieData);
amplitude.init(apiKey, null);
assert.equal(amplitude.options.deviceId, 'old_device_id');
});
it('should favor the device id from the new cookie even if the old cookie exists', function(){
var now = new Date().getTime();
var cookieData = {
deviceId: 'old_device_id',
optOut: false,
sessionId: now,
lastEventTime: now,
eventId: 50,
identifyId: 60
}
cookie.set(oldCookieName, cookieData);
cookie.setRaw(cookieName, `new_device_id.${Base64.encode(userId)}..1000.1000.0.0.0`);
amplitude.init(apiKey, null);
assert.equal(amplitude.options.deviceId, 'new_device_id');
});
it('should save cookie data to localStorage if cookies are not enabled', function() {
var deviceId = 'test_device_id';
var clock = sinon.useFakeTimers();
clock.tick(1000);
localStorage.clear();
sinon.stub(baseCookie, 'areCookiesEnabled').returns(false);
var amplitude2 = new AmplitudeClient();
amplitude2.init(apiKey, userId, {'deviceId': deviceId});
baseCookie.areCookiesEnabled.restore();
clock.restore();
var cookieData = localStorage.getItem(cookieName);
assert.equal(
cookieData,
`${deviceId}.${Base64.encode(userId)}..v8.v8.0.0.0`
);
assert.isNull(cookie.get(amplitude2.options.cookieName)); // assert did not write to cookies
});
it('should load sessionId, eventId from cookie and ignore the one in localStorage', function() {
var amplitude2 = new AmplitudeClient();
var clock = sinon.useFakeTimers();
clock.tick(1000);
var sessionId = new Date().getTime();
// the following values in localStorage will all be ignored
localStorage.clear();
localStorage.setItem('cookieName',`0.0.0.3.4.5.6.7`);
var cookieData = {
deviceId: 'test_device_id',
userId: 'test_user_id',
optOut: true,
sessionId: sessionId,
lastEventTime: sessionId,
eventId: 50,
identifyId: 60,
sequenceNumber: 70
}
const storage = new MetadataStorage({storageKey: cookieName, disableCookieStorage: true});
storage.save(cookieData);
clock.tick(10);
amplitude2.init(apiKey);
clock.restore();
assert.equal(amplitude2._sessionId, sessionId);
assert.equal(amplitude2._lastEventTime, sessionId + 10);
assert.equal(amplitude2._eventId, 50);
assert.equal(amplitude2._identifyId, 60);
assert.equal(amplitude2._sequenceNumber, 70);
});
it('should load sessionId from localStorage if not in cookie', function() {
var amplitude2 = new AmplitudeClient();
var cookieData = {
deviceId: 'test_device_id',
userId: userId,
optOut: true
}
cookie.set(amplitude2.options.cookieName, cookieData);
var clock = sinon.useFakeTimers();
clock.tick(1000);
var sessionId = new Date().getTime();
localStorage.clear();
localStorage.setItem(cookieName,`0.0.0.${sessionId.toString(32)}.${sessionId.toString(32)}.1i.1s.26`);
clock.tick(10);
amplitude2.init(apiKey, userId);
clock.restore();
assert.equal(amplitude2._sessionId, sessionId);
assert.equal(amplitude2._lastEventTime, sessionId + 10);
assert.equal(amplitude2._eventId, 50);
assert.equal(amplitude2._identifyId, 60);
assert.equal(amplitude2._sequenceNumber, 70);
});
it('should load saved events from localStorage for default instance', function() {
var existingEvent = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769146589,' +
'"event_id":49,"session_id":1453763315544,"event_type":"clicked","version_name":"Web","platform":"Web"' +
',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' +
'"event_properties":{},"user_properties":{},"uuid":"3c508faa-a5c9-45fa-9da7-9f4f3b992fb0","library"' +
':{"name":"amplitude-js","version":"2.9.0"},"sequence_number":130,"groups":{}}]';
var existingIdentify = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769338995,' +
'"event_id":82,"session_id":1453763315544,"event_type":"$identify","version_name":"Web","platform":"Web"' +
',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' +
'"event_properties":{},"user_properties":{"$set":{"age":30,"city":"San Francisco, CA"}},"uuid":"' +
'c50e1be4-7976-436a-aa25-d9ee38951082","library":{"name":"amplitude-js","version":"2.9.0"},"sequence_number"' +
':131,"groups":{}}]';
localStorage.setItem('amplitude_unsent_' + apiKey, existingEvent);
localStorage.setItem('amplitude_unsent_identify_' + apiKey, existingIdentify);
var amplitude2 = new AmplitudeClient('$default_Instance');
amplitude2.init(apiKey, null, {batchEvents: true});
// check event loaded into memory
assert.deepEqual(amplitude2._unsentEvents.map(({event}) => event), JSON.parse(existingEvent));
assert.deepEqual(amplitude2._unsentIdentifys.map(({event}) => event), JSON.parse(existingIdentify));
// check local storage keys are still same for default instance
assert.equal(localStorage.getItem('amplitude_unsent_' + apiKey), existingEvent);
assert.equal(localStorage.getItem('amplitude_unsent_identify_' + apiKey), existingIdentify);
});
it('should load saved events for non-default instances', function() {
var existingEvent = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769146589,' +
'"event_id":49,"session_id":1453763315544,"event_type":"clicked","version_name":"Web","platform":"Web"' +
',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' +
'"event_properties":{},"user_properties":{},"uuid":"3c508faa-a5c9-45fa-9da7-9f4f3b992fb0","library"' +
':{"name":"amplitude-js","version":"2.9.0"},"sequence_number":130,"groups":{}}]';
var existingIdentify = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769338995,' +
'"event_id":82,"session_id":1453763315544,"event_type":"$identify","version_name":"Web","platform":"Web"' +
',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' +
'"event_properties":{},"user_properties":{"$set":{"age":30,"city":"San Francisco, CA"}},"uuid":"' +
'c50e1be4-7976-436a-aa25-d9ee38951082","library":{"name":"amplitude-js","version":"2.9.0"},"sequence_number"' +
':131,"groups":{}}]';
localStorage.setItem('amplitude_unsent_' + apiKey + '_new_app', existingEvent);
localStorage.setItem('amplitude_unsent_identify_' + apiKey + '_new_app', existingIdentify);
assert.isNull(localStorage.getItem('amplitude_unsent'));
assert.isNull(localStorage.getItem('amplitude_unsent_identify'));
var amplitude2 = new AmplitudeClient('new_app');
amplitude2.init(apiKey, null, {batchEvents: true});
// check event loaded into memory
assert.deepEqual(amplitude2._unsentEvents.map(({event}) => event), JSON.parse(existingEvent));
assert.deepEqual(amplitude2._unsentIdentifys.map(({event}) => event), JSON.parse(existingIdentify));
// check local storage keys are still same
assert.equal(localStorage.getItem('amplitude_unsent_' + apiKey +'_new_app'), existingEvent);
assert.equal(localStorage.getItem('amplitude_unsent_identify_' + apiKey + '_new_app'), existingIdentify);
});
it('should validate event properties when loading saved events from localStorage', function() {
var existingEvents = '[{"device_id":"15a82aaa-0d9e-4083-a32d-2352191877e6","user_id":"15a82aaa-0d9e-4083-a32d' +
'-2352191877e6","timestamp":1455744744413,"event_id":2,"session_id":1455744733865,"event_type":"clicked",' +
'"version_name":"Web","platform":"Web","os_name":"Chrome","os_version":"48","device_model":"Mac","language"' +
':"en-US","api_properties":{},"event_properties":"{}","user_properties":{},"uuid":"1b8859d9-e91e-403e-92d4-' +
'c600dfb83432","library":{"name":"amplitude-js","version":"2.9.0"},"sequence_number":4},{"device_id":"15a82a' +
'aa-0d9e-4083-a32d-2352191877e6","user_id":"15a82aaa-0d9e-4083-a32d-2352191877e6","timestamp":1455744746295,' +
'"event_id":3,"session_id":1455744733865,"event_type":"clicked","version_name":"Web","platform":"Web",' +
'"os_name":"Chrome","os_version":"48","device_model":"Mac","language":"en-US","api_properties":{},' +
'"event_properties":{"10":"false","bool":true,"null":null,"string":"test","array":' +
'[0,1,2,"3"],"nested_array":["a",{"key":"value"},["b"]],"object":{"key":"value"},"nested_object":' +
'{"k":"v","l":[0,1],"o":{"k2":"v2","l2":["e2",{"k3":"v3"}]}}},"user_properties":{},"uuid":"650407a1-d705-' +
'47a0-8918-b4530ce51f89","library":{"name":"amplitude-js","version":"2.9.0"},"sequence_number":5}]'
localStorage.setItem('amplitude_unsent_' + apiKey, existingEvents);
var amplitude2 = new AmplitudeClient('$default_instance');
amplitude2.init(apiKey, null, {batchEvents: true});
var expected = {
'10': 'false',
'bool': true,
'string': 'test',
'array': [0, 1, 2, '3'],
'nested_array': ['a', {'key':'value'}],
'object': {'key':'value'},
'nested_object': {'k':'v', 'l':[0,1], 'o':{'k2':'v2', 'l2': ['e2', {'k3':'v3'}]}}
}
// check that event loaded into memory
assert.deepEqual(amplitude2._unsentEvents[0].event.event_properties, {});
assert.deepEqual(amplitude2._unsentEvents[1].event.event_properties, expected);
});
it('should validate user properties when loading saved identifys from localStorage', function() {
var existingEvents = '[{"device_id":"15a82a' +
'aa-0d9e-4083-a32d-2352191877e6","user_id":"15a82aaa-0d9e-4083-a32d-2352191877e6","timestamp":1455744746295,' +
'"event_id":3,"session_id":1455744733865,"event_type":"$identify","version_name":"Web","platform":"Web",' +
'"os_name":"Chrome","os_version":"48","device_model":"Mac","language":"en-US","api_properties":{},' +
'"user_properties":{"$set":{"10":"false","bool":true,"null":null,"string":"test","array":' +
'[0,1,2,"3"],"nested_array":["a",{"key":"value"},["b"]],"object":{"key":"value"},"nested_object":' +
'{"k":"v","l":[0,1],"o":{"k2":"v2","l2":["e2",{"k3":"v3"}]}}}},"event_properties":{},"uuid":"650407a1-d705-' +
'47a0-8918-b4530ce51f89","library":{"name":"amplitude-js","version":"2.9.0"},"sequence_number":5}]'
localStorage.setItem('amplitude_unsent_identify_' + apiKey, existingEvents);
var amplitude2 = new AmplitudeClient();
amplitude2.init(apiKey, null, {batchEvents: true});
var expected = {
'10': 'false',
'bool': true,
'string': 'test',
'array': [0, 1, 2, '3'],
'nested_array': ['a', {'key':'value'}],
'object': {'key':'value'},
'nested_object': {'k':'v', 'l':[0,1], 'o':{'k2':'v2', 'l2': ['e2', {'k3':'v3'}]}}
}
// check that event loaded into memory
assert.deepEqual(amplitude2._unsentIdentifys[0].event.user_properties, {'$set': expected});
});
it ('should load saved events from localStorage and send events for default instance', function() {
var existingEvent = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769146589,' +
'"event_id":49,"session_id":1453763315544,"event_type":"clicked","version_name":"Web","platform":"Web"' +
',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' +
'"event_properties":{},"user_properties":{},"uuid":"3c508faa-a5c9-45fa-9da7-9f4f3b992fb0","library"' +
':{"name":"amplitude-js","version":"2.9.0"},"sequence_number":130}]';
var existingIdentify = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769338995,' +
'"event_id":82,"session_id":1453763315544,"event_type":"$identify","version_name":"Web","platform":"Web"' +
',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' +
'"event_properties":{},"user_properties":{"$set":{"age":30,"city":"San Francisco, CA"}},"uuid":"' +
'c50e1be4-7976-436a-aa25-d9ee38951082","library":{"name":"amplitude-js","version":"2.9.0"},"sequence_number"' +
':131}]';
localStorage.setItem('amplitude_unsent_' + apiKey, existingEvent);
localStorage.setItem('amplitude_unsent_identify_' + apiKey, existingIdentify);
var amplitude2 = new AmplitudeClient();
amplitude2.init(apiKey, null, {batchEvents: true, eventUploadThreshold: 2});
server.respondWith('success');
server.respond();
// check event loaded into memory
assert.deepEqual(amplitude2._unsentEvents, []);
assert.deepEqual(amplitude2._unsentIdentifys, []);
// check local storage keys are still same
assert.equal(localStorage.getItem('amplitude_unsent_' + apiKey), JSON.stringify([]));
assert.equal(localStorage.getItem('amplitude_unsent_identify_' + apiKey), JSON.stringify([]));
// check request
assert.lengthOf(server.requests, 1);
var events = JSON.parse(queryString.parse(server.requests[0].requestBody).e);
assert.lengthOf(events, 2);
assert.equal(events[0].event_id, 49);
assert.equal(events[1].event_type, '$identify');
});
it ('should load saved events from localStorage new keys and send events', function() {
var existingEvent = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769146589,' +
'"event_id":49,"session_id":1453763315544,"event_type":"clicked","version_name":"Web","platform":"Web"' +
',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' +
'"event_properties":{},"user_properties":{},"uuid":"3c508faa-a5c9-45fa-9da7-9f4f3b992fb0","library"' +
':{"name":"amplitude-js","version":"2.9.0"},"sequence_number":130}]';
var existingIdentify = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769338995,' +
'"event_id":82,"session_id":1453763315544,"event_type":"$identify","version_name":"Web","platform":"Web"' +
',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' +
'"event_properties":{},"user_properties":{"$set":{"age":30,"city":"San Francisco, CA"}},"uuid":"' +
'c50e1be4-7976-436a-aa25-d9ee38951082","library":{"name":"amplitude-js","version":"2.9.0"},"sequence_number"' +
':131}]';
localStorage.setItem('amplitude_unsent_' + apiKey + '_new_app', existingEvent);
localStorage.setItem('amplitude_unsent_identify_' + apiKey + '_new_app', existingIdentify);
var amplitude2 = new AmplitudeClient('new_app');
amplitude2.init(apiKey, null, {batchEvents: true, eventUploadThreshold: 2});
server.respondWith('success');
server.respond();
// check event loaded into memory
assert.deepEqual(amplitude2._unsentEvents, []);
assert.deepEqual(amplitude2._unsentIdentifys, []);
// check local storage keys are still same
assert.equal(localStorage.getItem('amplitude_unsent_' + apiKey + '_new_app'), JSON.stringify([]));
assert.equal(localStorage.getItem('amplitude_unsent_identify_' + apiKey + '_new_app'), JSON.stringify([]));
// check request
assert.lengthOf(server.requests, 1);
var events = JSON.parse(queryString.parse(server.requests[0].requestBody).e);
assert.lengthOf(events, 2);
assert.equal(events[0].event_id, 49);
assert.equal(events[1].event_type, '$identify');
});
it('should validate event properties when loading saved events from localStorage', function() {
var existingEvents = '[{"device_id":"15a82aaa-0d9e-4083-a32d-2352191877e6","user_id":"15a82aaa-0d9e-4083-a32d' +
'-2352191877e6","timestamp":1455744744413,"event_id":2,"session_id":1455744733865,"event_type":"clicked",' +
'"version_name":"Web","platform":"Web","os_name":"Chrome","os_version":"48","device_model":"Mac","language"' +
':"en-US","api_properties":{},"event_properties":"{}","user_properties":{},"uuid":"1b8859d9-e91e-403e-92d4-' +
'c600dfb83432","library":{"name":"amplitude-js","version":"2.9.0"},"sequence_number":4},{"device_id":"15a82a' +
'aa-0d9e-4083-a32d-2352191877e6","user_id":"15a82aaa-0d9e-4083-a32d-2352191877e6","timestamp":1455744746295,' +
'"event_id":3,"session_id":1455744733865,"event_type":"clicked","version_name":"Web","platform":"Web",' +
'"os_name":"Chrome","os_version":"48","device_model":"Mac","language":"en-US","api_properties":{},' +
'"event_properties":{"10":"false","bool":true,"null":null,"string":"test","array":' +
'[0,1,2,"3"],"nested_array":["a",{"key":"value"},["b"]],"object":{"key":"value"},"nested_object":' +
'{"k":"v","l":[0,1],"o":{"k2":"v2","l2":["e2",{"k3":"v3"}]}}},"user_properties":{},"uuid":"650407a1-d705-' +
'47a0-8918-b4530ce51f89","library":{"name":"amplitude-js","version":"2.9.0"},"sequence_number":5}]';
localStorage.setItem('amplitude_unsent_' + apiKey, existingEvents);
var amplitude2 = new AmplitudeClient();
amplitude2.init(apiKey, null, {
batchEvents: true
});
var expected = {
'10': 'false',
'bool': true,
'string': 'test',
'array': [0, 1, 2, '3'],
'nested_array': ['a', {'key':'value'}],
'object': {
'key': 'value'
},
'nested_object': {
'k': 'v',
'l': [0, 1],
'o': {
'k2': 'v2',
'l2': ['e2', {'k3':'v3'}]
}
}
}
// check that event loaded into memory
assert.deepEqual(amplitude2._unsentEvents[0].event.event_properties, {});
assert.deepEqual(amplitude2._unsentEvents[1].event.event_properties, expected);
});
it('should not load saved events from another instances\'s localStorage', function() {
var existingEvent = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769146589,' +
'"event_id":49,"session_id":1453763315544,"event_type":"clicked","version_name":"Web","platform":"Web"' +
',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' +
'"event_properties":{},"user_properties":{},"uuid":"3c508faa-a5c9-45fa-9da7-9f4f3b992fb0","library"' +
':{"name":"amplitude-js","version":"2.9.0"},"sequence_number":130}]';
var existingIdentify = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769338995,' +
'"event_id":82,"session_id":1453763315544,"event_type":"$identify","version_name":"Web","platform":"Web"' +
',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' +
'"event_properties":{},"user_properties":{"$set":{"age":30,"city":"San Francisco, CA"}},"uuid":"' +
'c50e1be4-7976-436a-aa25-d9ee38951082","library":{"name":"amplitude-js","version":"2.9.0"},"sequence_number"' +
':131}]';
localStorage.setItem('amplitude_unsent_' + apiKey, existingEvent);
localStorage.setItem('amplitude_unsent_identify_' + apiKey, existingIdentify);
assert.isNull(localStorage.getItem('amplitude_unsent_' + apiKey + '_new_app'));
assert.isNull(localStorage.getItem('amplitude_unsent_identify_' + apiKey + '_new_app'));
var amplitude2 = new AmplitudeClient('new_app');
amplitude2.init(apiKey, null, {batchEvents: true, eventUploadThreshold: 2});
// check events not loaded into memory
assert.deepEqual(amplitude2._unsentEvents, []);
assert.deepEqual(amplitude2._unsentIdentifys, []);
// check local storage
assert.equal(localStorage.getItem('amplitude_unsent_' + apiKey), existingEvent);
assert.equal(localStorage.getItem('amplitude_unsent_identify_' + apiKey), existingIdentify);
assert.equal(localStorage.getItem('amplitude_unsent_' + apiKey + '_new_app'), '[]');
assert.equal(localStorage.getItem('amplitude_unsent_identify_' + apiKey + '_new_app'), '[]');
// check request
assert.lengthOf(server.requests, 0);
});
it('should merge tracking options during parseConfig', function() {
var trackingOptions = {
city: false,
ip_address: false,
language: false,
region: true,
};
var amplitude2 = new AmplitudeClient('new_app');
amplitude2.init(apiKey, null, {trackingOptions: trackingOptions});
// check config loaded correctly
assert.deepEqual(amplitude2.options.trackingOptions, {
city: false,
country: true,
carrier: true,
device_manufacturer: true,
device_model: true,
dma: true,
ip_address: false,
language: false,
os_name: true,
os_version: true,
platform: true,
region: true,
version_name: true
});
});
it('should pregenerate tracking options for api properties', function() {
var trackingOptions = {
city: false,
ip_address: false,
language: false,
region: true,
};
var amplitude2 = new AmplitudeClient('new_app');
amplitude2.init(apiKey, null, {trackingOptions: trackingOptions});
assert.deepEqual(amplitude2._apiPropertiesTrackingOptions, {tracking_options: {
city: false,
ip_address: false
}});
});
});
describe('runQueuedFunctions', function() {
beforeEach(function() {
amplitude.init(apiKey);
});
afterEach(function() {
reset();
});
it('should run queued functions', function() {
assert.equal(amplitude._unsentCount(), 0);
assert.lengthOf(server.requests, 0);
var userId = 'testUserId'
var eventType = 'test_event'
var functions = [
['setUserId', userId],
['logEvent', eventType]
];
amplitude._q = functions;
assert.lengthOf(amplitude._q, 2);
amplitude.runQueuedFunctions();
assert.equal(amplitude.options.userId, userId);
assert.equal(amplitude._unsentCount(), 1);
assert.lengthOf(server.requests, 1);
var events = JSON.parse(queryString.parse(server.requests[0].requestBody).e);
assert.lengthOf(events, 1);
assert.equal(events[0].event_type, eventType);
assert.lengthOf(amplitude._q, 0);
});
});
describe('setUserProperties', function() {
beforeEach(function() {
amplitude.init(apiKey);
});
afterEach(function() {
reset();
});
it('should log identify call from set user properties', function() {
assert.equal(amplitude._unsentCount(), 0);
amplitude.setUserProperties({'prop': true, 'key': 'value'});
assert.lengthOf(amplitude._unsentEvents, 0);
assert.lengthOf(amplitude._unsentIdentifys, 1);
assert.equal(amplitude._unsentCount(), 1);
assert.lengthOf(server.requests, 1);
var events = JSON.parse(queryString.parse(server.requests[0].requestBody).e);
assert.lengthOf(events, 1);
assert.equal(events[0].event_type, '$identify');
assert.deepEqual(events[0].event_properties, {});
var expected = {
'$set': {
'prop': true,
'key': 'value'
}
};
assert.deepEqual(events[0].user_properties, expected);
});
});
describe('clearUserProperties', function() {
beforeEach(function() {
amplitude.init(apiKey);
});
afterEach(function() {
reset();
});
it('should log identify call from clear user properties', function() {
assert.equal(amplitude._unsentCount(), 0);
amplitude.clearUserProperties();
assert.lengthOf(amplitude._unsentEvents, 0);
assert.lengthOf(amplitude._unsentIdentifys, 1);
assert.equal(amplitude._unsentCount(), 1);
assert.lengthOf(server.requests, 1);
var events = JSON.parse(queryString.parse(server.requests[0].requestBody).e);
assert.lengthOf(events, 1);
assert.equal(events[0].event_type, '$identify');
assert.deepEqual(events[0].event_properties, {});
var expected = {
'$clearAll': '-'
};
assert.deepEqual(events[0].user_properties, expected);
});
});
describe('setGroup', function() {
beforeEach(function() {
reset();
amplitude.init(apiKey);
});
afterEach(function() {
reset();
});
it('should generate an identify event with groups set', function() {
amplitude.setGroup('orgId', 15);
assert.lengthOf(server.requests, 1);
var events = JSON.parse(queryString.parse(server.requests[0].requestBody).e);
assert.lengthOf(events, 1);
// verify identify event
var identify = events[0];
assert.equal(identify.event_type, '$identify');
assert.deepEqual(identify.user_properties, {
'$set': {'orgId': 15},
});
assert.deepEqual(identify.event_properties, {});
assert.deepEqual(identify.groups, {
'orgId': '15',
});
});
it('should ignore empty string groupTypes', function() {
amplitude.setGroup('', 15);
assert.lengthOf(server.requests, 0);
});
it('should ignore non-string groupTypes', function() {
amplitude.setGroup(10, 10);
amplitude.setGroup([], 15);
amplitude.setGroup({}, 20);
amplitude.setGroup(true, false);
assert.lengthOf(server.requests, 0);
});
});
describe('setVersionName', function() {
beforeEach(function() {
reset();
});
afterEach(function() {
reset();
});
it('should set version name', function() {
amplitude.init(apiKey, null, {batchEvents: true});
amplitude.setVersionName('testVersionName1');
amplitude.logEvent('testEvent1');
assert.equal(amplitude._unsentEvents[0].event.version_name, 'testVersionName1');
// should ignore non-string values
amplitude.setVersionName(15000);
amplitude.logEvent('testEvent2');
assert.equal(amplitude._unsentEvents[1].event.version_name, 'testVersionName1');
});
});
describe('regenerateDeviceId', function() {
beforeEach(function() {
reset();
});
afterEach(function() {
reset();
});
it('should regenerate the deviceId', function() {
var deviceId = 'oldDeviceId';
amplitude.init(apiKey, null, {'deviceId': deviceId});
amplitude.regenerateDeviceId();
assert.notEqual(amplitude.options.deviceId, deviceId);
assert.lengthOf(amplitude.options.deviceId, 22);
});
});
describe('setDeviceId', function() {
beforeEach(function() {
reset();
});
afterEach(function() {
reset();
});
it('should change device id', function() {
amplitude.init(apiKey, null, {'deviceId': 'fakeDeviceId'});
amplitude.setDeviceId('deviceId');
assert.equal(amplitude.options.deviceId, 'deviceId');
});
it('should not change device id if empty', function() {
amplitude.init(apiKey, null, {'deviceId': 'deviceId'});
amplitude.setDeviceId('');
assert.notEqual(amplitude.options.deviceId, '');
assert.equal(amplitude.options.deviceId, 'deviceId');
});
it('should not change device id if null', function() {
amplitude.init(apiKey, null, {'deviceId': 'deviceId'});
amplitude.setDeviceId(null);
assert.notEqual(amplitude.options.deviceId, null);
assert.equal(amplitude.options.deviceId, 'deviceId');
});
it('should store device id in cookie', function() {
amplitude.init(apiKey, null, {'deviceId': 'fakeDeviceId'});
amplitude.setDeviceId('deviceId');
var stored = amplitude._metadataStorage.load();
assert.propertyVal(stored, 'deviceId', 'deviceId');
});
});
describe('resetSessionId', function() {
let clock;
beforeEach(function() {
clock = sinon.useFakeTimers();
});
afterEach(function() {
reset();
clock.restore();
});
it('should reset the session Id', function() {
clock.tick(10);
amplitude.init(apiKey);
clock.tick(100);
amplitude.resetSessionId();
clock.tick(200);
assert.equal(amplitude._sessionId, 110);
});
});
describe('identify', function() {
let clock;
beforeEach(function() {
clock = sinon.useFakeTimers();
amplitude.init(apiKey);
});
afterEach(function() {
reset();
clock.restore();