@mparticle/web-sdk 2.58.0 → 2.60.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mparticle.common.js +110 -86
- package/dist/mparticle.esm.js +110 -86
- package/dist/mparticle.js +467 -276
- package/package.json +1 -1
- package/src/apiClient.ts +42 -4
- package/src/batchUploader.ts +23 -26
- package/src/cookieSyncManager.ts +6 -0
- package/src/foregroundTimeTracker.ts +5 -3
- package/src/identity-utils.ts +24 -1
- package/src/identityApiClient.ts +15 -5
- package/src/logger.ts +4 -0
- package/src/mp-instance.ts +65 -23
- package/src/persistence.js +15 -0
- package/src/roktManager.ts +12 -4
- package/src/sdkRuntimeModels.ts +2 -0
- package/src/sessionManager.ts +11 -2
- package/src/store.ts +2 -1
- package/src/utils.ts +63 -2
- package/src/vault.ts +28 -35
package/dist/mparticle.common.js
CHANGED
|
@@ -15,7 +15,7 @@ map:function map(a,b){var c,d,e;if(null===this)throw new TypeError(" this is nul
|
|
|
15
15
|
filter:function filter(a/*, thisArg*/){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g);}return d},// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
|
|
16
16
|
isArray:function isArray(a){return "[object Array]"===Object.prototype.toString.call(a)},Base64:Base64$1};
|
|
17
17
|
|
|
18
|
-
var version = "2.
|
|
18
|
+
var version = "2.60.0";
|
|
19
19
|
|
|
20
20
|
var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
|
|
21
21
|
},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/",loggingUrl:"apps.rokt-api.com/v1/log",errorUrl:"apps.rokt-api.com/v1/errors"},// These are the paths that are used to construct the CNAME urls
|
|
@@ -30,6 +30,16 @@ CaptureIntegrationSpecificIds:"captureIntegrationSpecificIds",// CaptureIntegrat
|
|
|
30
30
|
CaptureIntegrationSpecificIdsV2:"captureIntegrationSpecificIdsV2",AstBackgroundEvents:"astBackgroundEvents"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out",IdentityMethods:{Modify:"modify",Logout:"logout",Login:"login",Identify:"identify"},Environment:{Development:"development",Production:"production"},CaptureIntegrationSpecificIdsV2Modes:{All:"all",None:"none",RoktOnly:"roktonly"},Rokt:{LauncherInstanceGuidKey:"__rokt_li_guid__"}};var ONE_DAY_IN_SECONDS=86400;var MILLIS_IN_ONE_SEC=1e3;// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
|
|
31
31
|
var HTTP_OK=200;var HTTP_ACCEPTED=202;var HTTP_BAD_REQUEST=400;var HTTP_SERVER_ERROR=500;
|
|
32
32
|
|
|
33
|
+
function _typeof$1(o) {
|
|
34
|
+
"@babel/helpers - typeof";
|
|
35
|
+
|
|
36
|
+
return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
|
|
37
|
+
return typeof o;
|
|
38
|
+
} : function (o) {
|
|
39
|
+
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
|
|
40
|
+
}, _typeof$1(o);
|
|
41
|
+
}
|
|
42
|
+
|
|
33
43
|
/******************************************************************************
|
|
34
44
|
Copyright (c) Microsoft Corporation.
|
|
35
45
|
|
|
@@ -139,7 +149,11 @@ return isStringOrNumber(a)?a.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g,"
|
|
|
139
149
|
var b=function parseCookies(){try{return "undefined"==typeof window?[]:window.document.cookie.split(";").map(function(a){return a.trim()})}catch(a){return console.error("Unable to parse cookies",a),[]}}();// Helper function to filter cookies by keys
|
|
140
150
|
// Parse cookies from document.cookie
|
|
141
151
|
// Filter cookies by keys if provided
|
|
142
|
-
return function filterCookies(a,b){for(var c={},d=0,e=a;d<e.length;d++){var f=e[d],g=f.split("="),h=g[0],i=g[1];(!b||b.includes(h))&&(c[h]=i);}return c}(b,a)},getHref=function(){return "undefined"!=typeof window&&window.location?window.location.href:""},filterDictionaryWithHash=function(a,b,c){var d={};if(!isEmpty(a))for(var e in a)if(a.hasOwnProperty(e)){var f=c(e);inArray(b,f)||(d[e]=a[e]);}return d},parseConfig=function(a,b,c){var d;return (null===(d=a.kitConfigs)||void 0===d?void 0:d.find(function(a){return a.name===b&&a.moduleId===c}))||null}
|
|
152
|
+
return function filterCookies(a,b){for(var c={},d=0,e=a;d<e.length;d++){var f=e[d],g=f.split("="),h=g[0],i=g[1];(!b||b.includes(h))&&(c[h]=i);}return c}(b,a)},getHref=function(){return "undefined"!=typeof window&&window.location?window.location.href:""},filterDictionaryWithHash=function(a,b,c){var d={};if(!isEmpty(a))for(var e in a)if(a.hasOwnProperty(e)){var f=c(e);inArray(b,f)||(d[e]=a[e]);}return d},parseConfig=function(a,b,c){var d;return (null===(d=a.kitConfigs)||void 0===d?void 0:d.find(function(a){return a.name===b&&a.moduleId===c}))||null},obfuscateData=function(a){// Preserve null and undefined
|
|
153
|
+
if(null===a||a===void 0)return a;// Handle arrays - recursively obfuscate each element
|
|
154
|
+
if(Array.isArray(a))return a.map(function(a){return obfuscateData(a)});// Handle objects - recursively obfuscate each property
|
|
155
|
+
if(isObject(a)){var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]=obfuscateData(a[c]));return b}// For primitives and other types, return the type as a string
|
|
156
|
+
return _typeof$1(a)},obfuscateDevData=function(a,b){return b?a:obfuscateData(a)};/**
|
|
143
157
|
* Returns a value between 1-100 inclusive.
|
|
144
158
|
*/ // FIXME: REFACTOR for V3
|
|
145
159
|
|
|
@@ -150,16 +164,6 @@ if(c.includes(d)){var e=IdentityType.getIdentityName(parseNumber(d));b[e]=a[d];}
|
|
|
150
164
|
getExpansionName:function getExpansionName(a){return a===ProductActionType.AddToCart?"add_to_cart":a===ProductActionType.RemoveFromCart?"remove_from_cart":a===ProductActionType.Checkout?"checkout":a===ProductActionType.CheckoutOption?"checkout_option":a===ProductActionType.Click?"click":a===ProductActionType.ViewDetail?"view_detail":a===ProductActionType.Purchase?"purchase":a===ProductActionType.Refund?"refund":a===ProductActionType.AddToWishlist?"add_to_wishlist":a===ProductActionType.RemoveFromWishlist?"remove_from_wishlist":"unknown"}};var PromotionActionType={Unknown:0,PromotionView:1,PromotionClick:2,getName:function getName(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"},// these are the names that the server and mobile SDKs use while expanding CommerceEvent
|
|
151
165
|
getExpansionName:function getExpansionName(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"}};var ProfileMessageType={Logout:3};var ApplicationTransitionType$1={AppInit:1};var PerformanceMarkType={SdkStart:"mp:sdkStart",JointSdkSelectPlacements:"mp:jointSdkSelectPlacements",JointSdkRoktKitInit:"mp:jointSdkRoktKitInit"};var Types = {MessageType:MessageType$1,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,Environment:Constants.Environment};
|
|
152
166
|
|
|
153
|
-
function _typeof$1(o) {
|
|
154
|
-
"@babel/helpers - typeof";
|
|
155
|
-
|
|
156
|
-
return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
|
|
157
|
-
return typeof o;
|
|
158
|
-
} : function (o) {
|
|
159
|
-
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
|
|
160
|
-
}, _typeof$1(o);
|
|
161
|
-
}
|
|
162
|
-
|
|
163
167
|
var SDKProductActionType;(function(a){a[a.Unknown=0]="Unknown",a[a.AddToCart=1]="AddToCart",a[a.RemoveFromCart=2]="RemoveFromCart",a[a.Checkout=3]="Checkout",a[a.CheckoutOption=4]="CheckoutOption",a[a.Click=5]="Click",a[a.ViewDetail=6]="ViewDetail",a[a.Purchase=7]="Purchase",a[a.Refund=8]="Refund",a[a.AddToWishlist=9]="AddToWishlist",a[a.RemoveFromWishlist=10]="RemoveFromWishlist";})(SDKProductActionType||(SDKProductActionType={}));var LogLevelType={None:"none",Verbose:"verbose",Warning:"warning",Error:"error"};
|
|
164
168
|
|
|
165
169
|
function getDefaultExportFromCjs (x) {
|
|
@@ -411,15 +415,14 @@ return g=Object.assign(g,b),{event_type:dist.EventTypeEnum.applicationStateTrans
|
|
|
411
415
|
var BaseVault=/** @class */function(){/**
|
|
412
416
|
*
|
|
413
417
|
* @param {string} storageKey the local storage key string
|
|
414
|
-
* @param {Storage} Web API Storage object that is being used
|
|
415
|
-
|
|
416
|
-
*/function a(a,b,c){this._storageKey=a,this.storageObject=b,this.logger=(null===c||void 0===c?void 0:c.logger)||{verbose:function verbose(){},warning:function warning(){},error:function error(){}},this.contents=this.retrieve();}/**
|
|
418
|
+
* @param {Storage} storageObject Web API Storage object that is being used
|
|
419
|
+
*/function a(a,b){this._storageKey=a,this.storageObject=b,this.contents=this.retrieve();}/**
|
|
417
420
|
* Stores a StorableItem to Storage
|
|
418
421
|
* @method store
|
|
419
422
|
* @param item {StorableItem}
|
|
420
|
-
*/return a.prototype.store=function(a){var b;this.contents=a,b=isNumber(a)||!isEmpty(a)?JSON.stringify(a):""
|
|
423
|
+
*/return a.prototype.store=function(a){var b;this.contents=a,b=isNumber(a)||!isEmpty(a)?JSON.stringify(a):"",this.storageObject.setItem(this._storageKey,b);},a.prototype.retrieve=function(){// TODO: Handle cases where Local Storage is unavailable
|
|
421
424
|
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
422
|
-
var a=this.storageObject.getItem(this._storageKey);return this.contents=a?JSON.parse(a):null,this.
|
|
425
|
+
var a=this.storageObject.getItem(this._storageKey);return this.contents=a?JSON.parse(a):null,this.contents},a.prototype.purge=function(){this.contents=null,this.storageObject.removeItem(this._storageKey);},a}();var LocalStorageVault=/** @class */function(a){function b(b){return a.call(this,b,window.localStorage)||this}return __extends(b,a),b}(BaseVault);var SessionStorageVault=/** @class */function(a){function b(b){return a.call(this,b,window.sessionStorage)||this}return __extends(b,a),b}(BaseVault);var DisabledVault=/** @class */function(a){function b(b){var c=a.call(this,b,window.localStorage)||this;return c.contents=null,c.storageObject.removeItem(c._storageKey),c}return __extends(b,a),b.prototype.store=function(){this.contents=null;},b.prototype.retrieve=function(){return this.contents},b.prototype.purge=function(){this.contents=null;},b}(BaseVault);
|
|
423
426
|
|
|
424
427
|
var AsyncUploader=/** @class */function(){function a(a){this.url=a;}return a}();var FetchUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a,b){return __awaiter(this,void 0,void 0,function(){var c;return __generator(this,function(d){switch(d.label){case 0:return c=b||this.url,[4/*yield*/,fetch(c,a)];case 1:return [2/*return*/,d.sent()]}})})},b}(AsyncUploader);var XHRUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,this.makeRequest(this.url,a.body,a.method,a.headers)];case 1:return b=c.sent(),[2/*return*/,b]}})})},b.prototype.makeRequest=function(a,b,c,d){return void 0===c&&(c="post"),void 0===d&&(d={}),__awaiter(this,void 0,void 0,function(){var e;return __generator(this,function(){return e=new XMLHttpRequest,[2/*return*/,new Promise(function(f,g){for(var h in e.onreadystatechange=function(){4!==e.readyState||// Process the response
|
|
425
428
|
// We resolve all xhr responses whose ready state is 4 regardless of HTTP codes that may be errors (400+)
|
|
@@ -448,7 +451,8 @@ function appendUserInfo(a,b){if(b){if(!a)return b.MPID=null,b.ConsentState=null,
|
|
|
448
451
|
* Creates an instance of a BatchUploader
|
|
449
452
|
* @param {IMParticleWebSDKInstance} mpInstance - the mParticle SDK instance
|
|
450
453
|
* @param {number} uploadInterval - the desired upload interval in milliseconds
|
|
451
|
-
*/function a(b,c){var d;this.offlineStorageEnabled=!1,this.lastASTEventTime=0,this.AST_DEBOUNCE_MS=1e3,this.mpInstance=b,this.uploadIntervalMillis=c,this.batchingEnabled=c>=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis<a.MINIMUM_INTERVAL_MILLIS&&(this.uploadIntervalMillis=a.MINIMUM_INTERVAL_MILLIS),this.eventsQueuedForProcessing=[],this.batchesQueuedForProcessing=[],this.offlineStorageEnabled=this.isOfflineStorageAvailable()
|
|
454
|
+
*/function a(b,c){var d,e;this.offlineStorageEnabled=!1,this.lastASTEventTime=0,this.AST_DEBOUNCE_MS=1e3,this.mpInstance=b,this.uploadIntervalMillis=c,this.batchingEnabled=c>=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis<a.MINIMUM_INTERVAL_MILLIS&&(this.uploadIntervalMillis=a.MINIMUM_INTERVAL_MILLIS),this.eventsQueuedForProcessing=[],this.batchesQueuedForProcessing=[],this.offlineStorageEnabled=this.isOfflineStorageAvailable();// When noFunctional is true, prevent events/batches storage
|
|
455
|
+
var f=null===(e=b._CookieConsentManager)||void 0===e?void 0:e.getNoFunctional();this.offlineStorageEnabled&&!f&&(this.eventVault=new SessionStorageVault("".concat(b._Store.storageName,"-events")),this.batchVault=new LocalStorageVault("".concat(b._Store.storageName,"-batches")),(d=this.eventsQueuedForProcessing).push.apply(d,this.eventVault.retrieve()));var g=this.mpInstance._Store,h=g.SDKConfig,i=g.devToken,j=this.mpInstance._Helpers.createServiceUrl(h.v3SecureServiceUrl,i);this.uploadUrl="".concat(j,"/events"),this.uploader=window.fetch?new FetchUploader(this.uploadUrl):new XHRUploader(this.uploadUrl),this.triggerUploadInterval(!0,!1),this.addEventListeners();}return a.prototype.isOfflineStorageAvailable=function(){var a=this.mpInstance,b=a._Helpers.getFeatureFlag,c=a._Store.deviceId,d=b(Constants.FeatureFlags.OfflineStorage),e=parseInt(d,10),f=getRampNumber(c);// https://go.mparticle.com/work/SQDSDKS-6317
|
|
452
456
|
// TODO: Handle cases where Local Storage is unavailable
|
|
453
457
|
// Potentially shared between Vault and Persistence as well
|
|
454
458
|
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
@@ -456,25 +460,62 @@ return e>=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Dat
|
|
|
456
460
|
if(s){this.mpInstance._IntegrationCapture.capture();var t=this.mpInstance._IntegrationCapture.getClickIdsAsCustomFlags();o=__assign(__assign({},t),o);var u=this.mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes();p=__assign(__assign({},u),p);}return n.CustomFlags=o,n.IntegrationAttributes=p,appendUserInfo(m(),n),n},a.prototype.addEventListeners=function(){var a=this,b=this,c=function(){// Check for debounce before creating and queueing event
|
|
457
461
|
var c=a.mpInstance._Helpers.getFeatureFlag,d=Constants.FeatureFlags.AstBackgroundEvents;if(c(d)){if(b.shouldDebounceAndUpdateLastASTTime())return;// Add application state transition event to queue
|
|
458
462
|
var e=b.createBackgroundASTEvent();b.queueEvent(e);}// Then trigger the upload with beacon
|
|
459
|
-
b.prepareAndUpload(!1,b.isBeaconAvailable());};document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&c();}),window.addEventListener("beforeunload",c),window.addEventListener("pagehide",c);},a.prototype.isBeaconAvailable=function(){return !!navigator.sendBeacon},a.prototype.triggerUploadInterval=function(a,b){var c=this;void 0===a&&(a=!1),void 0===b&&(b=!1),setTimeout(function(){c.prepareAndUpload(a,b);},this.uploadIntervalMillis);},a.prototype.queueEvent=function(a){if(!isEmpty(a)){
|
|
463
|
+
b.prepareAndUpload(!1,b.isBeaconAvailable());};document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&c();}),window.addEventListener("beforeunload",c),window.addEventListener("pagehide",c);},a.prototype.isBeaconAvailable=function(){return !!navigator.sendBeacon},a.prototype.triggerUploadInterval=function(a,b){var c=this;void 0===a&&(a=!1),void 0===b&&(b=!1),setTimeout(function(){c.prepareAndUpload(a,b);},this.uploadIntervalMillis);},a.prototype.queueEvent=function(a){if(!isEmpty(a)){if(this.eventsQueuedForProcessing.push(a),this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store(this.eventsQueuedForProcessing),this.mpInstance.Logger.isVerbose()){var b=obfuscateDevData(a,this.mpInstance._Store.SDKConfig.isDevelopmentMode);this.mpInstance.Logger.verbose("Queuing event: ".concat(JSON.stringify(b))),this.mpInstance.Logger.verbose("Queued event count: ".concat(this.eventsQueuedForProcessing.length));}this.shouldTriggerImmediateUpload(a.EventDataType)&&this.prepareAndUpload(!1,!1);}},a.prototype.shouldTriggerImmediateUpload=function(a){var b=[MessageType$1.Commerce,MessageType$1.UserIdentityChange];return !this.batchingEnabled||b.includes(a)},(a.createNewBatches=function(a,b,c){if(!b||!a||!a.length)return null;//bucket by MPID, and then by session, ordered by timestamp
|
|
460
464
|
for(var d,e=[],f=new Map,g=0,h=a;g<h.length;g++){//on initial startup, there may be events logged without an mpid.
|
|
461
|
-
if(d=h[g],!d.MPID){var i=b.getMPID();d.MPID=i;}var j=f.get(d.MPID);j||(j=[]),j.push(d),f.set(d.MPID,j);}for(var k=0,l=Array.from(f.entries());k<l.length;k++){for(var m=l[k],i=m[0],n=m[1],o=new Map,p=0,q=n;p<q.length;p++){var d=q[p],j=o.get(d.SessionId);j||(j=[]),j.push(d),o.set(d.SessionId,j);}for(var r=0,s=Array.from(o.entries());r<s.length;r++){var t=s[r],u=convertEvents(i,t[1],c),v=c._Store.SDKConfig.onCreateBatch;v&&(u=v(u),u?u.modified=!0:c.Logger.warning("Skiping batch upload because no batch was returned from onCreateBatch callback")),u&&e.push(u);}}return e},a.prototype.prepareAndUpload=function(b,c){return void 0===b&&(b=!1),void 0===c&&(c=!1),__awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k;return __generator(this,function(l){switch(l.label){case 0:return d=this.mpInstance.Identity.getCurrentUser(),e=this.eventsQueuedForProcessing,this.eventsQueuedForProcessing=[],this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store([]),f=[],isEmpty(e)||(f=a.createNewBatches(e,d,this.mpInstance)),this.offlineStorageEnabled&&this.batchVault&&((i=this.batchesQueuedForProcessing).unshift.apply(i,this.batchVault.retrieve()),this.batchVault.purge()),isEmpty(f)||(j=this.batchesQueuedForProcessing).push.apply(j,f),g=this.batchesQueuedForProcessing,this.batchesQueuedForProcessing=[],[4/*yield*/,this.uploadBatches(
|
|
462
|
-
return
|
|
463
|
-
return
|
|
465
|
+
if(d=h[g],!d.MPID){var i=b.getMPID();d.MPID=i;}var j=f.get(d.MPID);j||(j=[]),j.push(d),f.set(d.MPID,j);}for(var k=0,l=Array.from(f.entries());k<l.length;k++){for(var m=l[k],i=m[0],n=m[1],o=new Map,p=0,q=n;p<q.length;p++){var d=q[p],j=o.get(d.SessionId);j||(j=[]),j.push(d),o.set(d.SessionId,j);}for(var r=0,s=Array.from(o.entries());r<s.length;r++){var t=s[r],u=convertEvents(i,t[1],c),v=c._Store.SDKConfig.onCreateBatch;v&&(u=v(u),u?u.modified=!0:c.Logger.warning("Skiping batch upload because no batch was returned from onCreateBatch callback")),u&&e.push(u);}}return e},a.prototype.prepareAndUpload=function(b,c){return void 0===b&&(b=!1),void 0===c&&(c=!1),__awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k;return __generator(this,function(l){switch(l.label){case 0:return d=this.mpInstance.Identity.getCurrentUser(),e=this.eventsQueuedForProcessing,this.eventsQueuedForProcessing=[],this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store([]),f=[],isEmpty(e)||(f=a.createNewBatches(e,d,this.mpInstance)),this.offlineStorageEnabled&&this.batchVault&&((i=this.batchesQueuedForProcessing).unshift.apply(i,this.batchVault.retrieve()),this.batchVault.purge()),isEmpty(f)||(j=this.batchesQueuedForProcessing).push.apply(j,f),g=this.batchesQueuedForProcessing,this.batchesQueuedForProcessing=[],[4/*yield*/,this.uploadBatches(g,c)];case 1:return h=l.sent(),isEmpty(h)||(k=this.batchesQueuedForProcessing).unshift.apply(k,h),!c&&this.offlineStorageEnabled&&this.batchVault&&(this.batchVault.store(this.batchesQueuedForProcessing),this.batchesQueuedForProcessing=[]),b&&this.triggerUploadInterval(b,!1),[2/*return*/]}})})},a.prototype.uploadBatches=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,j,k;return __generator(this,function(i){switch(i.label){case 0:if(d=b.filter(function(a){return !isEmpty(a.events)}),isEmpty(d))return [2/*return*/,null];this.mpInstance.Logger.isVerbose()&&(e=obfuscateDevData(d,this.mpInstance._Store.SDKConfig.isDevelopmentMode),this.mpInstance.Logger.verbose("Uploading batches: ".concat(JSON.stringify(e))),this.mpInstance.Logger.verbose("Batch count: ".concat(d.length))),f=0,i.label=1;case 1:return f<d.length?(g={method:"POST",headers:{Accept:a.CONTENT_TYPE,"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify(d[f])},!(c&&this.isBeaconAvailable()))?[3/*break*/,2]:(h=new Blob([g.body],{type:"text/plain;charset=UTF-8"}),navigator.sendBeacon(this.uploadUrl,h),[3/*break*/,5]):[3/*break*/,6];case 2:return i.trys.push([2,4,,5]),[4/*yield*/,this.uploader.upload(g)];case 3:if(j=i.sent(),200<=j.status&&300>j.status)this.mpInstance.Logger.verbose("Upload success for request ID: ".concat(d[f].source_request_id));else {if(500<=j.status||429===j.status)// Server error, add back current batches and try again later
|
|
466
|
+
return this.mpInstance.Logger.error("HTTP error status ".concat(j.status," received")),[2/*return*/,d.slice(f,d.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads.
|
|
467
|
+
return this.mpInstance.Logger.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),this.mpInstance.Logger.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,d.slice(f,d.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null]}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a)}();
|
|
468
|
+
|
|
469
|
+
var _a=Constants.IdentityMethods,Identify$2=_a.Identify,Modify$4=_a.Modify,Login$2=_a.Login,Logout$2=_a.Logout;var CACHE_HEADER="x-mp-max-age";var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache
|
|
470
|
+
if(!e){// default the expire timestamp to one day in milliseconds unless a header comes back
|
|
471
|
+
var f=getExpireTimestamp(null===d||void 0===d?void 0:d.cacheMaxAge);a===Login$2||a===Identify$2?cacheIdentityRequest(a,b,f,c,d):a===Modify$4||a===Logout$2?c.purge():void 0;}};var cacheIdentityRequest=function(a,b,c,d,e){var f=e.responseText,g=e.status,h=d.retrieve()||{},i=concatenateIdentities(a,b),j=generateHash(i),k=f.mpid,l=f.is_logged_in;h[j]={responseText:JSON.stringify({mpid:k,is_logged_in:l}),status:g,expireTimestamp:c},d.store(h);};// We need to ensure that identities are concatenated in a deterministic way, so
|
|
472
|
+
// we sort the identities based on their enum.
|
|
473
|
+
// we create an array, set the user identity at the index of the user identity type
|
|
474
|
+
var concatenateIdentities=function(a,b){var c="".concat(a,":").concat("device_application_stamp","=").concat(b.device_application_stamp,";"),d=Object.keys(b).length,e="";// set DAS first since it is not an official identity type
|
|
475
|
+
if(d){var f=[];// create an array where each index is equal to the user identity type
|
|
476
|
+
for(var g in b)if(g==="device_application_stamp")continue;else f[Types.IdentityType.getIdentityType(g)]=b[g];e=f.reduce(function(a,b,c){var d=Types.IdentityType.getIdentityName(c);return "".concat(a).concat(d,"=").concat(b,";")},c);}return e};var hasValidCachedIdentity=function(a,b,c){// There is an edge case where multiple identity calls are taking place
|
|
477
|
+
// before identify fires, so there may not be a cache. See what happens when
|
|
478
|
+
// the ? in idCache is removed to the following test
|
|
479
|
+
// "queued events contain login mpid instead of identify mpid when calling
|
|
480
|
+
// login immediately after mParticle initializes"
|
|
481
|
+
var d=null===c||void 0===c?void 0:c.retrieve();// if there is no cache, then there is no valid cached identity
|
|
482
|
+
if(!d)return !1;var e=concatenateIdentities(a,b),f=generateHash(e);// if cache doesn't have the cacheKey, there is no valid cached identity
|
|
483
|
+
if(!d.hasOwnProperty(f))return !1;// If there is a valid cache key, compare the expireTimestamp to the current time.
|
|
484
|
+
// If the current time is greater than the expireTimestamp, it is not a valid
|
|
485
|
+
// cached identity.
|
|
486
|
+
var g=d[f].expireTimestamp;return !(g<new Date().getTime())};var getCachedIdentity=function(a,b,c){var d=concatenateIdentities(a,b),e=generateHash(d),f=c.retrieve(),g=f?f[e]:null;return {responseText:parseIdentityResponse(g.responseText),expireTimestamp:g.expireTimestamp,status:g.status}};// https://go.mparticle.com/work/SQDSDKS-6079
|
|
487
|
+
var createKnownIdentities=function(a,b){var c={};if(isObject(null===a||void 0===a?void 0:a.userIdentities))for(var d in a.userIdentities)c[d]=a.userIdentities[d];return c.device_application_stamp=b,c};var removeExpiredIdentityCacheDates=function(a){var b=a.retrieve()||{},c=new Date().getTime();// Iterate over the cache and remove any key/value pairs that are expired
|
|
488
|
+
for(var d in b)b[d].expireTimestamp<c&&delete b[d];a.store(b);};var tryCacheIdentity=function(a,b,c,d,e,f,g){// https://go.mparticle.com/work/SQDSDKS-6095
|
|
489
|
+
var h=hasValidCachedIdentity(g,a,b);// If Identity is cached, then immediately parse the identity response
|
|
490
|
+
if(h){var i=getCachedIdentity(g,a,b);return c(i,d,e,f,g,a,!0),!0}return !1};var getExpireTimestamp=function(a){return void 0===a&&(a=ONE_DAY_IN_SECONDS),new Date().getTime()+a*MILLIS_IN_ONE_SEC},parseIdentityResponse=function(a){return a?JSON.parse(a):{}};var hasIdentityRequestChanged=function(a,b){if(!a||!(null!==b&&void 0!==b)||!b.userIdentities)return !1;var c=a.getUserIdentities().userIdentities,d=b.userIdentities;return JSON.stringify(c)!==JSON.stringify(d)};/**
|
|
491
|
+
* Checks if deviceId or other user identifiers (like email) were explicitly provided
|
|
492
|
+
* by the partner via config.deviceId or config.identifyRequest.userIdentities.
|
|
493
|
+
* When noFunctional is true, then cookies are blocked, so the partner must explicitly
|
|
494
|
+
* pass deviceId or other identifiers to prevent new users from being created on each page load.
|
|
495
|
+
*
|
|
496
|
+
* @param store - The SDK store (provides SDKConfig.deviceId and SDKConfig.identifyRequest.userIdentities)
|
|
497
|
+
* @returns true if deviceId or other identifiers were explicitly provided in config, false otherwise
|
|
498
|
+
*/var hasExplicitIdentifier=function(a){var b,c,d,e=null===(c=null===(b=null===a||void 0===a?void 0:a.SDKConfig)||void 0===b?void 0:b.identifyRequest)||void 0===c?void 0:c.userIdentities;return !!(e&&isObject(e)&&!isEmpty(e)&&Object.values(e).some(Boolean))||!(!(null!==(d=null===a||void 0===a?void 0:a.SDKConfig)&&void 0!==d)||!d.deviceId)};
|
|
464
499
|
|
|
465
500
|
function APIClient(a,b){this.uploader=null;var c=this;this.queueEventForBatchUpload=function(b){if(!this.uploader){// https://go.mparticle.com/work/SQDSDKS-6317
|
|
466
501
|
var c=parseNumber(a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis));this.uploader=new BatchUploader(a,c);}// https://go.mparticle.com/work/SQDSDKS-6038
|
|
467
|
-
this.uploader.queueEvent(b),a._Persistence.update();},this.processQueuedEvents=function(){var b,d=a.Identity.getCurrentUser();if(d&&(b=d.getMPID()),a._Store.eventQueue.length&&b){var e=a._Store.eventQueue;a._Store.eventQueue=[],this.appendUserInfoToEvents(d,e),e.forEach(function(a){c.sendEventToServer(a);});}},this.appendUserInfoToEvents=function(a,b){b.forEach(function(b){b.MPID||appendUserInfo(a,b);});}
|
|
468
|
-
//
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
var
|
|
502
|
+
this.uploader.queueEvent(b),a._Persistence.update();},this.processQueuedEvents=function(){var b,d=a.Identity.getCurrentUser();if(d&&(b=d.getMPID()),a._Store.eventQueue.length&&b){var e=a._Store.eventQueue;a._Store.eventQueue=[],this.appendUserInfoToEvents(d,e),e.forEach(function(a){c.sendEventToServer(a);});}},this.appendUserInfoToEvents=function(a,b){b.forEach(function(b){b.MPID||appendUserInfo(a,b);});};// When noFunctional is set and there are no identities passed, the SDK will not fully initialize.
|
|
503
|
+
// In this case, there will be no MPID, but we still want kits to initialize and forward the event to kits.
|
|
504
|
+
// The original event is queued for the MP server upload path so it can be sent once an MPID is returned.
|
|
505
|
+
// Returns true if the event was handled by this path (caller should return early).
|
|
506
|
+
var d=function(c,d){var e,f=(null===(e=a._CookieConsentManager)||void 0===e?void 0:e.getNoFunctional())&&!hasExplicitIdentifier(a._Store);if(!f||d||!a._Store.configurationLoaded||a._Store.requireDelay)return !1;var g=c;return (null===b||void 0===b?void 0:b.kitBlockingEnabled)&&(g=b.createBlockedEvent(c)),g&&(a._Forwarders.sendEventToForwarders(g),c.AlreadySentToForwarders=!0),a.Logger.verbose("noFunctional event forwarded to kits and queued for MP server upload when MPID is available."),a._Store.eventQueue.push(c),!0};this.sendEventToServer=function(c,e){var f=a._Helpers.extend({shouldUploadEvent:!0},e);if(a._Store.webviewBridgeEnabled)return void a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.LogEvent,JSON.stringify(c));var g,h=a.Identity.getCurrentUser();if(h&&(g=h.getMPID()),a._Store.requireDelay=a._Helpers.isDelayedByIntegration(a._preInit.integrationDelays,a._Store.integrationDelayTimeoutStart,Date.now()),!d(c,g)){// We queue events if there is no MPID (MPID is null, or === 0), or there are integrations that
|
|
507
|
+
// require this to stall because integration attributes need to be set, or if we are still
|
|
508
|
+
// fetching the config (self hosted only), and so require delaying events
|
|
509
|
+
if(!g||a._Store.requireDelay||!a._Store.configurationLoaded)return a.Logger.verbose("Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay."),void a._Store.eventQueue.push(c);this.processQueuedEvents(),isEmpty(c)||(f.shouldUploadEvent&&this.queueEventForBatchUpload(c),c.EventName!==Types.MessageType.AppStateTransition&&(b&&b.kitBlockingEnabled&&(c=b.createBlockedEvent(c)),c&&!c.AlreadySentToForwarders&&a._Forwarders.sendEventToForwarders(c)));}// https://go.mparticle.com/work/SQDSDKS-6038
|
|
510
|
+
},this.sendBatchForwardingStatsToServer=function(b,c){var d,e;try{d=a._Helpers.createServiceUrl(a._Store.SDKConfig.v2SecureServiceUrl,a._Store.devToken),e={uuid:a._Helpers.generateUniqueId(),data:b},c&&(c.open("post",d+"/Forwarding"),c.send(JSON.stringify(e)));}catch(b){a.Logger.error("Error sending forwarding stats to mParticle servers.");}},this.initializeForwarderStatsUploader=function(){var b=a._Store.SDKConfig.v1SecureServiceUrl,c=a._Store.devToken,d="https://".concat(b).concat(c,"/Forwarding"),e=window.fetch?new FetchUploader(d):new XHRUploader(d);return e},this.prepareForwardingStats=function(b,c){var d,e=a._Forwarders.getForwarderStatsQueue();if(b&&b.isVisible){d={mid:b.id,esid:b.eventSubscriptionId,n:c.EventName,attrs:c.EventAttributes,sdk:c.SDKVersion,dt:c.EventDataType,et:c.EventCategory,dbg:c.Debug,ct:c.Timestamp,eec:c.ExpandedEventCount,dp:c.DataPlan};var f=a._Forwarders,g=f.sendSingleForwardingStatsToServer,h=f.setForwarderStatsQueue;a._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)?(e.push(d),h(e)):g(d);}};}
|
|
511
|
+
|
|
512
|
+
var Modify$3=Constants.IdentityMethods.Modify,Validators={// From ./utils
|
|
472
513
|
// Utility Functions for backwards compatability
|
|
473
514
|
isNumber:isNumber,isFunction:isFunction,isStringOrNumber:isStringOrNumber,// Validator Functions
|
|
474
515
|
isValidAttributeValue:isValidAttributeValue,// Validator Functions
|
|
475
516
|
// Neither null nor undefined can be a valid Key
|
|
476
517
|
isValidKeyValue:function isValidKeyValue(a){return !(!a||isObject(a)||Array.isArray(a)||this.isFunction(a))},removeFalsyIdentityValues:function removeFalsyIdentityValues(a,b){if(!a||!a.userIdentities)return a;var c={},d=__assign({},a.userIdentities);for(var e in a.userIdentities)if(a.userIdentities.hasOwnProperty(e)){var f=a.userIdentities[e];// Check if value is falsy (undefined, false, 0, '', etc.) but not null
|
|
477
|
-
null===f||f||(b.warning("Identity value for '".concat(e,"' is falsy (").concat(f,"). This value will be removed from the request.")),delete d[e]);}return c.userIdentities=d,c},validateIdentities:function validateIdentities(a,b){var c={userIdentities:1,onUserAlias:1,copyUserAttributes:1};if(a){if(b===Modify$
|
|
518
|
+
null===f||f||(b.warning("Identity value for '".concat(e,"' is falsy (").concat(f,"). This value will be removed from the request.")),delete d[e]);}return c.userIdentities=d,c},validateIdentities:function validateIdentities(a,b){var c={userIdentities:1,onUserAlias:1,copyUserAttributes:1};if(a){if(b===Modify$3&&(isObject(a.userIdentities)&&!Object.keys(a.userIdentities).length||!isObject(a.userIdentities)))return {valid:!1,error:Constants.Messages.ValidationMessages.ModifyIdentityRequestUserIdentitiesPresent};for(var d in a)if(a.hasOwnProperty(d)){if(!c[d])return {valid:!1,error:Constants.Messages.ValidationMessages.IdentityRequesetInvalidKey};if("onUserAlias"===d&&!Validators.isFunction(a[d]))return {valid:!1,error:Constants.Messages.ValidationMessages.OnUserAliasType}}if(0===Object.keys(a).length)return {valid:!0};// identityApiData.userIdentities can't be undefined
|
|
478
519
|
if(void 0===a.userIdentities)return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentities};// identityApiData.userIdentities can be null, but if it isn't null or undefined (above conditional), it must be an object
|
|
479
520
|
if(null!==a.userIdentities&&!isObject(a.userIdentities))return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentities};if(isObject(a.userIdentities)&&Object.keys(a.userIdentities).length)for(var e in a.userIdentities)if(a.userIdentities.hasOwnProperty(e)){if(!1===Types.IdentityType.getIdentityType(e))return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentitiesInvalidKey};if("string"!=typeof a.userIdentities[e]&&null!==a.userIdentities[e])return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentitiesInvalidValues}}}return {valid:!0}}};
|
|
480
521
|
|
|
@@ -511,11 +552,13 @@ return !!(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHan
|
|
|
511
552
|
var Messages$7=Constants.Messages,InformationMessages=Messages$7.InformationMessages;var DAYS_IN_MILLISECONDS=86400000;// Partner module IDs for cookie sync configurations
|
|
512
553
|
var PARTNER_MODULE_IDS={AdobeEventForwarder:11,DoubleclickDFP:41,AppNexus:50,Lotame:58,TradeDesk:103,VerizonMedia:155,Rokt:1277};function CookieSyncManager(a){var b=this;// Public
|
|
513
554
|
// Private
|
|
514
|
-
this.attemptCookieSync=function(c,d){var e=a._Store,f
|
|
555
|
+
this.attemptCookieSync=function(c,d){var e,f=a._Store,g=f.pixelConfigurations,h=f.webviewBridgeEnabled;if(c&&!h&&(null===(e=a._CookieConsentManager)||void 0===e||!e.getNoFunctional()))// When noFunctional is true, persistence is not saved, so we cannot track cookie sync
|
|
556
|
+
// dates. Skip cookie sync to avoid running it on every page load.
|
|
557
|
+
{var i=a._Persistence.getPersistence();isEmpty(i)||g.forEach(function(e){var f,g,h=!1,j=e.filteringConsentRuleValues,k=e.pixelUrl,l=e.redirectUrl,m=e.moduleId,// Tells you how often we should do a cookie sync (in days)
|
|
515
558
|
n=e.frequencyCap,o=(j||{}).values;// set requiresConsent to false to start each additional pixel configuration
|
|
516
559
|
// set to true only if filteringConsenRuleValues.values.length exists
|
|
517
560
|
// Filtering rules as defined in UI
|
|
518
|
-
if(!isEmpty(k)&&(isEmpty(o)||(
|
|
561
|
+
if(!isEmpty(k)&&(isEmpty(o)||(h=!0),!(h&&d))&&!(m===PARTNER_MODULE_IDS.Rokt&&a._CookieConsentManager.getNoTargeting()))// For Rokt, block cookie sync when noTargeting privacy flag is true
|
|
519
562
|
// If MPID is new to cookies, we should not try to perform the cookie sync
|
|
520
563
|
// because a cookie sync can only occur once a user either consents or doesn't.
|
|
521
564
|
// we should not check if it's enabled if the user has a blank consent
|
|
@@ -523,33 +566,10 @@ if(!isEmpty(k)&&(isEmpty(o)||(i=!0),!(i&&d))&&!(m===PARTNER_MODULE_IDS.Rokt&&a._
|
|
|
523
566
|
// It is optional but to simplify the code, we add it for all Trade
|
|
524
567
|
// // Desk cookie syncs.
|
|
525
568
|
// Add domain parameter for Trade Desk
|
|
526
|
-
{var p=a._Consent.isEnabledForUserConsent;if(p(j,a.Identity.getCurrentUser())){var q=null!==(g=null===(f=
|
|
569
|
+
{var p=a._Consent.isEnabledForUserConsent;if(p(j,a.Identity.getCurrentUser())){var q=null!==(g=null===(f=i[c])||void 0===f?void 0:f.csd)&&void 0!==g?g:{},r=q[m]||null;if(isLastSyncDateExpired(n,r)){var s=m===PARTNER_MODULE_IDS.TradeDesk?window.location.hostname:void 0,t=createCookieSyncUrl(c,k,l,s);b.performCookieSync(t,m.toString(),c,q);}}}});}},this.performCookieSync=function(b,c,d,e){var f=document.createElement("img");a.Logger.verbose(InformationMessages.CookieSync),f.onload=function(){e[c]=new Date().getTime(),a._Persistence.saveUserCookieSyncDatesToPersistence(d,e);},f.src=b;};}var isLastSyncDateExpired=function(a,b){// If there is no lastSyncDate, then there is no previous cookie sync, so we should sync the cookie
|
|
527
570
|
return !b||new Date().getTime()>new Date(b).getTime()+a*DAYS_IN_MILLISECONDS;// Otherwise, compare the last sync date to determine if it should do a cookie sync again
|
|
528
571
|
};
|
|
529
572
|
|
|
530
|
-
var _a=Constants.IdentityMethods,Identify$2=_a.Identify,Modify$3=_a.Modify,Login$2=_a.Login,Logout$2=_a.Logout;var CACHE_HEADER="x-mp-max-age";var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache
|
|
531
|
-
if(!e){// default the expire timestamp to one day in milliseconds unless a header comes back
|
|
532
|
-
var f=getExpireTimestamp(null===d||void 0===d?void 0:d.cacheMaxAge);a===Login$2||a===Identify$2?cacheIdentityRequest(a,b,f,c,d):a===Modify$3||a===Logout$2?c.purge():void 0;}};var cacheIdentityRequest=function(a,b,c,d,e){var f=e.responseText,g=e.status,h=d.retrieve()||{},i=concatenateIdentities(a,b),j=generateHash(i),k=f.mpid,l=f.is_logged_in;h[j]={responseText:JSON.stringify({mpid:k,is_logged_in:l}),status:g,expireTimestamp:c},d.store(h);};// We need to ensure that identities are concatenated in a deterministic way, so
|
|
533
|
-
// we sort the identities based on their enum.
|
|
534
|
-
// we create an array, set the user identity at the index of the user identity type
|
|
535
|
-
var concatenateIdentities=function(a,b){var c="".concat(a,":").concat("device_application_stamp","=").concat(b.device_application_stamp,";"),d=Object.keys(b).length,e="";// set DAS first since it is not an official identity type
|
|
536
|
-
if(d){var f=[];// create an array where each index is equal to the user identity type
|
|
537
|
-
for(var g in b)if(g==="device_application_stamp")continue;else f[Types.IdentityType.getIdentityType(g)]=b[g];e=f.reduce(function(a,b,c){var d=Types.IdentityType.getIdentityName(c);return "".concat(a).concat(d,"=").concat(b,";")},c);}return e};var hasValidCachedIdentity=function(a,b,c){// There is an edge case where multiple identity calls are taking place
|
|
538
|
-
// before identify fires, so there may not be a cache. See what happens when
|
|
539
|
-
// the ? in idCache is removed to the following test
|
|
540
|
-
// "queued events contain login mpid instead of identify mpid when calling
|
|
541
|
-
// login immediately after mParticle initializes"
|
|
542
|
-
var d=null===c||void 0===c?void 0:c.retrieve();// if there is no cache, then there is no valid cached identity
|
|
543
|
-
if(!d)return !1;var e=concatenateIdentities(a,b),f=generateHash(e);// if cache doesn't have the cacheKey, there is no valid cached identity
|
|
544
|
-
if(!d.hasOwnProperty(f))return !1;// If there is a valid cache key, compare the expireTimestamp to the current time.
|
|
545
|
-
// If the current time is greater than the expireTimestamp, it is not a valid
|
|
546
|
-
// cached identity.
|
|
547
|
-
var g=d[f].expireTimestamp;return !(g<new Date().getTime())};var getCachedIdentity=function(a,b,c){var d=concatenateIdentities(a,b),e=generateHash(d),f=c.retrieve(),g=f?f[e]:null;return {responseText:parseIdentityResponse(g.responseText),expireTimestamp:g.expireTimestamp,status:g.status}};// https://go.mparticle.com/work/SQDSDKS-6079
|
|
548
|
-
var createKnownIdentities=function(a,b){var c={};if(isObject(null===a||void 0===a?void 0:a.userIdentities))for(var d in a.userIdentities)c[d]=a.userIdentities[d];return c.device_application_stamp=b,c};var removeExpiredIdentityCacheDates=function(a){var b=a.retrieve()||{},c=new Date().getTime();// Iterate over the cache and remove any key/value pairs that are expired
|
|
549
|
-
for(var d in b)b[d].expireTimestamp<c&&delete b[d];a.store(b);};var tryCacheIdentity=function(a,b,c,d,e,f,g){// https://go.mparticle.com/work/SQDSDKS-6095
|
|
550
|
-
var h=hasValidCachedIdentity(g,a,b);// If Identity is cached, then immediately parse the identity response
|
|
551
|
-
if(h){var i=getCachedIdentity(g,a,b);return c(i,d,e,f,g,a,!0),!0}return !1};var getExpireTimestamp=function(a){return void 0===a&&(a=ONE_DAY_IN_SECONDS),new Date().getTime()+a*MILLIS_IN_ONE_SEC},parseIdentityResponse=function(a){return a?JSON.parse(a):{}};var hasIdentityRequestChanged=function(a,b){if(!a||!(null!==b&&void 0!==b)||!b.userIdentities)return !1;var c=a.getUserIdentities().userIdentities,d=b.userIdentities;return JSON.stringify(c)!==JSON.stringify(d)};
|
|
552
|
-
|
|
553
573
|
var Messages$6=Constants.Messages;function SessionManager(a){/**
|
|
554
574
|
* Checks if the session has expired based on the last event timestamp
|
|
555
575
|
* @param lastEventTimestamp - Unix timestamp in milliseconds of the last event
|
|
@@ -560,9 +580,9 @@ var Messages$6=Constants.Messages;function SessionManager(a){/**
|
|
|
560
580
|
* - Logs a SessionEnd event
|
|
561
581
|
* - Nullifies the session ID and related data
|
|
562
582
|
* - Resets the time-on-site timer
|
|
563
|
-
*/function c(){var b;a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.nullifySession(),null===(b=a._timeOnSiteTimer)||void 0===b?void 0:b.resetTimer();}var d=this;this.initialize=function(){if(a._Store.sessionId){var
|
|
583
|
+
*/function c(){var b;a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.nullifySession(),null===(b=a._timeOnSiteTimer)||void 0===b?void 0:b.resetTimer();}var d=this;this.initialize=function(){var c;if(a._Store.sessionId){var e=a._Store,f=e.dateLastEventSent,g=e.SDKConfig,h=g.sessionTimeout;if(b(null===f||void 0===f?void 0:f.getTime(),h))d.endSession(),d.startNewSession();else {// https://go.mparticle.com/work/SQDSDKS-6045
|
|
564
584
|
// https://go.mparticle.com/work/SQDSDKS-6323
|
|
565
|
-
var
|
|
585
|
+
var i=a.Identity.getCurrentUser(),j=g.identifyRequest,k=(null===(c=a._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(a._Store);!k&&hasIdentityRequestChanged(i,j)&&(a.Identity.identify(j,g.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null);}}else d.startNewSession();},this.getSession=function(){return a.Logger.warning(generateDeprecationMessage("SessionManager.getSession()",!1,"SessionManager.getSessionId()")),this.getSessionId()},this.getSessionId=function(){return a._Store.sessionId},this.startNewSession=function(){var b;if(a.Logger.verbose(Messages$6.InformationMessages.StartingNewSession),a._Helpers.canLog()){a._Store.sessionId=a._Helpers.generateUniqueId().toUpperCase();var c=a.Identity.getCurrentUser(),e=c?c.getMPID():null;if(e&&(a._Store.currentSessionMPIDs=[e]),!a._Store.sessionStartDate){var f=new Date;a._Store.sessionStartDate=f,a._Store.dateLastEventSent=f;}d.setSessionTimer();var g=(null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())&&!hasExplicitIdentifier(a._Store);a._Store.identifyCalled||g||(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null),a._Events.logEvent({messageType:Types.MessageType.SessionStart});}else a.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);},this.endSession=function(e){var f,g,h,i;if(a.Logger.verbose(Messages$6.InformationMessages.StartingEndSession),e)return void c();if(!a._Helpers.canLog())return a.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession),void(null===(f=a._timeOnSiteTimer)||void 0===f?void 0:f.resetTimer());var j=a._Persistence.getPersistence();if(!j||j.gs&&!j.gs.sid)return a.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd),void(null===(g=a._timeOnSiteTimer)||void 0===g?void 0:g.resetTimer());// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
|
|
566
586
|
if(j.gs.sid&&a._Store.sessionId!==j.gs.sid&&(a._Store.sessionId=j.gs.sid),null===(h=null===j||void 0===j?void 0:j.gs)||void 0===h?void 0:h.les){var k=a._Store.SDKConfig.sessionTimeout;b(j.gs.les,k)?c():(d.setSessionTimer(),null===(i=a._timeOnSiteTimer)||void 0===i?void 0:i.resetTimer());}},this.setSessionTimer=function(){var b=6e4*a._Store.SDKConfig.sessionTimeout;a._Store.globalTimer=window.setTimeout(function(){d.endSession();},b);},this.resetSessionTimer=function(){a._Store.webviewBridgeEnabled||(!a._Store.sessionId&&d.startNewSession(),d.clearSessionTimeout(),d.setSessionTimer()),d.startNewSessionIfNeeded();},this.clearSessionTimeout=function(){clearTimeout(a._Store.globalTimer);},this.startNewSessionIfNeeded=function(){if(!a._Store.webviewBridgeEnabled){var b=a._Persistence.getPersistence();!a._Store.sessionId&&b&&(b.sid?a._Store.sessionId=b.sid:d.startNewSession());}};}
|
|
567
587
|
|
|
568
588
|
var Messages$5=Constants.Messages;function Ecommerce(a){var b=this;// https://go.mparticle.com/work/SQDSDKS-4801
|
|
@@ -575,8 +595,8 @@ this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty(
|
|
|
575
595
|
return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(d=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce,sourceMessageId:null===c||void 0===c?void 0:c.sourceMessageId}),d.EventName="eCommerce - ",d.CurrencyCode=a._Store.currencyCode,d.ShoppingCart=[],d.CustomFlags=e(d.CustomFlags,b),d):(a.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent),null)},this.sanitizeAmount=function(b,c){if(!a._Helpers.Validators.isStringOrNumber(b)){var d=[c,"must be of type number. A",_typeof$1(b),"was passed. Converting to 0"].join(" ");return a.Logger.warning(d),0}// if amount is a string, it will be parsed into a number if possible, or set to 0
|
|
576
596
|
return a._Helpers.parseNumber(b)};}
|
|
577
597
|
|
|
578
|
-
var ForegroundTimeTracker=/** @class */function(){function a(a){this.isTrackerActive=!1,this.localStorageName="",this.startTime=0,this.totalTime=0,this.localStorageName="mprtcl-tos-".concat(a),this.timerVault=new LocalStorageVault(this.localStorageName),this.loadTimeFromStorage(),this.addHandlers(),!1===document.hidden&&this.startTracking();}return a.prototype.addHandlers=function(){var a=this;// when user switches tabs or minimizes the window
|
|
579
|
-
document.addEventListener("visibilitychange",function(){return a.handleVisibilityChange()}),window.addEventListener("blur",function(){return a.handleWindowBlur()}),window.addEventListener("focus",function(){return a.handleWindowFocus()}),window.addEventListener("storage",function(b){return a.syncAcrossTabs(b)}),window.addEventListener("beforeunload",function(){return a.updateTimeInPersistence()});},a.prototype.handleVisibilityChange=function(){document.hidden?this.stopTracking():this.startTracking();},a.prototype.handleWindowBlur=function(){this.isTrackerActive&&this.stopTracking();},a.prototype.handleWindowFocus=function(){this.isTrackerActive||this.startTracking();},a.prototype.syncAcrossTabs=function(a){if(a.key===this.localStorageName&&null!==a.newValue){var b=parseFloat(a.newValue)||0;this.totalTime=b;}},a.prototype.updateTimeInPersistence=function(){this.isTrackerActive&&this.timerVault.store(Math.round(this.totalTime));},a.prototype.loadTimeFromStorage=function(){var a=this.timerVault.retrieve();isNumber(a)&&null!==a&&(this.totalTime=a);},a.prototype.startTracking=function(){document.hidden||(this.startTime=Math.floor(performance.now()),this.isTrackerActive=!0);},a.prototype.stopTracking=function(){this.isTrackerActive&&(this.setTotalTime(),this.updateTimeInPersistence(),this.isTrackerActive=!1);},a.prototype.setTotalTime=function(){if(this.isTrackerActive){var a=Math.floor(performance.now());this.totalTime+=a-this.startTime,this.startTime=a;}},a.prototype.getTimeInForeground=function(){return this.setTotalTime(),this.updateTimeInPersistence(),this.totalTime},a.prototype.resetTimer=function(){this.totalTime=0,this.updateTimeInPersistence();},a}();
|
|
598
|
+
var ForegroundTimeTracker=/** @class */function(){function a(a,b){void 0===b&&(b=!1),this.noFunctional=b,this.isTrackerActive=!1,this.localStorageName="",this.startTime=0,this.totalTime=0,this.localStorageName="mprtcl-tos-".concat(a),this.timerVault=new LocalStorageVault(this.localStorageName),this.noFunctional||this.loadTimeFromStorage(),this.addHandlers(),!1===document.hidden&&this.startTracking();}return a.prototype.addHandlers=function(){var a=this;// when user switches tabs or minimizes the window
|
|
599
|
+
document.addEventListener("visibilitychange",function(){return a.handleVisibilityChange()}),window.addEventListener("blur",function(){return a.handleWindowBlur()}),window.addEventListener("focus",function(){return a.handleWindowFocus()}),window.addEventListener("storage",function(b){return a.syncAcrossTabs(b)}),window.addEventListener("beforeunload",function(){return a.updateTimeInPersistence()});},a.prototype.handleVisibilityChange=function(){document.hidden?this.stopTracking():this.startTracking();},a.prototype.handleWindowBlur=function(){this.isTrackerActive&&this.stopTracking();},a.prototype.handleWindowFocus=function(){this.isTrackerActive||this.startTracking();},a.prototype.syncAcrossTabs=function(a){if(a.key===this.localStorageName&&null!==a.newValue){var b=parseFloat(a.newValue)||0;this.totalTime=b;}},a.prototype.updateTimeInPersistence=function(){this.isTrackerActive&&!this.noFunctional&&this.timerVault.store(Math.round(this.totalTime));},a.prototype.loadTimeFromStorage=function(){var a=this.timerVault.retrieve();isNumber(a)&&null!==a&&(this.totalTime=a);},a.prototype.startTracking=function(){document.hidden||(this.startTime=Math.floor(performance.now()),this.isTrackerActive=!0);},a.prototype.stopTracking=function(){this.isTrackerActive&&(this.setTotalTime(),this.updateTimeInPersistence(),this.isTrackerActive=!1);},a.prototype.setTotalTime=function(){if(this.isTrackerActive){var a=Math.floor(performance.now());this.totalTime+=a-this.startTime,this.startTime=a;}},a.prototype.getTimeInForeground=function(){return this.setTotalTime(),this.updateTimeInPersistence(),this.totalTime},a.prototype.resetTimer=function(){this.totalTime=0,this.updateTimeInPersistence();},a}();
|
|
580
600
|
|
|
581
601
|
function createSDKConfig(a){// TODO: Refactor to create a default config object
|
|
582
602
|
var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultBaseUrls)b[c]=Constants.DefaultBaseUrls[c];// Always initialize flags to at least an empty object to prevent undefined access
|
|
@@ -584,11 +604,8 @@ return b.flags=b.flags||{},b}// TODO: Merge this with SDKStoreApi in sdkRuntimeM
|
|
|
584
604
|
function Store(a,b,c){var d=this,e=b._Helpers.createMainStorageName,f=b._NativeSdkHelpers.isWebviewEnabled,g={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,identityCallFailed:!1,identifyRequestCount:0,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},roktAccountId:null,integrationName:null,// Placeholder for in-memory persistence model
|
|
585
605
|
persistenceData:{gs:{}}};for(var h in g)this[h]=g[h];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&returnConvertedBoolean(a.isDevelopmentMode);var i=processBaseUrls(a,this.SDKConfig.flags,c);for(var j in i)this.SDKConfig[j]=i[j];if(this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var k=a.identityCallback;b._Helpers.Validators.isFunction(k)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof$1(k)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var l=a.dataPlan;l.planId&&(isDataPlanSlug(l.planId)?this.SDKConfig.dataPlan.PlanId=l.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),l.planVersion&&(isNumber(l.planVersion)?this.SDKConfig.dataPlan.PlanVersion=l.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var m=a.dataPlanOptions;m.hasOwnProperty("dataPlanVersion")&&m.hasOwnProperty("blockUserAttributes")&&m.hasOwnProperty("blockEventAttributes")&&m.hasOwnProperty("blockEvents")&&m.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this._getFromPersistence=function(a,b){return a?(d.syncPersistenceData(),d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a][b]?d.persistenceData[a][b]:null):null},this._setPersistence=function(a,c,e){var f;a&&(d.syncPersistenceData(),d.persistenceData&&(d.persistenceData[a]?d.persistenceData[a][c]=e:d.persistenceData[a]=(f={},f[c]=e,f),isObject(d.persistenceData[a][c])&&isEmpty(d.persistenceData[a][c])&&delete d.persistenceData[a][c],b._Persistence.savePersistence(d.persistenceData)));},this.hasInvalidIdentifyRequest=function(){var a=d.SDKConfig.identifyRequest;return isObject(a)&&isObject(a.userIdentities)&&isEmpty(a.userIdentities)||!a},this.getConsentState=function(a){var c=b._Consent.ConsentSerialization.fromMinifiedJsonObject,e=d._getFromPersistence(a,"con");return isEmpty(e)?null:c(e)},this.setConsentState=function(a,c){var e=b._Consent.ConsentSerialization.toMinifiedJsonObject;// If ConsentState is null, we assume the intent is to clear out the consent state
|
|
586
606
|
(c||null===c)&&d._setPersistence(a,"con",e(c));},this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.getFirstSeenTime=function(a){return d._getFromPersistence(a,"fst")},this.setFirstSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"fst",c);}},this.getLastSeenTime=function(a){if(!a)return null;// https://go.mparticle.com/work/SQDSDKS-6315
|
|
587
|
-
var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d._getFromPersistence(a,"lst")},this.setLastSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"lst",c);}},this.getLocalSessionAttributes=function(){return d.localSessionAttributes||{}},this.setLocalSessionAttribute=function(a,c){var e;d.localSessionAttributes[a]=c,d.persistenceData.gs.lsa=__assign(__assign({},d.persistenceData.gs.lsa||{}),(e={},e[a]=c,e)),b._Persistence.savePersistence(d.persistenceData);},this.syncPersistenceData=function(){var a=b._Persistence.getPersistence();d.persistenceData=b._Helpers.extend({},d.persistenceData,a);},this.getUserAttributes=function(a){return d._getFromPersistence(a,"ua")||{}},this.setUserAttributes=function(a,b){return d._setPersistence(a,"ua",b)},this.getUserIdentities=function(a){return d._getFromPersistence(a,"ui")||{}},this.setUserIdentities=function(a,b){d._setPersistence(a,"ui",b);},this.getRoktAccountId=function(){return d.roktAccountId},this.setRoktAccountId=function(a){d.roktAccountId=a;},this.getIntegrationName=function(){return d.integrationName},this.setIntegrationName=function(a){d.integrationName=a;},this.addMpidToSessionHistory=function(a,b){var c=d.currentSessionMPIDs.indexOf(a);return a&&b!==a&&0>c?void d.currentSessionMPIDs.push(a):void(0<=c&&(d.currentSessionMPIDs=moveElementToEnd(d.currentSessionMPIDs,c)))},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionStartDate=null,d.sessionAttributes={},d.localSessionAttributes={},b._Persistence.update();},this.processConfig=function(a){var g=a.workspaceToken,
|
|
588
|
-
//
|
|
589
|
-
// https://go.mparticle.com/work/SQDSDKS-6317
|
|
590
|
-
// Only update flags if the config actually has flags (don't overwrite with empty object)
|
|
591
|
-
a.flags&&(d.SDKConfig.flags=processFlags(a));var i=processBaseUrls(a,d.SDKConfig.flags,c);for(var j in i)d.SDKConfig[j]=i[j];g?(d.SDKConfig.workspaceToken=g,b._timeOnSiteTimer=new ForegroundTimeTracker(g)):b.Logger.warning("You should have a workspaceToken on your config object for security purposes."),d.storageName=e(g),d.SDKConfig.requiredWebviewBridgeName=h||g,d.webviewBridgeEnabled=f(d.SDKConfig.requiredWebviewBridgeName,d.SDKConfig.minWebviewBridgeVersion),d.configurationLoaded=!0;};}// https://go.mparticle.com/work/SQDSDKS-6317
|
|
607
|
+
var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d._getFromPersistence(a,"lst")},this.setLastSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"lst",c);}},this.getLocalSessionAttributes=function(){return d.localSessionAttributes||{}},this.setLocalSessionAttribute=function(a,c){var e;d.localSessionAttributes[a]=c,d.persistenceData.gs.lsa=__assign(__assign({},d.persistenceData.gs.lsa||{}),(e={},e[a]=c,e)),b._Persistence.savePersistence(d.persistenceData);},this.syncPersistenceData=function(){var a=b._Persistence.getPersistence();d.persistenceData=b._Helpers.extend({},d.persistenceData,a);},this.getUserAttributes=function(a){return d._getFromPersistence(a,"ua")||{}},this.setUserAttributes=function(a,b){return d._setPersistence(a,"ua",b)},this.getUserIdentities=function(a){return d._getFromPersistence(a,"ui")||{}},this.setUserIdentities=function(a,b){d._setPersistence(a,"ui",b);},this.getRoktAccountId=function(){return d.roktAccountId},this.setRoktAccountId=function(a){d.roktAccountId=a;},this.getIntegrationName=function(){return d.integrationName},this.setIntegrationName=function(a){d.integrationName=a;},this.addMpidToSessionHistory=function(a,b){var c=d.currentSessionMPIDs.indexOf(a);return a&&b!==a&&0>c?void d.currentSessionMPIDs.push(a):void(0<=c&&(d.currentSessionMPIDs=moveElementToEnd(d.currentSessionMPIDs,c)))},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionStartDate=null,d.sessionAttributes={},d.localSessionAttributes={},b._Persistence.update();},this.processConfig=function(a){var g,h=a.workspaceToken,i=a.requiredWebviewBridgeName;a.flags&&(d.SDKConfig.flags=processFlags(a));var j=processBaseUrls(a,d.SDKConfig.flags,c);for(var k in j)d.SDKConfig[k]=j[k];if(h){d.SDKConfig.workspaceToken=h;var l=!0===(null===(g=null===a||void 0===a?void 0:a.launcherOptions)||void 0===g?void 0:g.noFunctional);b._timeOnSiteTimer=new ForegroundTimeTracker(h,l);}else b.Logger.warning("You should have a workspaceToken on your config object for security purposes.");// add a new function to apply items to the store that require config to be returned
|
|
608
|
+
d.storageName=e(h),d.SDKConfig.requiredWebviewBridgeName=i||h,d.webviewBridgeEnabled=f(d.SDKConfig.requiredWebviewBridgeName,d.SDKConfig.minWebviewBridgeVersion),d.configurationLoaded=!0;};}// https://go.mparticle.com/work/SQDSDKS-6317
|
|
592
609
|
function processFlags(a){var b={},c=Constants.FeatureFlags,d=c.ReportBatching,e=c.EventBatchingIntervalMillis,f=c.OfflineStorage,g=c.DirectUrlRouting,h=c.CacheIdentity,i=c.AudienceAPI,j=c.CaptureIntegrationSpecificIds,k=c.CaptureIntegrationSpecificIdsV2,l=c.AstBackgroundEvents;return a.flags?(b[d]=a.flags[d]||!1,b[e]=parseNumber(a.flags[e])||Constants.DefaultConfig.uploadInterval,b[f]=a.flags[f]||"0",b[g]="True"===a.flags[g],b[h]="True"===a.flags[h],b[i]="True"===a.flags[i],b[j]="True"===a.flags[j],b[k]=a.flags[k]||"none",b[l]="True"===a.flags[l],b):{};// https://go.mparticle.com/work/SQDSDKS-6317
|
|
593
610
|
// Passed in config flags take priority over defaults
|
|
594
611
|
}function processBaseUrls(a,b,c){// an API key is not present in a webview only mode. In this case, no baseUrls are needed
|
|
@@ -614,7 +631,7 @@ for(var g in c){// Any custom endpoints passed to mpConfig will take priority ov
|
|
|
614
631
|
// mapping to the silo. The most common use case is a customer provided CNAME.
|
|
615
632
|
if("configUrl"==g||"loggingUrl"===g||"errorUrl"===g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d}
|
|
616
633
|
|
|
617
|
-
var Logger=/** @class */function(){function a(a,b){var c,d;this.logLevel=null!==(c=a.logLevel)&&void 0!==c?c:LogLevelType.Warning,this.logger=null!==(d=a.logger)&&void 0!==d?d:new ConsoleLogger,this.reportingLogger=b;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a,b){var c;this.logLevel===LogLevelType.None||this.logger.error&&(this.logger.error(a),b&&(null===(c=this.reportingLogger)||void 0===c?void 0:c.error(a,b)));},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}();
|
|
634
|
+
var Logger=/** @class */function(){function a(a,b){var c,d;this.logLevel=null!==(c=a.logLevel)&&void 0!==c?c:LogLevelType.Warning,this.logger=null!==(d=a.logger)&&void 0!==d?d:new ConsoleLogger,this.reportingLogger=b;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a,b){var c;this.logLevel===LogLevelType.None||this.logger.error&&(this.logger.error(a),b&&(null===(c=this.reportingLogger)||void 0===c?void 0:c.error(a,b)));},a.prototype.isVerbose=function(){return this.logLevel===LogLevelType.Verbose},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}();
|
|
618
635
|
|
|
619
636
|
var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function _Persistence(a){function b(b){var c=a._Store;return b.gs.sid=c.sessionId,b.gs.ie=c.isEnabled,b.gs.sa=c.sessionAttributes,b.gs.lsa=c.localSessionAttributes,b.gs.ss=c.serverSettings,b.gs.dt=c.devToken,b.gs.les=c.dateLastEventSent?c.dateLastEventSent.getTime():null,b.gs.av=c.SDKConfig.appVersion,b.gs.cgid=c.clientId,b.gs.das=c.deviceId,b.gs.c=c.context,b.gs.ssd=c.sessionStartDate?c.sessionStartDate.getTime():0,b.gs.ia=c.integrationAttributes,b}function c(a){localStorage.removeItem(a);}function d(a,b,c){return f.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}var f=this;// https://go.mparticle.com/work/SQDSDKS-5022
|
|
620
637
|
// https://go.mparticle.com/work/SQDSDKS-6045
|
|
@@ -654,13 +671,16 @@ this.useLocalStorage=function(){return !a._Store.SDKConfig.useCookieStorage&&a._
|
|
|
654
671
|
// Determine if there is any data in cookies or localStorage to figure out if it is the first time the browser is loading mParticle
|
|
655
672
|
// https://go.mparticle.com/work/SQDSDKS-6046
|
|
656
673
|
// Stores all non-current user MPID information into the store
|
|
657
|
-
for(var g in d||e?a._Store.isFirstRun=!1:(a._Store.isFirstRun=!0,a._Store.mpid=0),a._Store.isLocalStorageAvailable||(a._Store.SDKConfig.useCookieStorage=!0),a._Store.isLocalStorageAvailable?(b=window.localStorage,a._Store.SDKConfig.useCookieStorage?(d?(c=e?a._Helpers.extend(!1,d,e):d,b.removeItem(a._Store.storageName)):e&&(c=e),f.storeDataInMemory(c)):e?(c=d?a._Helpers.extend(!1,d,e):e,f.storeDataInMemory(c),f.expireCookies(a._Store.storageName)):f.storeDataInMemory(d)):f.storeDataInMemory(e),c)c.hasOwnProperty(g)&&(SDKv2NonMPIDCookieKeys[g]||(a._Store.nonCurrentUserMPIDs[g]=c[g]));f.update();}catch(b){f.useLocalStorage()&&a._Store.isLocalStorageAvailable?localStorage.removeItem(a._Store.storageName):f.expireCookies(a._Store.storageName),a.Logger.error("Error initializing storage: "+b);}},this.update=function(){a._Store.webviewBridgeEnabled||(a._Store.SDKConfig.useCookieStorage&&f.setCookie(),f.setLocalStorage());},this.storeDataInMemory=function(b,c){try{b?(a._Store.mpid=c?c:b.cu||0,b.gs=b.gs||{},a._Store.sessionId=b.gs.sid||a._Store.sessionId,a._Store.isEnabled="undefined"==typeof b.gs.ie?a._Store.isEnabled:b.gs.ie,a._Store.sessionAttributes=b.gs.sa||a._Store.sessionAttributes,a._Store.localSessionAttributes=b.gs.lsa||a._Store.localSessionAttributes,a._Store.serverSettings=b.gs.ss||a._Store.serverSettings,a._Store.devToken=a._Store.devToken||b.gs.dt,a._Store.SDKConfig.appVersion=a._Store.SDKConfig.appVersion||b.gs.av,a._Store.clientId=b.gs.cgid||a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||b.gs.das||a._Helpers.generateUniqueId(),a._Store.integrationAttributes=b.gs.ia||{},a._Store.context=b.gs.c||a._Store.context,a._Store.currentSessionMPIDs=b.gs.csm||a._Store.currentSessionMPIDs,a._Store.isLoggedIn=!0===b.l,b.gs.les&&(a._Store.dateLastEventSent=new Date(b.gs.les)),a._Store.sessionStartDate=b.gs.ssd?new Date(b.gs.ssd):new Date,b=c?b[c]:b[b.cu]):(a.Logger.verbose(Messages$4.InformationMessages.CookieNotFound),a._Store.clientId=a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||a._Helpers.generateUniqueId());}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.determineLocalStorageAvailability=function(a){var b;window.mParticle&&window.mParticle._forceNoLocalStorage&&(a=void 0);try{return a.setItem("mparticle","test"),b="test"===a.getItem("mparticle"),a.removeItem("mparticle"),b&&a}catch(a){return !1}},this.setLocalStorage=function(){
|
|
674
|
+
for(var g in d||e?a._Store.isFirstRun=!1:(a._Store.isFirstRun=!0,a._Store.mpid=0),a._Store.isLocalStorageAvailable||(a._Store.SDKConfig.useCookieStorage=!0),a._Store.isLocalStorageAvailable?(b=window.localStorage,a._Store.SDKConfig.useCookieStorage?(d?(c=e?a._Helpers.extend(!1,d,e):d,b.removeItem(a._Store.storageName)):e&&(c=e),f.storeDataInMemory(c)):e?(c=d?a._Helpers.extend(!1,d,e):e,f.storeDataInMemory(c),f.expireCookies(a._Store.storageName)):f.storeDataInMemory(d)):f.storeDataInMemory(e),c)c.hasOwnProperty(g)&&(SDKv2NonMPIDCookieKeys[g]||(a._Store.nonCurrentUserMPIDs[g]=c[g]));f.update();}catch(b){f.useLocalStorage()&&a._Store.isLocalStorageAvailable?localStorage.removeItem(a._Store.storageName):f.expireCookies(a._Store.storageName),a.Logger.error("Error initializing storage: "+b);}},this.update=function(){a._Store.webviewBridgeEnabled||(a._Store.SDKConfig.useCookieStorage&&f.setCookie(),f.setLocalStorage());},this.storeDataInMemory=function(b,c){try{b?(a._Store.mpid=c?c:b.cu||0,b.gs=b.gs||{},a._Store.sessionId=b.gs.sid||a._Store.sessionId,a._Store.isEnabled="undefined"==typeof b.gs.ie?a._Store.isEnabled:b.gs.ie,a._Store.sessionAttributes=b.gs.sa||a._Store.sessionAttributes,a._Store.localSessionAttributes=b.gs.lsa||a._Store.localSessionAttributes,a._Store.serverSettings=b.gs.ss||a._Store.serverSettings,a._Store.devToken=a._Store.devToken||b.gs.dt,a._Store.SDKConfig.appVersion=a._Store.SDKConfig.appVersion||b.gs.av,a._Store.clientId=b.gs.cgid||a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||b.gs.das||a._Helpers.generateUniqueId(),a._Store.integrationAttributes=b.gs.ia||{},a._Store.context=b.gs.c||a._Store.context,a._Store.currentSessionMPIDs=b.gs.csm||a._Store.currentSessionMPIDs,a._Store.isLoggedIn=!0===b.l,b.gs.les&&(a._Store.dateLastEventSent=new Date(b.gs.les)),a._Store.sessionStartDate=b.gs.ssd?new Date(b.gs.ssd):new Date,b=c?b[c]:b[b.cu]):(a.Logger.verbose(Messages$4.InformationMessages.CookieNotFound),a._Store.clientId=a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||a._Helpers.generateUniqueId());}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.determineLocalStorageAvailability=function(a){var b;window.mParticle&&window.mParticle._forceNoLocalStorage&&(a=void 0);try{return a.setItem("mparticle","test"),b="test"===a.getItem("mparticle"),a.removeItem("mparticle"),b&&a}catch(a){return !1}},this.setLocalStorage=function(){var c;if(a._Store.isLocalStorageAvailable&&!(null!==(c=a._CookieConsentManager)&&void 0!==c&&c.getNoFunctional()))// Block mprtcl-v4 localStorage when noFunctional is true
|
|
675
|
+
{var d=a._Store.storageName,e=f.getLocalStorage()||{},g=a.Identity.getCurrentUser(),h=g?g.getMPID():null;if(!a._Store.SDKConfig.useCookieStorage){e.gs=e.gs||{},e.l=a._Store.isLoggedIn?1:0,a._Store.sessionId&&(e.gs.csm=a._Store.currentSessionMPIDs),e.gs.ie=a._Store.isEnabled,h&&(e.cu=h),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(e=a._Helpers.extend({},e,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),e=b(e);try{window.localStorage.setItem(encodeURIComponent(d),f.encodePersistence(JSON.stringify(e)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){if(!a._Store.isLocalStorageAvailable)return null;var b,c=a._Store.storageName,d=f.decodePersistence(window.localStorage.getItem(c)),e={};if(d)for(b in d=JSON.parse(d),d)d.hasOwnProperty(b)&&(e[b]=d[b]);return Object.keys(e).length?e:null},this.expireCookies=function(a){var b,c,d,e=new Date;d=f.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),document.cookie=a+"="+b+"; path=/"+c;},this.getCookie=function(){var b,c,d,e,g,h,j=a._Store.storageName,k=j?void 0:{};a.Logger.verbose(Messages$4.InformationMessages.CookieSearch);try{b=window.document.cookie.split("; ");}catch(b){return a.Logger.verbose("Unable to parse undefined cookie"),null}for(c=0,d=b.length;c<d;c++){try{e=b[c].split("="),g=e.shift(),h=e.join("=");}catch(b){a.Logger.verbose("Unable to parse cookie: "+g+". Skipping.");}if(j&&j===g){k=a._Helpers.converted(h);break}j||(k[g]=a._Helpers.converted(h));}return k?(a.Logger.verbose(Messages$4.InformationMessages.CookieFound),JSON.parse(f.decodePersistence(k))):null},this.setCookie=function(){var c;// Block mprtcl-v4 cookies when noFunctional is true
|
|
676
|
+
if(!(null!==(c=a._CookieConsentManager)&&void 0!==c&&c.getNoFunctional())){var d,e=a.Identity.getCurrentUser();e&&(d=e.getMPID());var g,h,i,j=new Date,k=a._Store.storageName,l=f.getCookie()||{},m=new Date(j.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toGMTString();g=f.getCookieDomain(),h=""===g?"":";domain="+g,l.gs=l.gs||{},a._Store.sessionId&&(l.gs.csm=a._Store.currentSessionMPIDs),d&&(l.cu=d),l.l=a._Store.isLoggedIn?1:0,l=b(l),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(l=a._Helpers.extend({},l,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),i=f.reduceAndEncodePersistence(l,m,h,a._Store.SDKConfig.maxCookieSize),a.Logger.verbose(Messages$4.InformationMessages.CookieSet),window.document.cookie=encodeURIComponent(k)+"="+i;}},this.reduceAndEncodePersistence=function(b,c,e,f){var g,h=b.gs.csm?b.gs.csm:[];// Comment 1 above
|
|
658
677
|
if(!h.length)for(var j in b)b.hasOwnProperty(j)&&(g=d(b,c,e),g.length>f&&!SDKv2NonMPIDCookieKeys[j]&&j!==b.cu&&delete b[j]);else {// Comment 2 above - First create an object of all MPIDs on the cookie
|
|
659
678
|
var k={};for(var l in b)b.hasOwnProperty(l)&&(SDKv2NonMPIDCookieKeys[l]||l===b.cu||(k[l]=1));// Comment 2a above
|
|
660
679
|
if(Object.keys(k).length)for(var m in k)g=d(b,c,e),g.length>f&&k.hasOwnProperty(m)&&-1===h.indexOf(m)&&delete b[m];// Comment 2b above
|
|
661
680
|
for(var n,o=0;o<h.length&&(g=d(b,c,e),g.length>f);o++)n=h[o],b[n]?(a.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of "+f+". Removing from cookie the earliest logged in MPID containing: "+JSON.stringify(b[n],0,2)),delete b[n]):a.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of "+f+". We recommend using a maxCookieSize of 1500.");}return g},this.findPrevCookiesBasedOnUI=function(b){var c,d=a._Persistence.getPersistence();if(b)for(var e in b.userIdentities)if(d&&Object.keys(d).length)for(var g in d)// any value in persistence that has an MPID key will be an MPID to search through
|
|
662
681
|
// other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched
|
|
663
|
-
if(d[g].mpid){var h=d[g].ui;for(var i in h)if(e===i&&b.userIdentities[e]===h[i]){c=g;break}}c&&f.storeDataInMemory(d,c);},this.encodePersistence=function(b){for(var c in b=JSON.parse(b),b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]?Array.isArray(b.gs[c])&&b.gs[c].length||a._Helpers.isObject(b.gs[c])&&Object.keys(b.gs[c]).length?b.gs[c]=Base64.encode(JSON.stringify(b.gs[c])):delete b.gs[c]:delete b.gs[c]:"ie"===c?b.gs[c]=b.gs[c]?1:0:!b.gs[c]&&delete b.gs[c]);for(var d in b)if(b.hasOwnProperty(d)&&!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&(a._Helpers.isObject(b[d][c])&&Object.keys(b[d][c]).length?b[d][c]=Base64.encode(JSON.stringify(b[d][c])):delete b[d][c]);return createCookieString(JSON.stringify(b))},this.decodePersistence=function(b){try{if(b){if(b=JSON.parse(revertCookieString(b)),a._Helpers.isObject(b)&&Object.keys(b).length){for(var c in b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]=JSON.parse(Base64.decode(b.gs[c])):"ie"===c&&(b.gs[c]=!!b.gs[c]));for(var d in b)if(b.hasOwnProperty(d))if(!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&b[d][c].length&&(b[d][c]=JSON.parse(Base64.decode(b[d][c])));else "l"===d&&(b[d]=!!b[d]);}return JSON.stringify(b)}}catch(b){a.Logger.error("Problem with decoding cookie",b);}},this.getCookieDomain=function(){if(a._Store.SDKConfig.cookieDomain)return a._Store.SDKConfig.cookieDomain;var b=f.getDomain(document,location.hostname);return ""===b?"":"."+b},this.getDomain=function(a,b){var c,d,e=b.split(".");for(c=e.length-1;0<=c;c--)if(d=e.slice(c).join("."),a.cookie="mptest=cookie;domain=."+d+";",-1<a.cookie.indexOf("mptest=cookie"))return a.cookie="mptest=;domain=."+d+";expires=Thu, 01 Jan 1970 00:00:01 GMT;",d;return ""},this.saveUserCookieSyncDatesToPersistence=function(a,b){if(b){var c=f.getPersistence();c&&(c[a]?c[a].csd=b:c[a]={csd:b}),f.savePersistence(c);}},this.swapCurrentUser=function(a,b,c){if(a&&b&&a!==b){var d=f.getPersistence();d&&(d.cu=b,d.gs.csm=c,f.savePersistence(d));}},this.savePersistence=function(b){var c
|
|
682
|
+
if(d[g].mpid){var h=d[g].ui;for(var i in h)if(e===i&&b.userIdentities[e]===h[i]){c=g;break}}c&&f.storeDataInMemory(d,c);},this.encodePersistence=function(b){for(var c in b=JSON.parse(b),b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]?Array.isArray(b.gs[c])&&b.gs[c].length||a._Helpers.isObject(b.gs[c])&&Object.keys(b.gs[c]).length?b.gs[c]=Base64.encode(JSON.stringify(b.gs[c])):delete b.gs[c]:delete b.gs[c]:"ie"===c?b.gs[c]=b.gs[c]?1:0:!b.gs[c]&&delete b.gs[c]);for(var d in b)if(b.hasOwnProperty(d)&&!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&(a._Helpers.isObject(b[d][c])&&Object.keys(b[d][c]).length?b[d][c]=Base64.encode(JSON.stringify(b[d][c])):delete b[d][c]);return createCookieString(JSON.stringify(b))},this.decodePersistence=function(b){try{if(b){if(b=JSON.parse(revertCookieString(b)),a._Helpers.isObject(b)&&Object.keys(b).length){for(var c in b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]=JSON.parse(Base64.decode(b.gs[c])):"ie"===c&&(b.gs[c]=!!b.gs[c]));for(var d in b)if(b.hasOwnProperty(d))if(!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&b[d][c].length&&(b[d][c]=JSON.parse(Base64.decode(b[d][c])));else "l"===d&&(b[d]=!!b[d]);}return JSON.stringify(b)}}catch(b){a.Logger.error("Problem with decoding cookie",b);}},this.getCookieDomain=function(){if(a._Store.SDKConfig.cookieDomain)return a._Store.SDKConfig.cookieDomain;var b=f.getDomain(document,location.hostname);return ""===b?"":"."+b},this.getDomain=function(a,b){var c,d,e=b.split(".");for(c=e.length-1;0<=c;c--)if(d=e.slice(c).join("."),a.cookie="mptest=cookie;domain=."+d+";",-1<a.cookie.indexOf("mptest=cookie"))return a.cookie="mptest=;domain=."+d+";expires=Thu, 01 Jan 1970 00:00:01 GMT;",d;return ""},this.saveUserCookieSyncDatesToPersistence=function(a,b){if(b){var c=f.getPersistence();c&&(c[a]?c[a].csd=b:c[a]={csd:b}),f.savePersistence(c);}},this.swapCurrentUser=function(a,b,c){if(a&&b&&a!==b){var d=f.getPersistence();d&&(d.cu=b,d.gs.csm=c,f.savePersistence(d));}},this.savePersistence=function(b){var c;// Block mprtcl-v4 persistence when noFunctional is true
|
|
683
|
+
if(!(null!==(c=a._CookieConsentManager)&&void 0!==c&&c.getNoFunctional())){var d,e=f.encodePersistence(JSON.stringify(b)),g=new Date,h=a._Store.storageName,i=new Date(g.getTime()+1e3*(60*(60*(24*a._Store.SDKConfig.cookieExpiration)))).toGMTString(),j=f.getCookieDomain();if(d=""===j?"":";domain="+j,a._Store.SDKConfig.useCookieStorage){var k=f.reduceAndEncodePersistence(b,i,d,a._Store.SDKConfig.maxCookieSize);window.document.cookie=encodeURIComponent(h)+"="+k;}else a._Store.isLocalStorageAvailable&&localStorage.setItem(a._Store.storageName,e);}},this.getPersistence=function(){var a=this.useLocalStorage()?this.getLocalStorage():this.getCookie();return a},this.getFirstSeenTime=function(a){if(!a)return null;var b=f.getPersistence();return b&&b[a]&&b[a].fst?b[a].fst:null},this.setFirstSeenTime=function(a,b){if(a){b||(b=new Date().getTime());var c=f.getPersistence();c&&(!c[a]&&(c[a]={}),!c[a].fst&&(c[a].fst=b,f.savePersistence(c)));}// https://go.mparticle.com/work/SQDSDKS-6329
|
|
664
684
|
},this.getLastSeenTime=function(b){if(!b)return null;if(b===a.Identity.getCurrentUser().getMPID())//if the mpid is the current user, its last seen time is the current time
|
|
665
685
|
return new Date().getTime();var c=f.getPersistence();return c&&c[b]&&c[b].lst?c[b].lst:null},this.setLastSeenTime=function(a,b){if(a){b||(b=new Date().getTime());var c=f.getPersistence();c&&c[a]&&(c[a].lst=b,f.savePersistence(c));}// https://go.mparticle.com/work/SQDSDKS-6329
|
|
666
686
|
},this.getDeviceId=function(){return a._Store.deviceId},this.setDeviceId=function(b){a._Store.deviceId=b,f.update();},this.resetPersistence=function(){if(localStorage.clear(),f.expireCookies(StorageNames.cookieName),f.expireCookies(StorageNames.cookieNameV2),f.expireCookies(StorageNames.cookieNameV3),f.expireCookies(StorageNames.cookieNameV4),f.expireCookies(a._Store.storageName),mParticle._isTestEnv){c(a._Helpers.createMainStorageName("abcdef")),f.expireCookies(a._Helpers.createMainStorageName("abcdef"));}},this.forwardingStatsBatches={uploadsTable:{},forwardingStatsEventQueue:[]};}
|
|
@@ -1404,7 +1424,7 @@ return [2/*return*/,b]}})})};}
|
|
|
1404
1424
|
|
|
1405
1425
|
var ErrorCodes={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST"};var WSDKErrorSeverity={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"};
|
|
1406
1426
|
|
|
1407
|
-
var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k,l;return __awaiter(this,void 0,void 0,function(){var m,n,o,p,q,r,s,t,u,v,w,x,y,z,z,m,
|
|
1427
|
+
var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k,l;return __awaiter(this,void 0,void 0,function(){var m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,z,m,D,m,z;return __generator(this,function(E){switch(E.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestStart"))),n=a._Helpers.invokeCallback,o=a.Logger,o.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return o.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(o.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return n(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];p=g||null,q=this.getUploadUrl(c,g),r=window.fetch?new FetchUploader(q):new XHRUploader(q),s={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,E.label=1;case 1:return E.trys.push([1,9,,10]),[4/*yield*/,r.upload(s)];case 2:return t=E.sent(),u=void 0,v=void 0,w=t.status,w===HTTP_ACCEPTED?[3/*break*/,3]:w===HTTP_OK?[3/*break*/,3]:w===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return t.json?[4/*yield*/,t.json()]:[3/*break*/,5];case 4:return x=E.sent(),u=this.getIdentityResponseFromFetch(t,x),[3/*break*/,6];case 5:u=this.getIdentityResponseFromXHR(t),E.label=6;case 6:return u.status===HTTP_BAD_REQUEST?(y=u.responseText,v="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+u.status,(null===y||void 0===y?void 0:y.Errors)&&(z=y.Errors.map(function(a){return a.message}).join(", "),v+=" - "+z)):o.isVerbose()&&(A=u.responseText,B=a._Store.SDKConfig.isDevelopmentMode,C=A,!B&&(null===A||void 0===A?void 0:A.matched_identities)&&(C=__assign(__assign({},A),{matched_identities:obfuscateData(A.matched_identities)})),v="Received Identity Response from server: "+JSON.stringify(C)),[3/*break*/,8];case 7:{if(t.status>=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+t.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,z="Received HTTP Code of "+t.status,o.error("Error sending identity request to servers - "+z),n(d,HTTPCodes$1.noHttpCoverage,z),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,v&&o.verbose(v),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),f(u,p,d,e,c,h,!1),[3/*break*/,10];case 9:return D=E.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),z=D.message||D.toString(),o.error("Error sending identity request to servers - "+z,ErrorCodes.IDENTITY_REQUEST),null===(l=a.processQueueOnIdentityFailure)||void 0===l?void 0:l.call(a),n(d,HTTPCodes$1.noHttpCoverage,z),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};}
|
|
1408
1428
|
|
|
1409
1429
|
// The formatted ClickID value must be of the form version.subdomainIndex.creationTime.<fbclid>, where:
|
|
1410
1430
|
// - version is always this prefix: fb
|
|
@@ -1462,12 +1482,12 @@ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters=
|
|
|
1462
1482
|
// as that is independent of this setting, though they share the same name.
|
|
1463
1483
|
var p=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through
|
|
1464
1484
|
// to the Rokt Launcher.
|
|
1465
|
-
this.launcherOptions=__assign({sandbox:p},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain),this.initialized=!0;},Object.defineProperty(a.prototype,"isInitialized",{get:function get(){return this.initialized},enumerable:!1,configurable:!0}),a.prototype.attachKit=function(a){var b,c,d,f;this.kit=a,(null===(b=a.settings)||void 0===b?void 0:b.accountId)&&this.store.setRoktAccountId(a.settings.accountId),a.integrationName&&(null===(c=this.store)||void 0===c?void 0:c.setIntegrationName(a.integrationName)),this.processMessageQueue();try{null===(d=this.onReadyCallback)||void 0===d?void 0:d.call(this);}catch(a){null===(f=this.logger)||void 0===f?void 0:f.error("RoktManager: Error in onReadyCallback: "+a);}},a.prototype.selectPlacements=function(a){var b,c,d,e,f,g,h;return __awaiter(this,void 0,void 0,function(){var
|
|
1466
|
-
if(null===(b=this.captureTiming)||void 0===b?void 0:b.call(this,PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(c=this.store)||void 0===c?void 0:c.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];
|
|
1485
|
+
this.launcherOptions=__assign({sandbox:p},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain),this.initialized=!0;},Object.defineProperty(a.prototype,"isInitialized",{get:function get(){return this.initialized},enumerable:!1,configurable:!0}),a.prototype.attachKit=function(a){var b,c,d,f;this.kit=a,(null===(b=a.settings)||void 0===b?void 0:b.accountId)&&this.store.setRoktAccountId(a.settings.accountId),a.integrationName&&(null===(c=this.store)||void 0===c?void 0:c.setIntegrationName(a.integrationName)),this.processMessageQueue();try{null===(d=this.onReadyCallback)||void 0===d?void 0:d.call(this);}catch(a){null===(f=this.logger)||void 0===f?void 0:f.error("RoktManager: Error in onReadyCallback: "+a);}},a.prototype.selectPlacements=function(a){var b,c,d,e,f,g,h,i,j;return __awaiter(this,void 0,void 0,function(){var k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E=this;return __generator(this,function(F){switch(F.label){case 0:// Queue if kit isn't ready OR if identity is in flight
|
|
1486
|
+
if(null===(b=this.captureTiming)||void 0===b?void 0:b.call(this,PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(c=this.store)||void 0===c?void 0:c.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];F.label=1;case 1:if(F.trys.push([1,6,,7]),k=a.attributes,l=(null===k||void 0===k?void 0:k.sandbox)||null,m=this.mapPlacementAttributes(k,this.placementAttributesMapping),(null===(d=this.logger)||void 0===d?void 0:d.isVerbose())&&(n=obfuscateDevData(k,null===(f=null===(e=this.store)||void 0===e?void 0:e.SDKConfig)||void 0===f?void 0:f.isDevelopmentMode),this.logger.verbose("mParticle.Rokt selectPlacements called with attributes:\n".concat(JSON.stringify(n,null,2)))),this.currentUser=this.identityService.getCurrentUser(),o=(null===(h=null===(g=this.currentUser)||void 0===g?void 0:g.getUserIdentities())||void 0===h?void 0:h.userIdentities)||{},p=o.email,q=m.email,r=void 0,s=void 0,t=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),t&&(r=o[this.mappedEmailShaIdentityType],s=m.emailsha256||m[this.mappedEmailShaIdentityType]||void 0),u=this.hasIdentityChanged(p,q),v=this.hasIdentityChanged(r,s),w={},u&&(w.email=q,q&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),v&&(w[this.mappedEmailShaIdentityType]=s,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(w))return [3/*break*/,5];F.label=2;case 2:return F.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){E.identityService.identify({userIdentities:__assign(__assign({},o),w)},function(){a();});})];case 3:return F.sent(),[3/*break*/,5];case 4:return x=F.sent(),y=x instanceof Error?x.message:JSON.stringify(x),this.logger.error("Failed to identify user with updated identities: "+y),[3/*break*/,5];case 5:return this.currentUser=this.identityService.getCurrentUser(),z=(null===(j=null===(i=this.currentUser)||void 0===i?void 0:i.getUserIdentities())||void 0===j?void 0:j.userIdentities)||{},this.setUserAttributes(m),A=__assign(__assign({},m),null===l?{}:{sandbox:l}),z.email&&!A.email&&(A.email=z.email),t&&(B=z[this.mappedEmailShaIdentityType],B&&!A.emailsha256&&!A[this.mappedEmailShaIdentityType]&&(A.emailsha256=B)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,C=__assign(__assign({},a),{attributes:A}),[2/*return*/,this.kit.selectPlacements(C)];case 6:return D=F.sent(),[2/*return*/,Promise.reject(D instanceof Error?D:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);f<g.length;f++)h=g[f],i=h.key,j=h.attributeValue,k=h.hashedValue,e[i]=j,k&&(e["".concat(i,"sha256")]=k);return [2/*return*/,e];case 2:return l=o.sent(),m=l instanceof Error?l.message:l+"",this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(m)),[2/*return*/,{}];case 3:return [2/*return*/]}})})},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.deferredCall("setExtensionData",a);try{this.kit.setExtensionData(a);}catch(a){var b=a instanceof Error?a.message:a+"";throw new Error("Error setting extension data: "+b)}},a.prototype.use=function(a){if(!this.isReady())return this.deferredCall("use",a);try{return this.kit.use(a)}catch(b){return Promise.reject(b instanceof Error?b:new Error("Error using extension: "+a))}},a.prototype.hashSha256=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];e.label=1;case 1:return e.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,e.sent()];case 3:return c=e.sent(),d=c instanceof Error?c.message:c+"",this.logger.error("Failed to hashSha256, returning undefined: ".concat(d)),[2/*return*/,void 0];case 4:return [2/*return*/]}})})},a.prototype.getLocalSessionAttributes=function(){return this.store.getLocalSessionAttributes()},a.prototype.setLocalSessionAttribute=function(a,b){this.store.setLocalSessionAttribute(a,b);},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
|
|
1467
1487
|
return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)if(a.hasOwnProperty(d)&&-1===b.indexOf(d)){var e=a[d];c[d]=Array.isArray(e)?JSON.stringify(e):e;}try{this.currentUser.setUserAttributes(c);}catch(a){this.logger.error("Error setting user attributes: "+a);}},a.prototype.mapPlacementAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.onIdentityComplete=function(){this.isReady()&&(this.currentUser=this.identityService.getCurrentUser(),this.processMessageQueue());},a.prototype.processMessageQueue=function(){var a,b=this;if(this.isReady()&&0!==this.messageQueue.size){null===(a=this.logger)||void 0===a?void 0:a.verbose("RoktManager: Processing ".concat(this.messageQueue.size," queued messages"));var c=Array.from(this.messageQueue.values());// Clear the queue immediately to prevent re-processing
|
|
1468
|
-
this.messageQueue.clear(),c.forEach(function(a){var c,d;if(!(a.methodName in b)||!isFunction(b[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found")));null===(d=b.logger)||void 0===d?void 0:d.verbose("RoktManager: Processing queued message: ".concat(a.methodName," with payload: ").concat(JSON.stringify(
|
|
1469
|
-
var
|
|
1470
|
-
Promise.resolve(
|
|
1488
|
+
this.messageQueue.clear(),c.forEach(function(a){var c,d,e,f;if(!(a.methodName in b)||!isFunction(b[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found")));if(null===(d=b.logger)||void 0===d?void 0:d.isVerbose()){var g=obfuscateDevData(a.payload,null===(f=null===(e=b.store)||void 0===e?void 0:e.SDKConfig)||void 0===f?void 0:f.isDevelopmentMode);b.logger.verbose("RoktManager: Processing queued message: ".concat(a.methodName," with payload: ").concat(JSON.stringify(g)));}// Capture resolve/reject functions before async processing
|
|
1489
|
+
var h=a.resolve,i=a.reject,j=function(c){var d,e=c instanceof Error?c.message:c+"";null===(d=b.logger)||void 0===d?void 0:d.error("RoktManager: Error processing message '".concat(a.methodName,"': ").concat(e)),i&&i(c);};try{var k=b[a.methodName](a.payload);// Handle both sync and async methods
|
|
1490
|
+
Promise.resolve(k).then(function(a){h&&h(a);})["catch"](j);}catch(a){j(a);}});}},a.prototype.queueMessage=function(a){this.messageQueue.set(a.messageId,a);},a.prototype.deferredCall=function(a,b){var c=this;return new Promise(function(d,e){var f="".concat(a,"_").concat(generateUniqueId());c.queueMessage({messageId:f,methodName:a,payload:b,resolve:d,reject:e});})},a.prototype.sha256Hex=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:return b=new TextEncoder,c=b.encode(a),[4/*yield*/,crypto.subtle.digest("SHA-256",c)];case 1:return d=e.sent(),[2/*return*/,this.arrayBufferToHex(d)]}})})},a.prototype.arrayBufferToHex=function(a){for(var b,c=new Uint8Array(a),d="",e=0;e<c.length;e++)b=c[e].toString(16).padStart(2,"0"),d+=b;return d},a.prototype.hasIdentityChanged=function(a,b){return !!b&&(!a||a!==b);// Values are the same
|
|
1471
1491
|
},a}();
|
|
1472
1492
|
|
|
1473
1493
|
/**
|
|
@@ -1498,11 +1518,11 @@ var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Const
|
|
|
1498
1518
|
*
|
|
1499
1519
|
* @class mParticle & mParticleInstance
|
|
1500
1520
|
*/function mParticleInstance(a){var b=this;// These classes are for internal use only. Not documented for public consumption
|
|
1501
|
-
this._instanceName=a,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._RoktManager=new RoktManager,this._RoktManager.setOnReadyCallback(function(){b.processQueueOnIdentityFailure();}),this.processQueueOnIdentityFailure=function(){var a,c,d;(null===(a=b._Store)||void 0===a?void 0:a.isInitialized)||(null===(c=b._Store)||void 0===c?void 0:c.identityCallFailed)&&(null===(d=b._RoktManager)||void 0===d?void 0:d.isReady())&&(b._RoktManager.processMessageQueue(),b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));},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,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){var c=this;// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization
|
|
1521
|
+
this._instanceName=a,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._RoktManager=new RoktManager,this._RoktManager.setOnReadyCallback(function(){b.processQueueOnIdentityFailure();}),this.processQueueOnIdentityFailure=function(){var a,c,d;(null===(a=b._Store)||void 0===a?void 0:a.isInitialized)||(null===(c=b._Store)||void 0===c?void 0:c.identityCallFailed)&&(null===(d=b._RoktManager)||void 0===d?void 0:d.isReady())&&(b._RoktManager.processMessageQueue(),b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));},this.processQueueOnNoFunctional=function(){var a,c;if(!(null!==(a=b._Store)&&void 0!==a)||!a.isInitialized){var d=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);d&&(b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));}},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,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){var c=this;// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization
|
|
1502
1522
|
// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization
|
|
1503
1523
|
// to it for it to be run after fetched
|
|
1504
1524
|
if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=c._Helpers.extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c,d){// Update ReportingLogger with the new Store reference to avoid stale data
|
|
1505
|
-
c._Store&&delete c._Store,c.Logger=new Logger(a,d),c._Store=new Store(a,c),null===d||void 0===d?void 0:d.setStore(c._Store),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e=isFunction(a)&&((null===(
|
|
1525
|
+
c._Store&&delete c._Store,c.Logger=new Logger(a,d),c._Store=new Store(a,c),null===d||void 0===d?void 0:d.setStore(c._Store),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.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."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval
|
|
1506
1526
|
b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof$1(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof$1(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/**
|
|
1507
1527
|
* Creates a CCPA Opt Out Consent State.
|
|
1508
1528
|
*
|
|
@@ -1648,35 +1668,39 @@ b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIf
|
|
|
1648
1668
|
* @param {Object} [attrs] attributes related to the refund
|
|
1649
1669
|
* @param {Object} [customFlags] Custom flags for the event
|
|
1650
1670
|
* @deprecated
|
|
1651
|
-
*/logRefund:function logRefund(a,c,d,e,f){return b.Logger.warning("mParticle.logRefund is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logRefundEvent(a,c,e,f)):void b.ready(function(){b.eCommerce.logRefund(a,c,d,e,f);})},expandCommerceEvent:function expandCommerceEvent(a){return b._Ecommerce.expandCommerceEvent(a)}},this.setSessionAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setSessionAttribute(a,c);},b);if(
|
|
1671
|
+
*/logRefund:function logRefund(a,c,d,e,f){return b.Logger.warning("mParticle.logRefund is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logRefundEvent(a,c,e,f)):void b.ready(function(){b.eCommerce.logRefund(a,c,d,e,f);})},expandCommerceEvent:function expandCommerceEvent(a){return b._Ecommerce.expandCommerceEvent(a)}},this.setSessionAttribute=function(a,c){var d,e=(null===(d=b._CookieConsentManager)||void 0===d?void 0:d.getNoFunctional())&&!hasExplicitIdentifier(b._Store);if(!e){var f=queueIfNotInitialized(function(){b.setSessionAttribute(a,c);},b);if(f)return}// Logs to cookie
|
|
1652
1672
|
// And logs to in-memory object
|
|
1653
1673
|
// Example: mParticle.setSessionAttribute('location', '33431');
|
|
1654
|
-
{if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var
|
|
1674
|
+
if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof$1(c));if(0===Object.keys(c).length)b._Store.integrationAttributes[a]={};else for(var e in c)if("string"!=typeof e){b.Logger.error("Keys must be strings, you entered a "+_typeof$1(e));continue}else if("string"==typeof c[e])b._Helpers.isObject(b._Store.integrationAttributes[a])?b._Store.integrationAttributes[a][e]=c[e]:(b._Store.integrationAttributes[a]={},b._Store.integrationAttributes[a][e]=c[e]);else {b.Logger.error("Values for integration attributes must be strings. You entered a "+_typeof$1(c[e]));continue}}b._Persistence.update();}},this.getIntegrationAttributes=function(a){return b._Store.integrationAttributes[a]?b._Store.integrationAttributes[a]:{}},this.addForwarder=function(a){b._preInit.forwarderConstructors.push(a);},this.configurePixel=function(a){b._Forwarders.configurePixel(a);},this._getActiveForwarders=function(){return b._Store.activeForwarders},this._getIntegrationDelays=function(){return b._preInit.integrationDelays},this._setIntegrationDelay=function(a,c){// If the integration delay is set to true, no further action needed
|
|
1655
1675
|
if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any
|
|
1656
1676
|
// other integration delays set to true. It not, process the queued events/.
|
|
1657
1677
|
var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment
|
|
1658
|
-
function completeSDKInitialization(a,b,c){var d,e=createKitBlocker(b,c),
|
|
1678
|
+
function completeSDKInitialization(a,b,c){var d,e,f=createKitBlocker(b,c),g=c._Helpers.getFeatureFlag;// Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's
|
|
1659
1679
|
// Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not
|
|
1660
1680
|
// responsible for sending events directly to mParticle's servers. The Web SDK will not initialize
|
|
1661
1681
|
// persistence or Identity directly.
|
|
1662
|
-
if(c._APIClient=new APIClient(c,
|
|
1663
|
-
var
|
|
1664
|
-
var
|
|
1665
|
-
var
|
|
1666
|
-
c._RoktManager.init(
|
|
1682
|
+
if(c._APIClient=new APIClient(c,f),c._Forwarders=new Forwarders(c,f),c._Store.processConfig(b),c._Identity.idCache=createIdentityCache(c),removeExpiredIdentityCacheDates(c._Identity.idCache),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.initializeSessionAttributes(a);else {c._Persistence.initializeStorage(),c._Store.syncPersistenceData();// Set up user identitiy variables for later use
|
|
1683
|
+
var h=c.Identity.getCurrentUser(),i=h?h.getMPID():null,j=h?h.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:j}:c._Store.SDKConfig.identifyRequest,g(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer();// https://go.mparticle.com/work/SQDSDKS-7639
|
|
1684
|
+
var k=g(CaptureIntegrationSpecificIds),l=g(CaptureIntegrationSpecificIdsV2),m=l&&l!==CaptureIntegrationSpecificIdsV2Modes.None||!0===k;if(m){var n;k||l===CaptureIntegrationSpecificIdsV2Modes.All?n="all":l===CaptureIntegrationSpecificIdsV2Modes.RoktOnly&&(n="roktonly"),c._IntegrationCapture=new IntegrationCapture(n),c._IntegrationCapture.capture();}// Configure Rokt Manager with user and filtered user
|
|
1685
|
+
var o=parseConfig(b,"Rokt",181);if(o){var p=null===(d=o.settings)||void 0===d?void 0:d.accountId;c._Store.setRoktAccountId(p);var q=o.userAttributeFilters,r=filteredMparticleUser(i,{userAttributeFilters:q},c),s={sandbox:null===b||void 0===b?void 0:b.isDevelopmentMode,launcherOptions:null===b||void 0===b?void 0:b.launcherOptions,domain:null===b||void 0===b?void 0:b.domain};// https://go.mparticle.com/work/SQDSDKS-7339
|
|
1686
|
+
c._RoktManager.init(o,r,c.Identity,c._Store,c.Logger,s,c.captureTiming);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,h,i,j);}// We will continue to clear out the ready queue as part of the initial init flow
|
|
1667
1687
|
// if an identify request is unnecessary, such as if there is an existing session
|
|
1668
|
-
(c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue)),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061
|
|
1688
|
+
(c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue)),null===(e=c.processQueueOnNoFunctional)||void 0===e?void 0:e.call(c),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061
|
|
1669
1689
|
function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK:
|
|
1670
1690
|
1. Manually via config.dataPlanOptions (this takes priority)
|
|
1671
1691
|
If not passed in manually, we user the server provided via either
|
|
1672
1692
|
2. Snippet via /mparticle.js endpoint (config.dataPlan.document)
|
|
1673
1693
|
3. Self hosting via /config endpoint (config.dataPlanResult)
|
|
1674
|
-
*/return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){
|
|
1694
|
+
*/return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){var b;// Identity expects mpInstance._Identity.idCache to always exist. DisabledVault
|
|
1695
|
+
// ensures no identity response data is written to localStorage when noFunctional is true
|
|
1696
|
+
return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache")):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"))}function runPreConfigFetchInitialization(a,b,c){var d;a._ReportingLogger=new ReportingLogger(c,Constants.sdkVersion,void 0,a.getLauncherInstanceGuid()),a.Logger=new Logger(c,a._ReportingLogger),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a._ReportingLogger.setStore(a._Store),a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions
|
|
1675
1697
|
var e=null!==(d=null===c||void 0===c?void 0:c.launcherOptions)&&void 0!==d?d:{},f=e.noFunctional,g=e.noTargeting;a._CookieConsentManager=new CookieConsentManager({noFunctional:f,noTargeting:g});// Check to see if localStorage is available before main configuration runs
|
|
1676
1698
|
// since we will need this for the current implementation of user persistence
|
|
1677
1699
|
// TODO: Refactor this when we refactor User Identity Persistence
|
|
1678
|
-
try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function queueIfNotInitialized(a,b){var c;//
|
|
1679
|
-
|
|
1700
|
+
try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function queueIfNotInitialized(a,b){var c,d,e=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);// When noFunctional is true with no explicit identifier, the SDK will never
|
|
1701
|
+
// receive an MPID. Let these calls through so events can still reach forwarders immediately.
|
|
1702
|
+
// sendEventToServer handles queuing for the MP server upload path separately.
|
|
1703
|
+
return !((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||e)&&(b._preInit.readyQueue.push(function(){var c;(null===(c=b._Store)||void 0===c?void 0:c.isInitialized)&&a();}),!0)}
|
|
1680
1704
|
|
|
1681
1705
|
// This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise!
|
|
1682
1706
|
var mockFunction=function(){return null},_BatchValidator=/** @class */function(){function a(){}return a.prototype.getMPInstance=function(){return {// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method
|