-
Notifications
You must be signed in to change notification settings - Fork 101
/
6_branch.js
2032 lines (1907 loc) · 70 KB
/
6_branch.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
/***
* This file provides the main Branch function.
*/
'use strict';
goog.provide('Branch');
goog.require('goog.json'); // jshint unused:false
goog.require('utils');
goog.require('resources');
goog.require('Server');
goog.require('banner');
goog.require('task_queue');
goog.require('storage');
goog.require('session');
goog.require('config');
goog.require('safejson');
goog.require('branch_view');
goog.require('journeys_utils');
/*globals Ti, BranchStorage, require */
var default_branch;
/**
* Enum for what parameters are in a wrapped Branch method
* @enum {number}
*/
var callback_params = {
NO_CALLBACK: 0,
CALLBACK_ERR: 1,
CALLBACK_ERR_DATA: 2
};
/**
* Enum for the initialization state of the Branch Object
* @enum {number}
*/
var init_states = {
NO_INIT: 0,
INIT_PENDING: 1,
INIT_FAILED: 2,
INIT_SUCCEEDED: 3
};
/**
* Enum for the initialization state of the Branch Object
* @enum {number}
*/
var init_state_fail_codes = {
NO_FAILURE: 0,
UNKNOWN_CAUSE: 1,
OPEN_FAILED: 2,
BFP_NOT_FOUND: 3,
HAS_APP_FAILED: 4
};
/***
* @param {number} parameters
* @param {function(...?): undefined} func
* @param {boolean=} init
*/
var wrap = function(parameters, func, init) {
var r = function() {
var self = this;
var args;
var callback;
var lastArg = arguments[arguments.length - 1];
if (parameters === callback_params.NO_CALLBACK || typeof lastArg !== 'function') {
callback = function(err) {
return;
};
args = Array.prototype.slice.call(arguments);
}
else {
args = Array.prototype.slice.call(arguments, 0, arguments.length - 1) || [];
callback = lastArg;
}
self._queue(function(next) {
/***
* @type {function(?Error,?): undefined}
*/
var done = function(err, data) {
try {
if (err && parameters === callback_params.NO_CALLBACK) {
throw err;
}
else if (parameters === callback_params.CALLBACK_ERR) {
callback(err);
}
else if (parameters === callback_params.CALLBACK_ERR_DATA) {
callback(err, data);
}
}
finally {
// ...but we always want to call next
next();
}
};
if (!init) {
if (self.init_state === init_states.INIT_PENDING) {
return done(new Error(utils.message(utils.messages.initPending)), null);
}
else if (self.init_state === init_states.INIT_FAILED) {
return done(new Error(utils.message(utils.messages.initFailed, self.init_state_fail_code, self.init_state_fail_details)), null);
}
else if (self.init_state === init_states.NO_INIT || !self.init_state) {
return done(new Error(utils.message(utils.messages.nonInit)), null);
}
}
args.unshift(done);
func.apply(self, args);
});
};
return r;
};
/***
* @class Branch
* @constructor
*/
Branch = function() {
if (!(this instanceof Branch)) {
if (!default_branch) {
default_branch = new Branch();
}
return default_branch;
}
this._queue = task_queue();
var storageMethods = [ 'session', 'cookie', 'pojo' ];
this._storage = /** @type {storage} */ (new storage.BranchStorage(storageMethods)); // jshint ignore:line
this._server = new Server();
var sdk = 'web';
/** @type {Array<utils.listener>} */
this._listeners = [ ];
this.sdk = sdk + config.version;
this.requestMetadata = {};
this.init_state = init_states.NO_INIT;
this.init_state_fail_code = init_state_fail_codes.NO_FAILURE;
this.init_state_fail_details = null;
};
/***
* @param {utils.resource} resource
* @param {Object.<string, *>} obj
* @param {function(?Error,?)=} callback
*/
Branch.prototype._api = function(resource, obj, callback) {
if (this.app_id) {
obj['app_id'] = this.app_id;
}
if (this.branch_key) {
obj['branch_key'] = this.branch_key;
}
if (((resource.params && resource.params['session_id']) ||
(resource.queryPart && resource.queryPart['session_id'])) &&
this.session_id) {
obj['session_id'] = this.session_id;
}
if (((resource.params && resource.params['identity_id']) ||
(resource.queryPart && resource.queryPart['identity_id'])) &&
this.identity_id) {
obj['identity_id'] = this.identity_id;
}
if (resource.endpoint.indexOf("/v1/") < 0) {
if (((resource.params && resource.params['developer_identity']) ||
(resource.queryPart && resource.queryPart['developer_identity'])) &&
this.identity) {
obj['developer_identity'] = this.identity;
}
}
else {
if (((resource.params && resource.params['identity']) ||
(resource.queryPart && resource.queryPart['identity'])) &&
this.identity) {
obj['identity'] = this.identity;
}
}
if (((resource.params && resource.params['link_click_id']) ||
(resource.queryPart && resource.queryPart['link_click_id'])) &&
this.link_click_id) {
obj['link_click_id'] = this.link_click_id;
}
if (((resource.params && resource.params['sdk']) ||
(resource.queryPart && resource.queryPart['sdk'])) && this.sdk) {
obj['sdk'] = this.sdk;
}
if (((resource.params && resource.params['browser_fingerprint_id']) ||
(resource.queryPart && resource.queryPart['browser_fingerprint_id'])) &&
this.browser_fingerprint_id) {
obj['browser_fingerprint_id'] = this.browser_fingerprint_id;
}
// Adds tracking_disabled to every post request when enabled
if (utils.userPreferences.trackingDisabled) {
obj['tracking_disabled'] = utils.userPreferences.trackingDisabled;
}
if (this.requestMetadata) {
for (var metadata_key in this.requestMetadata) {
if (this.requestMetadata.hasOwnProperty(metadata_key)) {
if (!obj["branch_requestMetadata"]) {
obj["branch_requestMetadata"] = {};
}
obj["branch_requestMetadata"][metadata_key] = this.requestMetadata[metadata_key];
}
}
}
if (utils.shouldAddDMAParams(resource.endpoint)) {
var dmaData = this._storage.get('branch_dma_data', true);
obj["branch_dma_data"] = dmaData ? safejson.parse(dmaData) : null;
}
if (resource.endpoint !== '/_r') {
resource.destination = config.api_endpoint;
}
return this._server.request(resource, obj, this._storage, function(err, data) {
callback(err, data);
});
};
/***
* @function Branch._referringLink
*/
Branch.prototype._referringLink = function(forJourneys) {
var sessionData = session.get(this._storage);
var referringLink = sessionData && sessionData['referring_link'];
if (referringLink) {
return referringLink;
}
else {
if (utils.userPreferences.enableExtendedJourneysAssist && forJourneys) {
var localStorageData = session.get(this._storage, true);
var referring_Link = localStorageData && localStorageData['referring_link'];
var referringLinkExpiry = localStorageData && localStorageData['referringLinkExpiry'];
if (referring_Link && referringLinkExpiry) {
var now = new Date();
// compare the expiry time of the item with the current time
if (now.getTime() > referringLinkExpiry) {
session.patch(this._storage, { "referringLinkExpiry": null }, true, true);
}
else {
return referring_Link;
}
}
}
}
var clickId = this._storage.get('click_id');
if (clickId) {
return config.link_service_endpoint + '/c/' + clickId;
}
return null;
};
/***
* @function Branch._publishEvent
* @param {string} event
* @param {Object} data - _optional_ - data to pass into listener callback.
*/
Branch.prototype._publishEvent = function(event, data) {
for (var i = 0; i < this._listeners.length; i++) {
if (!this._listeners[i].event || this._listeners[i].event === event) {
this._listeners[i].listener(event, data);
}
}
};
/**
* @function Branch.init
* @param {string} branch_key - _required_ - Your Branch [live key](http://dashboard.branch.io/settings), or (deprecated) your app id.
* @param {Object=} options - _optional_ - { }.
* @param {function(?Error, utils.sessionData=)=} callback - _optional_ - callback to read the
* session data.
*
* Adding the Branch script to your page automatically creates a window.branch
* object with all the external methods described below. All calls made to
* Branch methods are stored in a queue, so even if the SDK is not fully
* instantiated, calls made to it will be queued in the order they were
* originally called.
* If the session was opened from a referring link, `data()` will also return the referring link
* click as `referring_link`, which gives you the ability to continue the click flow.
*
* The init function on the Branch object initiates the Branch session and
* creates a new user session, if it doesn't already exist, in
* `sessionStorage`.
*
* **Useful Tip**: The init function returns a data object where you can read
* the link the user was referred by.
*
* Properties available in the options object:
*
* | Key | Value
* | --- | ---
* | branch_match_id | *optional* - `string`. The current user's browser-fingerprint-id. The value of this parameter should be the same as the value of ?_branch_match_id (automatically appended by Branch after a link click). _Only necessary if ?_branch_match_id is lost due to multiple redirects in your flow_.
* | branch_view_id | *optional* - `string`. If you would like to test how Journeys render on your page before activating them, you can set the value of this parameter to the id of the view you are testing. _Only necessary when testing a view related to a Journey_.
* | no_journeys | *optional* - `boolean`. When true, prevents Journeys from appearing on current page.
* | disable_entry_animation | *optional* - `boolean`. When true, prevents a Journeys entry animation.
* | disable_exit_animation | *optional* - `boolean`. When true, prevents a Journeys exit animation.
* | retries | *optional* - `integer`. Value specifying the number of times that a Branch API call can be re-attempted. Default 2.
* | retry_delay | *optional* - `integer `. Amount of time in milliseconds to wait before re-attempting a timed-out request to the Branch API. Default 200 ms.
* | timeout | *optional* - `integer`. Duration in milliseconds that the system should wait for a response before considering any Branch API call to have timed out. Default 5000 ms.
* | metadata | *optional* - `object`. Key-value pairs used to target Journeys users via the "is viewing a page with metadata key" filter.
* | nonce | *optional* - `string`. A nonce value that will be added to branch-journey-cta injected script. Used to allow that script from a Content Security Policy.
* | tracking_disabled | *optional* - `boolean`. true disables tracking
*
* ##### Usage
* ```js
* branch.init(
* branch_key,
* options,
* callback (err, data),
* );
* ```
*
* ##### Callback Format
* ```js
* callback(
* "Error message",
* {
* data_parsed: { }, // If the user was referred from a link, and the link has associated data, the data is passed in here.
* referring_identity: '12345', // If the user was referred from a link, and the link was created by a user with an identity, that identity is here.
* has_app: true, // Does the user have the app installed already?
* identity: 'BranchUser', // Unique string that identifies the user
* ~referring_link: 'https://bnc.lt/c/jgg75-Gjd3' // The referring link click, if available.
* }
* );
* ```
*
* **Note:** `Branch.init` must be called prior to calling any other Branch functions.
* ___
*/
/*** +TOC_HEADING &Branch Session& ^ALL ***/
/*** +TOC_ITEM #initbranch_key-options-callback &.init()& ^ALL ***/
Branch.prototype['init'] = wrap(
callback_params.CALLBACK_ERR_DATA,
function(done, branch_key, options) {
if (utils.navigationTimingAPIEnabled) {
utils.instrumentation['init-began-at'] = utils.timeSinceNavigationStart();
}
var self = this;
self.init_state = init_states.INIT_PENDING;
if (utils.isKey(branch_key)) {
self.branch_key = branch_key;
}
else {
self.app_id = branch_key;
}
options = options && utils.validateParameterType(options, 'object') ? options : { };
self.init_options = options;
utils.retries = options && options['retries'] && Number.isInteger(options['retries']) ? options['retries'] : utils.retries;
utils.retry_delay = options && options['retry_delay'] && Number.isInteger(options['retry_delay']) ? options['retry_delay'] : utils.retry_delay;
utils.timeout = options && options['timeout'] && Number.isInteger(options['timeout']) ? options['timeout'] : utils.timeout;
utils.nonce = options && options['nonce'] ? options['nonce'] : utils.nonce;
utils.debug = options && options['enableLogging'] ? options['enableLogging'] : utils.debug;
utils.userPreferences.trackingDisabled = options && options['tracking_disabled'] && options['tracking_disabled'] === true ? true : false;
utils.userPreferences.enableExtendedJourneysAssist = options && options['enableExtendedJourneysAssist'] ? options['enableExtendedJourneysAssist'] : utils.userPreferences.enableExtendedJourneysAssist;
utils.extendedJourneysAssistExpiryTime = options && options['extendedJourneysAssistExpiryTime'] && Number.isInteger(options['extendedJourneysAssistExpiryTime']) ? options['extendedJourneysAssistExpiryTime'] : utils.extendedJourneysAssistExpiryTime;
utils.userPreferences.allowErrorsInCallback = false;
utils.getClientHints();
if (utils.userPreferences.trackingDisabled) {
utils.cleanApplicationAndSessionStorage(self);
}
// initialize identity_id from storage
// note the previous line scrubs this if tracking disabled.
var localData = session.get(self._storage, true);
self.identity_id = localData && localData['identity_id'];
var setBranchValues = function(data) {
if (data['link_click_id']) {
self.link_click_id = data['link_click_id'].toString();
}
if (data['session_link_click_id']) {
self.session_link_click_id = data['session_link_click_id'].toString();
}
if (data['session_id']) {
self.session_id = data['session_id'].toString();
}
if (data['identity_id']) {
self.identity_id = data['identity_id'].toString();
}
if (data['identity']) {
self.identity = data['identity'].toString();
}
if (data['link']) {
self.sessionLink = data['link'];
}
if (data['referring_link']) {
data['referring_link'] = utils.processReferringLink(data['referring_link']);
}
if (!data['click_id'] && data['referring_link']) {
data['click_id'] = utils.getClickIdAndSearchStringFromLink(data['referring_link']);
}
self.browser_fingerprint_id = data['browser_fingerprint_id'];
return data;
};
var sessionData = session.get(self._storage);
var branchMatchIdFromOptions = (options && typeof options['branch_match_id'] !== 'undefined' && options['branch_match_id'] !== null) ?
options['branch_match_id'] :
null;
var link_identifier = (branchMatchIdFromOptions || utils.getParamValue('_branch_match_id') || utils.hashValue('r'));
var freshInstall = !self.identity_id; // initialized from local storage above
self._branchViewEnabled = !!self._storage.get('branch_view_enabled');
var fetchLatestBrowserFingerPrintID = function(cb) {
var params_r = { "sdk": config.version, "branch_key": self.branch_key };
var currentSessionData = session.get(self._storage) || {};
var permData = session.get(self._storage, true) || {};
if (permData['browser_fingerprint_id']) {
params_r['_t'] = permData['browser_fingerprint_id'];
}
if (!utils.isSafari11OrGreater() && !utils.isIOSWKWebView()) {
self._api(
resources._r,
params_r,
function(err, browser_fingerprint_id) {
if (err) {
self.init_state_fail_code = init_state_fail_codes.BFP_NOT_FOUND;
self.init_state_fail_details = err.message;
}
if (browser_fingerprint_id) {
currentSessionData['browser_fingerprint_id'] = browser_fingerprint_id;
}
}
);
}
if (cb) {
cb(null, currentSessionData);
}
};
var restoreIdentityOnInstall = function(data) {
if (freshInstall) {
data["identity"] = self.identity;
}
return data;
};
var finishInit = function(err, data) {
if (data) {
data = setBranchValues(data);
if (!utils.userPreferences.trackingDisabled) {
data = restoreIdentityOnInstall(data);
session.set(self._storage, data, freshInstall);
}
self.init_state = init_states.INIT_SUCCEEDED;
data['data_parsed'] = data['data'] && data['data'].length !== 0 ? safejson.parse(data['data']) : {};
}
if (err) {
self.init_state = init_states.INIT_FAILED;
if (!self.init_state_fail_code) {
self.init_state_fail_code = init_state_fail_codes.UNKNOWN_CAUSE;
self.init_state_fail_details = err.message;
}
return done(err, data && utils.whiteListSessionData(data));
}
try {
done(err, data && utils.whiteListSessionData(data));
}
catch (e) {
// pass
}
finally {
self['renderFinalize']();
}
var additionalMetadata = utils.getAdditionalMetadata();
var metadata = utils.validateParameterType(options['metadata'], "object") ? options['metadata'] : null;
if (metadata) {
var hostedDeeplinkDataWithMergedMetadata = utils.mergeHostedDeeplinkData(additionalMetadata['hosted_deeplink_data'], metadata);
if (hostedDeeplinkDataWithMergedMetadata && Object.keys(hostedDeeplinkDataWithMergedMetadata).length > 0) {
additionalMetadata['hosted_deeplink_data'] = hostedDeeplinkDataWithMergedMetadata;
}
}
var requestData = branch_view._getPageviewRequestData(
journeys_utils._getPageviewMetadata(options, additionalMetadata),
options,
self,
false
);
self['renderQueue'](function() {
self._api(
resources.pageview,
requestData,
function(err, pageviewResponse) {
if (!err && typeof pageviewResponse === "object") {
var journeyInTestMode = requestData['branch_view_id'] ? true : false;
if (branch_view.shouldDisplayJourney(
pageviewResponse,
options,
journeyInTestMode
)
) {
branch_view.displayJourney(
pageviewResponse['template'],
requestData,
requestData['branch_view_id'] || pageviewResponse['event_data']['branch_view_data']['id'],
pageviewResponse['event_data']['branch_view_data'],
journeyInTestMode,
pageviewResponse['journey_link_data']
);
}
else {
if (pageviewResponse['auto_branchify'] || (!branchMatchIdFromOptions && utils.getParamValue('branchify_url') && self._referringLink())) {
var linkOptions = {
'make_new_link': false,
'open_app': true,
'auto_branchify': true
};
this['branch']['deepview']({}, linkOptions);
}
journeys_utils.branch._publishEvent('willNotShowJourney');
}
}
if (utils.userPreferences.trackingDisabled) {
utils.userPreferences.allowErrorsInCallback = true;
}
}
);
});
};
var attachVisibilityEvent = function() {
var hidden;
var changeEvent;
if (typeof document.hidden !== 'undefined') {
hidden = 'hidden';
changeEvent = 'visibilitychange';
}
else if (typeof document.mozHidden !== 'undefined') {
hidden = 'mozHidden';
changeEvent = 'mozvisibilitychange';
}
else if (typeof document.msHidden !== 'undefined') {
hidden = 'msHidden';
changeEvent = 'msvisibilitychange';
}
else if (typeof document.webkitHidden !== 'undefined') {
hidden = 'webkitHidden';
changeEvent = 'webkitvisibilitychange';
}
if (changeEvent) {
// Ensures that we add a change-event-listener exactly once in-case re-initialization occurs through branch.trackingDisabled(false)
if (!self.changeEventListenerAdded) {
self.changeEventListenerAdded = true;
document.addEventListener(changeEvent, function() {
if (!document[hidden]) {
fetchLatestBrowserFingerPrintID(null);
if (typeof self._deepviewRequestForReplay === 'function') {
self._deepviewRequestForReplay();
}
}
}, false);
}
}
};
if (sessionData && sessionData['session_id'] && !link_identifier && !utils.getParamValue('branchify_url')) {
// resets data in session storage to prevent previous link click data from being returned to Branch.init()
session.update(self._storage, { "data": "" });
session.update(self._storage, { "referring_link": "" });
attachVisibilityEvent();
fetchLatestBrowserFingerPrintID(finishInit);
return;
}
var params_r = { "sdk": config.version, "branch_key": self.branch_key };
var permData = session.get(self._storage, true) || {};
if (permData['browser_fingerprint_id']) {
params_r['_t'] = permData['browser_fingerprint_id'];
}
if (permData['identity']) {
self.identity = permData['identity'];
}
// Execute the /v1/open right away or after _open_delay_ms.
var open_delay = parseInt(utils.getParamValue('[?&]_open_delay_ms'), 10);
if (!utils.isSafari11OrGreater() && !utils.isIOSWKWebView()) {
self._api(
resources._r,
params_r,
function(err, browser_fingerprint_id) {
if (err) {
self.init_state_fail_code = init_state_fail_codes.BFP_NOT_FOUND;
self.init_state_fail_details = err.message;
return finishInit(err, null);
}
utils.delay(function() {
self._api(
resources.open,
{
"link_identifier": link_identifier,
"browser_fingerprint_id": link_identifier || browser_fingerprint_id,
"identity": permData['identity'] ? permData['identity'] : null,
"alternative_browser_fingerprint_id": permData['browser_fingerprint_id'],
"options": options,
"initial_referrer": utils.getInitialReferrer(self._referringLink()),
"current_url": utils.getCurrentUrl(),
"screen_height": utils.getScreenHeight(),
"screen_width": utils.getScreenWidth(),
"model": utils.userAgentData ? utils.userAgentData.model : null,
"os_version": utils.userAgentData ? utils.userAgentData.platformVersion : null
},
function(err, data) {
if (err) {
self.init_state_fail_code = init_state_fail_codes.OPEN_FAILED;
self.init_state_fail_details = err.message;
}
if (!err && typeof data === 'object') {
if (data['branch_view_enabled']) {
self._branchViewEnabled = !!data['branch_view_enabled'];
self._storage.set('branch_view_enabled', self._branchViewEnabled);
}
if (link_identifier) {
data['click_id'] = link_identifier;
}
}
attachVisibilityEvent();
finishInit(err, data);
}
);
}, open_delay);
}
);
}
else {
utils.delay(function() {
self._api(
resources.open,
{
"link_identifier": link_identifier,
"browser_fingerprint_id": link_identifier || permData['browser_fingerprint_id'],
"identity": permData['identity'] ? permData['identity'] : null,
"alternative_browser_fingerprint_id": permData['browser_fingerprint_id'],
"options": options,
"initial_referrer": utils.getInitialReferrer(self._referringLink()),
"current_url": utils.getCurrentUrl(),
"screen_height": utils.getScreenHeight(),
"screen_width": utils.getScreenWidth(),
"model": utils.userAgentData ? utils.userAgentData.model : null,
"os_version": utils.userAgentData ? utils.userAgentData.platformVersion : null
},
function(err, data) {
if (err) {
self.init_state_fail_code = init_state_fail_codes.OPEN_FAILED;
self.init_state_fail_details = err.message;
}
if (!err && typeof data === 'object') {
if (data['branch_view_enabled']) {
self._branchViewEnabled = !!data['branch_view_enabled'];
self._storage.set('branch_view_enabled', self._branchViewEnabled);
}
if (link_identifier) {
data['click_id'] = link_identifier;
}
}
attachVisibilityEvent();
finishInit(err, data);
}
);
}, open_delay);
}
},
true
);
/**
* currently private method, which may be opened to the public in the future
*/
Branch.prototype['renderQueue'] = wrap(callback_params.NO_CALLBACK, function(done, render) {
var self = this;
if (self._renderFinalized) {
render();
}
else {
self._renderQueue = self._renderQueue || [];
self._renderQueue.push(render);
}
done(null, null);
});
/**
* currently private method, which may be opened to the public in the future
*/
Branch.prototype['renderFinalize'] = wrap(callback_params.CALLBACK_ERR_DATA, function(done) {
var self = this;
if (self._renderQueue && self._renderQueue.length > 0) {
self._renderQueue.forEach(function(callback) {
callback.call(this);
});
delete self._renderQueue;
}
self._renderFinalized = true;
done(null, null);
});
/**
* @function Branch.data
* @param {function(?Error, utils.sessionData=)=} callback - _optional_ - callback to read the
* session data.
*
* Returns the same session information and any referring data, as
* `Branch.init`, but does not require the `app_id`. This is meant to be called
* after `Branch.init` has been called if you need the session information at a
* later point.
* If the Branch session has already been initialized, the callback will return
* immediately, otherwise, it will return once Branch has been initialized.
* ___
*/
/*** +TOC_ITEM #datacallback &.data()& ^ALL ***/
Branch.prototype['data'] = wrap(callback_params.CALLBACK_ERR_DATA, function(done) {
var data = utils.whiteListSessionData(session.get(this._storage));
data['referring_link'] = this._referringLink();
data['data_parsed'] = data['data'] && data['data'].length !== 0 ? safejson.parse(data['data']) : {};
done(null, data);
});
/**
* @function Branch.first
* @param {function(?Error, utils.sessionData=)=} callback - _optional_ - callback to read the
* session data.
*
* Returns the same session information and any referring data, as
* `Branch.init` did when the app was first installed. This is meant to be called
* after `Branch.init` has been called if you need the first session information at a
* later point.
* If the Branch session has already been initialized, the callback will return
* immediately, otherwise, it will return once Branch has been initialized.
*
* ___
*
*/
/*** +TOC_ITEM #firstcallback &.first()& ^ALL ***/
Branch.prototype['first'] = wrap(callback_params.CALLBACK_ERR_DATA, function(done) {
done(null, utils.whiteListSessionData(session.get(this._storage, true)));
});
/**
* @function Branch.setIdentity
* @param {string} identity - _required_ - a string uniquely identifying the user - often a user ID
* or email address.
* @param {function(?Error, Object=)=} callback - _optional_ - callback that returns the user's
* Branch identity id and unique link.
*
* **[Formerly `identify()`](CHANGELOG.md)**
*
* Sets the identity of a user and returns the data. To use this function, pass
* a unique string that identifies the user - this could be an email address,
* UUID, Facebook ID, etc.
*
* ##### Usage
* ```js
* branch.setIdentity(
* identity,
* callback (err, data)
* );
* ```
*
* ##### Callback Format
* ```js
* callback(
* "Error message",
* {
* identity_id: '12345', // Server-generated ID of the user identity, stored in `sessionStorage`.
* link: 'url', // New link to use (replaces old stored link), stored in `sessionStorage`.
* referring_data_parsed: { }, // Returns the initial referring data for this identity, if exists, as a parsed object.
* referring_identity: '12345' // Returns the initial referring identity for this identity, if exists.
* }
* );
* ```
* ___
*/
/*** +TOC_ITEM #setidentityidentity-callback &.setIdentity()& ^ALL ***/
Branch.prototype['setIdentity'] = wrap(callback_params.CALLBACK_ERR_DATA, function(done, identity) {
var self = this;
if (identity) {
var data = {
identity_id: self.identity_id,
session_id: self.session_id,
link: self.sessionLink,
developer_identity: identity
};
self.identity = identity;
// store the identity
session.patch(self._storage, { "identity": identity }, true);
done(null, data);
}
else {
done(new Error(utils.message(utils.messages.missingIdentity)));
}
});
/**
* @function Branch.logout
* @param {function(?Error)=} callback - _optional_
*
* Logs out the current session, replaces session IDs and identity IDs.
*
* ##### Usage
* ```js
* branch.logout(
* callback (err)
* );
* ```
*
* ##### Callback Format
* ```js
* callback(
* "Error message"
* );
* ```
* ___
*
*/
/*** +TOC_ITEM #logoutcallback &.logout()& ^ALL ***/
Branch.prototype['logout'] = wrap(callback_params.CALLBACK_ERR, function(done) {
var self = this;
var data = {
"identity": null
};
self.identity = null;
// make sure to update both session and local. removeNull = true deletes, in particular,
// identity instead of inserting null in storage.
session.patch(self._storage, data, /* updateLocalStorage */ true, /* removeNull */ true);
done(null);
});
Branch.prototype['getBrowserFingerprintId'] = wrap(callback_params.CALLBACK_ERR_DATA, function(done) {
var permData = session.get(this._storage, true) || {};
done(null, permData['browser_fingerprint_id'] || null);
});
/**
* @function Branch.crossPlatformIds
* @param {function(?Error, Object=)=} callback - _optional_ - callback to read CPIDs
*
* Returns CPIDs for current user.
*
* ##### Usage
* ```js
* branch.crossPlatformIds(
* callback (err, data)
* );
* ```
* ___
*
*/
/*** +TOC_ITEM #crossPlatformIdscallback &.crossPlatformIds()& ^ALL ***/
Branch.prototype['crossPlatformIds'] = wrap(callback_params.CALLBACK_ERR_DATA, function(done) {
this._api(
resources.crossPlatformIds,
{
"user_data": safejson.stringify(utils.getUserData(this))
},
function(err, data) {
return done(err || null, data && data['user_data'] || null);
}
);
});
/**
* @function Branch.lastAttributedTouchData
* @param {number} attribution_window - the number of days to look up attribution data for
* @param {function(?Error, Object=)=} callback - _optional_ - callback to read last attributed touch data
*
* Returns last attributed touch data for current user. Last attributed touch data has the information associated with that user's last viewed impression or clicked link.
*
* ##### Usage
* ```js
* branch.lastAttributedTouchData(
* attribution_window,
* callback (err, data)
* );
* ```
* ___
*
*/
/*** +TOC_ITEM #lastAttributedTouchDataattribution_window-callback &.lastAttributedTouchData()& ^ALL ***/
Branch.prototype['lastAttributedTouchData'] = wrap(callback_params.CALLBACK_ERR_DATA, function(done, attribution_window) {
attribution_window = utils.validateParameterType(attribution_window, 'number') ? attribution_window : null;
var userData = utils.getUserData(this);
utils.addPropertyIfNotNull(userData, 'attribution_window', attribution_window);
this._api(
resources.lastAttributedTouchData,
{
"user_data": safejson.stringify(userData)
},
function(err, data) {
return done(err || null, data || null);
}
);
});
/**
* @function Branch.track
* @param {string} event - _required_ - name of the event to be tracked.
* @param {Object=} metadata - _optional_ - object of event metadata.
* @param {function(?Error)=} callback - _optional_
*
* This function allows you to track any event with supporting metadata.
* The `metadata` parameter is a formatted JSON object that can contain
* any data and has limitless hierarchy
*
* ##### Usage
* ```js
* branch.track(
* event,
* metadata,
* callback (err)
* );
* ```
*
* ##### Callback Format
* ```js
* callback("Error message");
* ```
* ___
*/
/*** +TOC_HEADING &Event Tracking& ^ALL ***/
/*** +TOC_ITEM #trackevent-metadata-callback &.track()& ^ALL ***/
Branch.prototype['track'] = wrap(callback_params.CALLBACK_ERR, function(done, event, metadata, options) {
var self = this;
metadata = metadata || {};
options = options || {};
utils.nonce = options['nonce'] ? options['nonce'] : utils.nonce;
if (event === "pageview") {
var hostedDeeplinkDataWithMergedMetadata = utils.mergeHostedDeeplinkData(utils.getHostedDeepLinkData(), metadata);
if (hostedDeeplinkDataWithMergedMetadata && Object.keys(hostedDeeplinkDataWithMergedMetadata).length > 0) {
metadata['hosted_deeplink_data'] = hostedDeeplinkDataWithMergedMetadata;
}
var requestData = branch_view._getPageviewRequestData(
journeys_utils._getPageviewMetadata(options, metadata),
options,
self,
false
);
self._api(resources.pageview,
requestData,
function(err, pageviewResponse) {
if (!err && typeof pageviewResponse === "object") {
var journeyInTestMode = requestData['branch_view_id'] ? true : false;
if (branch_view.shouldDisplayJourney
(
pageviewResponse,
options,
journeyInTestMode
)
) {
branch_view.displayJourney(
pageviewResponse['template'],
requestData,
requestData['branch_view_id'] || pageviewResponse['event_data']['branch_view_data']['id'],
pageviewResponse['event_data']['branch_view_data'],
journeyInTestMode,
pageviewResponse['journey_link_data']
);
}
else {
journeys_utils.branch._publishEvent('willNotShowJourney');