-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathmp-instance.ts
More file actions
1603 lines (1487 loc) · 58.1 KB
/
Copy pathmp-instance.ts
File metadata and controls
1603 lines (1487 loc) · 58.1 KB
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
//
// Copyright 2017 mParticle, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Uses portions of code from jQuery
// jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
import { EventType, IdentityType, CommerceEventType, PromotionActionType, ProductActionType, MessageType } from './types';
import Constants, { VaultKind } from './constants';
import APIClient, { IAPIClient } from './apiClient';
import Helpers from './helpers';
import NativeSdkHelpers from './nativeSdkHelpers';
import CookieSyncManager, { ICookieSyncManager } from './cookieSyncManager';
import SessionManager, { ISessionManager } from './sessionManager';
import Ecommerce from './ecommerce';
import Store, { IStore } from './store';
import Logger from './logger';
import Persistence from './persistence';
import Events from './events';
import Forwarders from './forwarders';
import ServerModel, { IServerModel } from './serverModel';
import ForwardingStatsUploader from './forwardingStatsUploader';
import Identity from './identity';
import Consent, { IConsent } from './consent';
import KitBlocker from './kitBlocking';
import ConfigAPIClient, { IKitConfigs } from './configAPIClient';
import IdentityAPIClient from './identityApiClient';
import { isFunction, parseConfig } from './utils';
import { createVault } from './vault';
import { removeExpiredIdentityCacheDates } from './identity-utils';
import IntegrationCapture from './integrationCapture';
import { IPreInit, processReadyQueue } from './pre-init-utils';
import { BaseEvent, MParticleWebSDK, SDKHelpersApi } from './sdkRuntimeModels';
import { Dictionary, SDKEventAttrs } from '@mparticle/web-sdk';
import { IIdentity } from './identity.interfaces';
import { IEvents } from './events.interfaces';
import { IECommerce } from './ecommerce.interfaces';
import { INativeSdkHelpers } from './nativeSdkHelpers.interfaces';
import { IPersistence } from './persistence.interfaces';
import ForegroundTimer from './foregroundTimeTracker';
import RoktManager, { IRoktOptions } from './roktManager';
import filteredMparticleUser from './filteredMparticleUser';
export interface IErrorLogMessage {
message?: string;
name?: string;
stack?: string;
}
export interface IErrorLogMessageMinified {
m?: string;
s?: string;
t?: string;
}
export type IntegrationDelays = Dictionary<boolean>;
// https://go.mparticle.com/work/SQDSDKS-6949
export interface IMParticleWebSDKInstance extends MParticleWebSDK {
// Private Properties
_APIClient: IAPIClient;
_Consent: IConsent;
_CookieSyncManager: ICookieSyncManager;
_Ecommerce: IECommerce;
_Events: IEvents;
_Forwarders: any; // https://go.mparticle.com/work/SQDSDKS-5767
_ForwardingStatsUploader: ForwardingStatsUploader;
_Helpers: SDKHelpersApi;
_Identity: IIdentity;
_IdentityAPIClient: typeof IdentityAPIClient;
_IntegrationCapture: IntegrationCapture;
_NativeSdkHelpers: INativeSdkHelpers;
_Persistence: IPersistence;
_RoktManager: RoktManager;
_SessionManager: ISessionManager;
_ServerModel: IServerModel;
_Store: IStore;
_instanceName: string;
_preInit: IPreInit;
_timeOnSiteTimer: ForegroundTimer;
}
const { Messages, HTTPCodes, FeatureFlags } = Constants;
const { ReportBatching, CaptureIntegrationSpecificIds } = FeatureFlags;
const { StartingInitialization } = Messages.InformationMessages;
/**
* <p>All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced <a href="https://docs.mparticle.com/developers/sdk/web/multiple-instances/">multiple instances</a>. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.</p>
* <p>In current versions of mParticle, if your site has one instance, that instance name is 'default_instance'. Any methods called on mParticle on a site with one instance will be mapped to the `default_instance`.</p>
* <p>This is for simplicity and backwards compatibility. For example, calling mParticle.logPageView() automatically maps to mParticle.getInstance('default_instance').logPageView().</p>
* <p>If you have multiple instances, instances must first be initialized and then a method can be called on that instance. For example:</p>
* <code>
* mParticle.init('apiKey', config, 'another_instance');
* mParticle.getInstance('another_instance').logPageView();
* </code>
*
* @class mParticle & mParticleInstance
*/
export default function mParticleInstance(this: IMParticleWebSDKInstance, instanceName: string) {
const self = this;
// These classes are for internal use only. Not documented for public consumption
this._instanceName = instanceName;
this._NativeSdkHelpers = new NativeSdkHelpers(this);
this._SessionManager = new SessionManager(this);
this._Persistence = new Persistence(this);
this._Helpers = new Helpers(this);
this._Events = new Events(this);
this._CookieSyncManager = new CookieSyncManager(this);
this._ServerModel = new ServerModel(this);
this._Ecommerce = new Ecommerce(this);
this._ForwardingStatsUploader = new ForwardingStatsUploader(this);
this._Consent = new Consent(this);
this._IdentityAPIClient = new IdentityAPIClient(this);
this._preInit = {
readyQueue: [],
integrationDelays: {},
forwarderConstructors: [],
};
this._IntegrationCapture = new IntegrationCapture();
this._RoktManager = new RoktManager();
// required for forwarders once they reference the mparticle instance
this.IdentityType = IdentityType;
this.EventType = EventType;
this.CommerceEventType = CommerceEventType;
this.PromotionType = PromotionActionType;
this.ProductActionType = ProductActionType;
this._Identity = new Identity(this);
this.Identity = this._Identity.IdentityAPI;
this.generateHash = this._Helpers.generateHash;
// https://go.mparticle.com/work/SQDSDKS-6289
// TODO: Replace this with Store once Store is moved earlier in the init process
this.getDeviceId = this._Persistence.getDeviceId;
if (typeof window !== 'undefined') {
if (window.mParticle && window.mParticle.config) {
if (window.mParticle.config.hasOwnProperty('rq')) {
this._preInit.readyQueue = window.mParticle.config.rq;
}
}
}
this.init = function(apiKey, config) {
if (!config) {
console.warn(
'You did not pass a config object to init(). mParticle will not initialize properly'
);
}
runPreConfigFetchInitialization(this, apiKey, config);
// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization
// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization
// to it for it to be run after fetched
if (config) {
if (
!config.hasOwnProperty('requestConfig') ||
config.requestConfig
) {
const configApiClient = new ConfigAPIClient(
apiKey,
config,
this
);
configApiClient.getSDKConfiguration().then(result => {
const mergedConfig = this._Helpers.extend(
{},
config,
result
);
completeSDKInitialization(apiKey, mergedConfig, this);
});
} else {
completeSDKInitialization(apiKey, config, this);
}
} else {
console.error(
'No config available on the window, please pass a config object to mParticle.init()'
);
return;
}
};
/**
* Resets the SDK to an uninitialized state and removes cookies/localStorage. You MUST call mParticle.init(apiKey, window.mParticle.config)
* before any other mParticle methods or the SDK will not function as intended.
* @method setLogLevel
* @param {String} logLevel verbose, warning, or none. By default, `warning` is chosen.
*/
this.setLogLevel = function(newLogLevel) {
self.Logger.setLogLevel(newLogLevel);
};
/**
* Resets the SDK to an uninitialized state and removes cookies/localStorage. You MUST call mParticle.init(apiKey, window.mParticle.config)
* before any other mParticle methods or the SDK will not function as intended.
* @method reset
*/
this.reset = function(instance) {
try {
instance._Persistence.resetPersistence();
if (instance._Store) {
delete instance._Store;
}
} catch (error) {
console.error('Cannot reset mParticle', error);
}
};
this._resetForTests = function(config, keepPersistence, instance) {
if (instance._Store) {
delete instance._Store;
}
instance._Store = new Store(config, instance);
instance._Store.isLocalStorageAvailable = instance._Persistence.determineLocalStorageAvailability(
window.localStorage
);
instance._Events.stopTracking();
if (!keepPersistence) {
instance._Persistence.resetPersistence();
}
instance._Persistence.forwardingStatsBatches.uploadsTable = {};
instance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue = [];
instance._preInit = {
readyQueue: [],
pixelConfigurations: [],
integrationDelays: {},
forwarderConstructors: [],
isDevelopmentMode: false,
};
};
/**
* A callback method that is invoked after mParticle is initialized.
* @method ready
* @param {Function} function A function to be called after mParticle is initialized
*/
this.ready = function(f) {
if (self.isInitialized() && typeof f === 'function') {
f();
} else {
self._preInit.readyQueue.push(f);
}
};
/**
* Returns the current mParticle environment setting
* @method getEnvironment
* @returns {String} mParticle environment setting
*/
this.getEnvironment = function() {
return self._Store.SDKConfig.isDevelopmentMode
? Constants.Environment.Development
: Constants.Environment.Production;
};
/**
* Returns the mParticle SDK version number
* @method getVersion
* @return {String} mParticle SDK version number
*/
this.getVersion = function() {
return Constants.sdkVersion;
};
/**
* Sets the app version
* @method setAppVersion
* @param {String} version version number
*/
this.setAppVersion = function(version) {
const queued = queueIfNotInitialized(function() {
self.setAppVersion(version);
}, self);
if (queued) return;
self._Store.SDKConfig.appVersion = version;
self._Persistence.update();
};
/**
* Sets the device id
* @method setDeviceId
* @param {String} name device ID (UUIDv4-formatted string)
*/
this.setDeviceId = function(guid) {
const queued = queueIfNotInitialized(function() {
self.setDeviceId(guid);
}, self);
if (queued) return;
this._Store.setDeviceId(guid);
};
/**
* Returns a boolean for whether or not the SDKhas been fully initialized
* @method isInitialized
* @return {Boolean} a boolean for whether or not the SDK has been fully initialized
*/
this.isInitialized = function() {
return self._Store ? self._Store.isInitialized : false;
};
/**
* Gets the app name
* @method getAppName
* @return {String} App name
*/
this.getAppName = function() {
return self._Store.SDKConfig.appName;
};
/**
* Sets the app name
* @method setAppName
* @param {String} name App Name
*/
this.setAppName = function(name) {
const queued = queueIfNotInitialized(function() {
self.setAppName(name);
}, self);
if (queued) return;
self._Store.SDKConfig.appName = name;
};
/**
* Gets the app version
* @method getAppVersion
* @return {String} App version
*/
this.getAppVersion = function() {
return self._Store.SDKConfig.appVersion;
};
/**
* Stops tracking the location of the user
* @method stopTrackingLocation
*/
this.stopTrackingLocation = function() {
self._SessionManager.resetSessionTimer();
self._Events.stopTracking();
};
/**
* Starts tracking the location of the user
* @method startTrackingLocation
* @param {Function} [callback] A callback function that is called when the location is either allowed or rejected by the user. A position object of schema {coords: {latitude: number, longitude: number}} is passed to the callback
*/
this.startTrackingLocation = function(callback) {
if (!isFunction(callback)) {
self.Logger.warning(
'Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location.'
);
}
self._SessionManager.resetSessionTimer();
self._Events.startTracking(callback);
};
/**
* Sets the position of the user
* @method setPosition
* @param {Number} lattitude lattitude digit
* @param {Number} longitude longitude digit
*/
this.setPosition = function(lat, lng) {
const queued = queueIfNotInitialized(function() {
self.setPosition(lat, lng);
}, self);
if (queued) return;
self._SessionManager.resetSessionTimer();
if (typeof lat === 'number' && typeof lng === 'number') {
self._Store.currentPosition = {
lat: lat,
lng: lng,
};
} else {
self.Logger.error(
'Position latitude and/or longitude must both be of type number'
);
}
};
/**
* Starts a new session
* @method startNewSession
*/
this.startNewSession = function() {
self._SessionManager.startNewSession();
};
/**
* Ends the current session
* @method endSession
*/
this.endSession = function() {
// Sends true as an over ride vs when endSession is called from the setInterval
self._SessionManager.endSession(true);
};
/**
* Logs a Base Event to mParticle's servers
* @param {Object} event Base Event Object
* @param {Object} [eventOptions] For Event-level Configuration Options
*/
this.logBaseEvent = function(event, eventOptions) {
const queued = queueIfNotInitialized(function() {
self.logBaseEvent(event, eventOptions);
}, self);
if (queued) return;
self._SessionManager.resetSessionTimer();
if (typeof event.name !== 'string') {
self.Logger.error(Messages.ErrorMessages.EventNameInvalidType);
return;
}
if (!event.eventType) {
event.eventType = EventType.Unknown;
}
if (!self._Helpers.canLog()) {
self.Logger.error(Messages.ErrorMessages.LoggingDisabled);
return;
}
self._Events.logEvent(event, eventOptions);
};
/**
* Logs an event to mParticle's servers
* @method logEvent
* @param {String} eventName The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/web/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
* @param {Object} [customFlags] Additional customFlags
* @param {Object} [eventOptions] For Event-level Configuration Options
*/
this.logEvent = function(
eventName,
eventType,
eventInfo,
customFlags,
eventOptions
) {
const queued = queueIfNotInitialized(function() {
self.logEvent(
eventName,
eventType,
eventInfo,
customFlags,
eventOptions
);
}, self);
if (queued) return;
self._SessionManager.resetSessionTimer();
if (typeof eventName !== 'string') {
self.Logger.error(Messages.ErrorMessages.EventNameInvalidType);
return;
}
if (!eventType) {
eventType = EventType.Unknown;
}
if (!self._Helpers.isEventType(eventType)) {
self.Logger.error(
'Invalid event type: ' +
eventType +
', must be one of: \n' +
JSON.stringify(EventType)
);
return;
}
if (!self._Helpers.canLog()) {
self.Logger.error(Messages.ErrorMessages.LoggingDisabled);
return;
}
self._Events.logEvent(
{
messageType: MessageType.PageEvent,
name: eventName,
data: eventInfo,
eventType: eventType,
customFlags: customFlags,
} as BaseEvent,
eventOptions
);
};
/**
* Used to log custom errors
*
* @method logError
* @param {String or Object} error The name of the error (string), or an object formed as follows {name: 'exampleName', message: 'exampleMessage', stack: 'exampleStack'}
* @param {Object} [attrs] Custom attrs to be passed along with the error event; values must be string, number, or boolean
*/
this.logError = function(error, attrs) {
const queued = queueIfNotInitialized(function() {
self.logError(error, attrs);
}, self);
if (queued) return;
self._SessionManager.resetSessionTimer();
if (!error) {
return;
}
if (typeof error === 'string') {
error = {
message: error,
};
}
const data: IErrorLogMessageMinified = {
m: error.message ? error.message : error as string,
s: 'Error',
t: error.stack || null,
};
if (attrs) {
const sanitized = self._Helpers.sanitizeAttributes(attrs, data.m);
for (const prop in sanitized) {
data[prop] = sanitized[prop];
}
}
self._Events.logEvent({
messageType: MessageType.CrashReport,
name: error.name ? error.name : 'Error',
eventType: EventType.Other,
data: data as SDKEventAttrs,
});
};
/**
* Logs `click` events
* @method logLink
* @param {String} selector The selector to add a 'click' event to (ex. #purchase-event)
* @param {String} [eventName] The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/web/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
*/
this.logLink = function(selector, eventName, eventType, eventInfo) {
self._Events.addEventHandler(
'click',
selector,
eventName,
eventInfo,
eventType
);
};
/**
* Logs `submit` events
* @method logForm
* @param {String} selector The selector to add the event handler to (ex. #search-event)
* @param {String} [eventName] The name of the event
* @param {Number} [eventType] The eventType as seen [here](http://docs.mparticle.com/developers/sdk/web/event-tracking#event-type)
* @param {Object} [eventInfo] Attributes for the event
*/
this.logForm = function(selector, eventName, eventType, eventInfo) {
self._Events.addEventHandler(
'submit',
selector,
eventName,
eventInfo,
eventType
);
};
/**
* Logs a page view
* @method logPageView
* @param {String} eventName The name of the event. Defaults to 'PageView'.
* @param {Object} [attrs] Attributes for the event
* @param {Object} [customFlags] Custom flags for the event
* @param {Object} [eventOptions] For Event-level Configuration Options
*/
this.logPageView = function(eventName, attrs, customFlags, eventOptions) {
const queued = queueIfNotInitialized(function() {
self.logPageView(eventName, attrs, customFlags, eventOptions);
}, self);
if (queued) return;
self._SessionManager.resetSessionTimer();
if (self._Helpers.canLog()) {
if (!self._Helpers.Validators.isStringOrNumber(eventName)) {
eventName = 'PageView';
}
if (!attrs) {
attrs = {
hostname: window.location.hostname,
title: window.document.title,
};
} else if (!self._Helpers.isObject(attrs)) {
self.Logger.error(
'The attributes argument must be an object. A ' +
typeof attrs +
' was entered. Please correct and retry.'
);
return;
}
if (customFlags && !self._Helpers.isObject(customFlags)) {
self.Logger.error(
'The customFlags argument must be an object. A ' +
typeof customFlags +
' was entered. Please correct and retry.'
);
return;
}
}
self._Events.logEvent(
{
messageType: MessageType.PageView,
name: eventName,
data: attrs as SDKEventAttrs,
eventType: EventType.Unknown,
customFlags: customFlags,
},
eventOptions
);
};
/**
* Forces an upload of the batch
* @method upload
*/
this.upload = function() {
if (self._Helpers.canLog()) {
if (self._Store.webviewBridgeEnabled) {
self._NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.Upload
);
} else {
self._APIClient?.uploader?.prepareAndUpload(false, false);
}
}
};
/**
* Invoke these methods on the mParticle.Consent object.
* Example: mParticle.Consent.createConsentState()
*
* @class mParticle.Consent
*/
this.Consent = {
/**
* Creates a CCPA Opt Out Consent State.
*
* @method createCCPAConsent
* @param {Boolean} optOut true represents a "data sale opt-out", false represents the user declining a "data sale opt-out"
* @param {Number} timestamp Unix time (likely to be Date.now())
* @param {String} consentDocument document version or experience that the user may have consented to
* @param {String} location location where the user gave consent
* @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users
* @return {Object} CCPA Consent State
*/
createCCPAConsent: self._Consent.createPrivacyConsent,
/**
* Creates a GDPR Consent State.
*
* @method createGDPRConsent
* @param {Boolean} consent true represents a "data sale opt-out", false represents the user declining a "data sale opt-out"
* @param {Number} timestamp Unix time (likely to be Date.now())
* @param {String} consentDocument document version or experience that the user may have consented to
* @param {String} location location where the user gave consent
* @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users
* @return {Object} GDPR Consent State
*/
createGDPRConsent: self._Consent.createPrivacyConsent,
/**
* Creates a Consent State Object, which can then be used to set CCPA states, add multiple GDPR states, as well as get and remove these privacy states.
*
* @method createConsentState
* @return {Object} ConsentState object
*/
createConsentState: self._Consent.createConsentState,
};
/**
* Invoke these methods on the mParticle.eCommerce object.
* Example: mParticle.eCommerce.createImpresion(...)
* @class mParticle.eCommerce
*/
this.eCommerce = {
/**
* Invoke these methods on the mParticle.eCommerce.Cart object.
* Example: mParticle.eCommerce.Cart.add(...)
* @class mParticle.eCommerce.Cart
* @deprecated
*/
Cart: {
/**
* Adds a product to the cart
* @method add
* @param {Object} product The product you want to add to the cart
* @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
* @deprecated
*/
add: function(product, logEventBoolean) {
self.Logger.warning(
'Deprecated function eCommerce.Cart.add() will be removed in future releases'
);
let mpid;
const currentUser = self.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
self._Identity
.mParticleUserCart(mpid)
.add(product, logEventBoolean);
},
/**
* Removes a product from the cart
* @method remove
* @param {Object} product The product you want to add to the cart
* @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
* @deprecated
*/
remove: function(product, logEventBoolean) {
self.Logger.warning(
'Deprecated function eCommerce.Cart.remove() will be removed in future releases'
);
let mpid;
const currentUser = self.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
self._Identity
.mParticleUserCart(mpid)
.remove(product, logEventBoolean);
},
/**
* Clears the cart
* @method clear
* @deprecated
*/
clear: function() {
self.Logger.warning(
'Deprecated function eCommerce.Cart.clear() will be removed in future releases'
);
let mpid;
const currentUser = self.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
self._Identity.mParticleUserCart(mpid).clear();
},
},
/**
* Sets the currency code
* @for mParticle.eCommerce
* @method setCurrencyCode
* @param {String} code The currency code
*/
setCurrencyCode: function(code) {
const queued = queueIfNotInitialized(function() {
self.eCommerce.setCurrencyCode(code);
}, self);
if (queued) return;
if (typeof code !== 'string') {
self.Logger.error('Code must be a string');
return;
}
self._SessionManager.resetSessionTimer();
self._Store.currencyCode = code;
},
/**
* Creates a product
* @for mParticle.eCommerce
* @method createProduct
* @param {String} name product name
* @param {String} sku product sku
* @param {Number} price product price
* @param {Number} [quantity] product quantity. If blank, defaults to 1.
* @param {String} [variant] product variant
* @param {String} [category] product category
* @param {String} [brand] product brand
* @param {Number} [position] product position
* @param {String} [coupon] product coupon
* @param {Object} [attributes] product attributes
*/
createProduct: function(
name,
sku,
price,
quantity,
variant,
category,
brand,
position,
coupon,
attributes
) {
return self._Ecommerce.createProduct(
name,
sku,
price,
quantity,
variant,
category,
brand,
position,
coupon,
attributes
);
},
/**
* Creates a promotion
* @for mParticle.eCommerce
* @method createPromotion
* @param {String} id a unique promotion id
* @param {String} [creative] promotion creative
* @param {String} [name] promotion name
* @param {Number} [position] promotion position
*/
createPromotion: function(id, creative, name, position) {
return self._Ecommerce.createPromotion(
id,
creative,
name,
position
);
},
/**
* Creates a product impression
* @for mParticle.eCommerce
* @method createImpression
* @param {String} name impression name
* @param {Object} product the product for which an impression is being created
*/
createImpression: function(name, product) {
return self._Ecommerce.createImpression(name, product);
},
/**
* Creates a transaction attributes object to be used with a checkout
* @for mParticle.eCommerce
* @method createTransactionAttributes
* @param {String or Number} id a unique transaction id
* @param {String} [affiliation] affilliation
* @param {String} [couponCode] the coupon code for which you are creating transaction attributes
* @param {Number} [revenue] total revenue for the product being purchased
* @param {String} [shipping] the shipping method
* @param {Number} [tax] the tax amount
*/
createTransactionAttributes: function(
id,
affiliation,
couponCode,
revenue,
shipping,
tax
) {
return self._Ecommerce.createTransactionAttributes(
id,
affiliation,
couponCode,
revenue,
shipping,
tax
);
},
/**
* Logs a checkout action
* @for mParticle.eCommerce
* @method logCheckout
* @param {Number} step checkout step number
* @param {String} checkout option string
* @param {Object} attrs
* @param {Object} [customFlags] Custom flags for the event
* @deprecated
*/
logCheckout: function(step, option, attrs, customFlags) {
self.Logger.warning(
'mParticle.logCheckout is deprecated, please use mParticle.logProductAction instead'
);
if (!self._Store.isInitialized) {
self.ready(function() {
self.eCommerce.logCheckout(
step,
option,
attrs,
customFlags
);
});
return;
}
self._SessionManager.resetSessionTimer();
self._Events.logCheckoutEvent(step, option, attrs, customFlags);
},
/**
* Logs a product action
* @for mParticle.eCommerce
* @method logProductAction
* @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218)
* @param {Object} product the product for which you are creating the product action
* @param {Object} [attrs] attributes related to the product action
* @param {Object} [customFlags] Custom flags for the event
* @param {Object} [transactionAttributes] Transaction Attributes for the event
* @param {Object} [eventOptions] For Event-level Configuration Options
*/
logProductAction: function(
productActionType,
product,
attrs,
customFlags,
transactionAttributes,
eventOptions
) {
const queued = queueIfNotInitialized(function() {
self.eCommerce.logProductAction(
productActionType,
product,
attrs,
customFlags,
transactionAttributes,
eventOptions
);
}, self);
if (queued) return;
self._SessionManager.resetSessionTimer();
self._Events.logProductActionEvent(
productActionType,
product,
attrs,
customFlags,
transactionAttributes,
eventOptions
);
},
/**
* Logs a product purchase
* @for mParticle.eCommerce
* @method logPurchase
* @param {Object} transactionAttributes transactionAttributes object
* @param {Object} product the product being purchased
* @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false
* @param {Object} [attrs] other attributes related to the product purchase
* @param {Object} [customFlags] Custom flags for the event
* @deprecated
*/
logPurchase: function(
transactionAttributes,
product,
clearCart,
attrs,
customFlags
) {
self.Logger.warning(
'mParticle.logPurchase is deprecated, please use mParticle.logProductAction instead'
);
if (!self._Store.isInitialized) {
self.ready(function() {
self.eCommerce.logPurchase(
transactionAttributes,
product,
clearCart,
attrs,
customFlags
);
});
return;
}
if (!transactionAttributes || !product) {
self.Logger.error(Messages.ErrorMessages.BadLogPurchase);
return;
}
self._SessionManager.resetSessionTimer();
self._Events.logPurchaseEvent(
transactionAttributes,
product,
attrs,
customFlags
);
},
/**
* Logs a product promotion
* @for mParticle.eCommerce
* @method logPromotion
* @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279)
* @param {Object} promotion promotion object
* @param {Object} [attrs] boolean to clear the cart after logging or not
* @param {Object} [customFlags] Custom flags for the event
* @param {Object} [eventOptions] For Event-level Configuration Options
*/