@mparticle/web-sdk 2.17.2 → 2.17.4

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.
@@ -32,7 +32,7 @@ function _defineProperty(obj, key, value) {
32
32
 
33
33
  var _TriggerUploadType,MessageType$1={SessionStart:1,SessionEnd:2,PageView:3,PageEvent:4,CrashReport:5,OptOut:6,AppStateTransition:10,Profile:14,Commerce:16,Media:20,UserAttributeChange:17,UserIdentityChange:18},TriggerUploadType=(_TriggerUploadType={},_defineProperty(_TriggerUploadType,MessageType$1.Commerce,1),_defineProperty(_TriggerUploadType,MessageType$1.UserAttributeChange,1),_defineProperty(_TriggerUploadType,MessageType$1.UserIdentityChange,1),_TriggerUploadType),EventType={Unknown:0,Navigation:1,Location:2,Search:3,Transaction:4,UserContent:5,UserPreference:6,Social:7,Other:8,Media:9,getName:function getName(a){return a===EventType.Unknown?"Unknown":a===EventType.Navigation?"Navigation":a===EventType.Location?"Location":a===EventType.Search?"Search":a===EventType.Transaction?"Transaction":a===EventType.UserContent?"User Content":a===EventType.UserPreference?"User Preference":a===EventType.Social?"Social":a===CommerceEventType.ProductAddToCart?"Product Added to Cart":a===CommerceEventType.ProductAddToWishlist?"Product Added to Wishlist":a===CommerceEventType.ProductCheckout?"Product Checkout":a===CommerceEventType.ProductCheckoutOption?"Product Checkout Options":a===CommerceEventType.ProductClick?"Product Click":a===CommerceEventType.ProductImpression?"Product Impression":a===CommerceEventType.ProductPurchase?"Product Purchased":a===CommerceEventType.ProductRefund?"Product Refunded":a===CommerceEventType.ProductRemoveFromCart?"Product Removed From Cart":a===CommerceEventType.ProductRemoveFromWishlist?"Product Removed from Wishlist":a===CommerceEventType.ProductViewDetail?"Product View Details":a===CommerceEventType.PromotionClick?"Promotion Click":a===CommerceEventType.PromotionView?"Promotion View":"Other"}},CommerceEventType={ProductAddToCart:10,ProductRemoveFromCart:11,ProductCheckout:12,ProductCheckoutOption:13,ProductClick:14,ProductViewDetail:15,ProductPurchase:16,ProductRefund:17,PromotionView:18,PromotionClick:19,ProductAddToWishlist:20,ProductRemoveFromWishlist:21,ProductImpression:22},IdentityType={Other:0,CustomerId:1,Facebook:2,Twitter:3,Google:4,Microsoft:5,Yahoo:6,Email:7,FacebookCustomAudienceId:9,Other2:10,Other3:11,Other4:12,Other5:13,Other6:14,Other7:15,Other8:16,Other9:17,Other10:18,MobileNumber:19,PhoneNumber2:20,PhoneNumber3:21};IdentityType.isValid=function(a){if("number"==typeof a)for(var b in IdentityType)if(IdentityType.hasOwnProperty(b)&&IdentityType[b]===a)return !0;return !1},IdentityType.getName=function(a){return a===window.mParticle.IdentityType.CustomerId?"Customer ID":a===window.mParticle.IdentityType.Facebook?"Facebook ID":a===window.mParticle.IdentityType.Twitter?"Twitter ID":a===window.mParticle.IdentityType.Google?"Google ID":a===window.mParticle.IdentityType.Microsoft?"Microsoft ID":a===window.mParticle.IdentityType.Yahoo?"Yahoo ID":a===window.mParticle.IdentityType.Email?"Email":a===window.mParticle.IdentityType.FacebookCustomAudienceId?"Facebook App User ID":"Other ID"},IdentityType.getIdentityType=function(a){return "other"===a?IdentityType.Other:"customerid"===a?IdentityType.CustomerId:"facebook"===a?IdentityType.Facebook:"twitter"===a?IdentityType.Twitter:"google"===a?IdentityType.Google:"microsoft"===a?IdentityType.Microsoft:"yahoo"===a?IdentityType.Yahoo:"email"===a?IdentityType.Email:"facebookcustomaudienceid"===a?IdentityType.FacebookCustomAudienceId:"other2"===a?IdentityType.Other2:"other3"===a?IdentityType.Other3:"other4"===a?IdentityType.Other4:"other5"===a?IdentityType.Other5:"other6"===a?IdentityType.Other6:"other7"===a?IdentityType.Other7:"other8"===a?IdentityType.Other8:"other9"===a?IdentityType.Other9:"other10"===a?IdentityType.Other10:"mobile_number"===a?IdentityType.MobileNumber:"phone_number_2"===a?IdentityType.PhoneNumber2:!("phone_number_3"!=a)&&IdentityType.PhoneNumber3},IdentityType.getIdentityName=function(a){return a===IdentityType.Other?"other":a===IdentityType.CustomerId?"customerid":a===IdentityType.Facebook?"facebook":a===IdentityType.Twitter?"twitter":a===IdentityType.Google?"google":a===IdentityType.Microsoft?"microsoft":a===IdentityType.Yahoo?"yahoo":a===IdentityType.Email?"email":a===IdentityType.FacebookCustomAudienceId?"facebookcustomaudienceid":a===IdentityType.Other2?"other2":a===IdentityType.Other3?"other3":a===IdentityType.Other4?"other4":a===IdentityType.Other5?"other5":a===IdentityType.Other6?"other6":a===IdentityType.Other7?"other7":a===IdentityType.Other8?"other8":a===IdentityType.Other9?"other9":a===IdentityType.Other10?"other10":a===IdentityType.MobileNumber?"mobile_number":a===IdentityType.PhoneNumber2?"phone_number_2":a===IdentityType.PhoneNumber3?"phone_number_3":void 0};var ProductActionType={Unknown:0,AddToCart:1,RemoveFromCart:2,Checkout:3,CheckoutOption:4,Click:5,ViewDetail:6,Purchase:7,Refund:8,AddToWishlist:9,RemoveFromWishlist:10};ProductActionType.getName=function(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"},ProductActionType.getExpansionName=function(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};PromotionActionType.getName=function(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"},PromotionActionType.getExpansionName=function(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"};var ProfileMessageType={Logout:3},ApplicationTransitionType$1={AppInit:1};var Types = {MessageType:MessageType$1,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,TriggerUploadType:TriggerUploadType};
34
34
 
35
- var version = "2.17.2";
35
+ var version = "2.17.4";
36
36
 
37
37
  var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{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"},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
38
38
  },DefaultUrls:{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/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventsV3:"eventsV3",EventBatchingIntervalMillis:"eventBatchingIntervalMillis"},DefaultInstance:"default_instance"};
@@ -379,7 +379,7 @@ var b=parseInt(a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventsV3),10);if
379
379
  // need to be set, or if we are still fetching the config (self hosted only), and so require delaying events
380
380
  return g&&(f=g.getMPID()),a._Store.requireDelay=a._Helpers.isDelayedByIntegration(a._preInit.integrationDelays,a._Store.integrationDelayTimeoutStart,Date.now()),f&&!a._Store.requireDelay&&a._Store.configurationLoaded?void(this.processQueuedEvents(),c&&e.shouldUploadEvent&&(this.shouldEnableBatching()?this.queueEventForBatchUpload(c):this.sendSingleEventToServer(c)),c&&c.EventName!==Types.MessageType.AppStateTransition&&(b&&b.kitBlockingEnabled&&(c=b.createBlockedEvent(c)),c&&a._Forwarders.sendEventToForwarders(c))):(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.sendSingleEventToServer=function(b){if(b.EventDataType!==Types.MessageType.Media){var c,d=function xhrCallback(){4===c.readyState&&(a.Logger.verbose("Received "+c.statusText+" from server"),a._Persistence.update());};if(!b)return void a.Logger.error(Messages$9.ErrorMessages.EventEmpty);if(a.Logger.verbose(Messages$9.InformationMessages.SendHttp),c=a._Helpers.createXHR(d),c)try{c.open("post",a._Helpers.createServiceUrl(a._Store.SDKConfig.v2SecureServiceUrl,a._Store.devToken)+"/Events"),c.send(JSON.stringify(a._ServerModel.convertEventToDTO(b)));}catch(b){a.Logger.error("Error sending event to mParticle servers. "+b);}}},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.sendSingleForwardingStatsToServer=function(b){var c,d;try{var e=function xhrCallback(){4===f.readyState&&202===f.status&&a.Logger.verbose("Successfully sent "+f.statusText+" from server");},f=a._Helpers.createXHR(e);c=a._Helpers.createServiceUrl(a._Store.SDKConfig.v1SecureServiceUrl,a._Store.devToken),d=b,f&&(f.open("post",c+"/Forwarding"),f.send(JSON.stringify(d)));}catch(b){a.Logger.error("Error sending forwarding stats to mParticle servers.");}},this.prepareForwardingStats=function(b,d){var e,f=a._Forwarders.getForwarderStatsQueue();b&&b.isVisible&&(e={mid:b.id,esid:b.eventSubscriptionId,n:d.EventName,attrs:d.EventAttributes,sdk:d.SDKVersion,dt:d.EventDataType,et:d.EventCategory,dbg:d.Debug,ct:d.Timestamp,eec:d.ExpandedEventCount,dp:d.DataPlan},a._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)?(f.push(e),a._Forwarders.setForwarderStatsQueue(f)):c.sendSingleForwardingStatsToServer(e));};}
381
381
 
382
- var slugify = {exports: {}};
382
+ var slugify$1 = {exports: {}};
383
383
 
384
384
  (function (module, exports) {
385
385
  (function (name, root, factory) {
@@ -443,14 +443,15 @@ var slugify = {exports: {}};
443
443
 
444
444
  return replace
445
445
  }));
446
- } (slugify));
446
+ } (slugify$1));
447
447
 
448
- var Slugify = slugify.exports;
448
+ var slugify = slugify$1.exports;
449
449
 
450
- var inArray=function(a,b){var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c<d;c++)if(c in a&&a[c]===b)return !0;return !1},findKeyInObject=function(a,b){if(b&&a)for(var c in a)if(a.hasOwnProperty(c)&&c.toLowerCase()===b.toLowerCase())return c;return null},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a};
450
+ var inArray=function(a,b){var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c<d;c++)if(c in a&&a[c]===b)return !0;return !1},findKeyInObject=function(a,b){if(b&&a)for(var c in a)if(a.hasOwnProperty(c)&&c.toLowerCase()===b.toLowerCase())return c;return null},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a},isString=function(a){return "string"==typeof a},isNumber=function(a){return "number"==typeof a},isFunction=function(a){return "function"==typeof a},isDataPlanSlug=function(a){return isString(a)&&a===slugify(a)},isStringOrNumber=function(a){return isString(a)||isNumber(a)};
451
451
 
452
- var Validators={isValidAttributeValue:function isValidAttributeValue(a){return a!==void 0&&!isObject(a)&&!Array.isArray(a)},// Neither null nor undefined can be a valid Key
453
- isValidKeyValue:function isValidKeyValue(a){return !(!a||isObject(a)||Array.isArray(a)||this.isFunction(a))},isStringOrNumber:function isStringOrNumber(a){return "string"==typeof a||"number"==typeof a},isNumber:function isNumber(a){return "number"==typeof a},isFunction:function isFunction(a){return "function"==typeof a},validateIdentities:function validateIdentities(a,b){var c={userIdentities:1,onUserAlias:1,copyUserAttributes:1};if(a){if("modify"===b&&(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
452
+ var Validators={// From ./utils
453
+ isNumber:isNumber,isFunction:isFunction,isStringOrNumber:isStringOrNumber,isValidAttributeValue:function isValidAttributeValue(a){return a!==void 0&&!isObject(a)&&!Array.isArray(a)},// Neither null nor undefined can be a valid Key
454
+ isValidKeyValue:function isValidKeyValue(a){return !(!a||isObject(a)||Array.isArray(a)||this.isFunction(a))},validateIdentities:function validateIdentities(a,b){var c={userIdentities:1,onUserAlias:1,copyUserAttributes:1};if(a){if("modify"===b&&(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
454
455
  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
455
456
  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}}};
456
457
 
@@ -478,7 +479,7 @@ return d// if the placeholder was passed, return
478
479
  /[018]/g,// zeroes, ones, and eights with
479
480
  c.generateUniqueId// random hex digits
480
481
  )},this.filterUserIdentities=function(a,b){var d=[];if(a&&Object.keys(a).length)for(var e in a)if(a.hasOwnProperty(e)){var f=Types.IdentityType.getIdentityType(e);if(!c.inArray(b,f)){var g={Type:f,Identity:a[e]};f===Types.IdentityType.CustomerId?d.unshift(g):d.push(g);}}return d},this.filterUserIdentitiesForForwarders=function(a,b){var d={};if(a&&Object.keys(a).length)for(var e in a)if(a.hasOwnProperty(e)){var f=Types.IdentityType.getIdentityType(e);c.inArray(b,f)||(d[e]=a[e]);}return d},this.filterUserAttributes=function(a,b){var d={};if(a&&Object.keys(a).length)for(var e in a)if(a.hasOwnProperty(e)){var f=c.generateHash(e);c.inArray(b,f)||(d[e]=a[e]);}return d},this.isEventType=function(a){for(var b in Types.EventType)if(Types.EventType.hasOwnProperty(b)&&Types.EventType[b]===a)return !0;return !1},this.parseStringOrNumber=function(a){return Validators.isStringOrNumber(a)?a:null},this.generateHash=function(a){var b,c=0,d=0;if(void 0===a||null===a)return 0;if(a=a.toString().toLowerCase(),Array.prototype.reduce)return a.split("").reduce(function(c,d){return c=(c<<5)-c+d.charCodeAt(0),c&c},0);if(0===a.length)return c;for(d=0;d<a.length;d++)b=a.charCodeAt(d),c=(c<<5)-c+b,c&=c;return c},this.sanitizeAttributes=function(b,d){if(!b||!c.isObject(b))return null;var e={};for(var f in b)// Make sure that attribute values are not objects or arrays, which are not valid
481
- b.hasOwnProperty(f)&&c.Validators.isValidAttributeValue(b[f])?e[f]=b[f]:a.Logger.warning("For '"+d+"', the corresponding attribute value of '"+f+"' must be a string, number, boolean, or null.");return e},this.isDelayedByIntegration=function(b,c,d){if(d-c>a._Store.SDKConfig.integrationDelayTimeout)return !1;for(var e in b){if(!0===b[e])return !0;continue}return !1},this.createMainStorageName=function(a){return a?StorageNames$2.currentStorageName+"_"+a:StorageNames$2.currentStorageName},this.createProductStorageName=function(a){return a?StorageNames$2.currentStorageProductsName+"_"+a:StorageNames$2.currentStorageProductsName},this.isSlug=function(a){return a===Slugify(a)},this.converted=converted,this.findKeyInObject=findKeyInObject,this.parseNumber=parseNumber,this.inArray=inArray,this.isObject=isObject,this.decoded=decoded,this.returnConvertedBoolean=returnConvertedBoolean,this.Validators=Validators;}
482
+ b.hasOwnProperty(f)&&c.Validators.isValidAttributeValue(b[f])?e[f]=b[f]:a.Logger.warning("For '"+d+"', the corresponding attribute value of '"+f+"' must be a string, number, boolean, or null.");return e},this.isDelayedByIntegration=function(b,c,d){if(d-c>a._Store.SDKConfig.integrationDelayTimeout)return !1;for(var e in b){if(!0===b[e])return !0;continue}return !1},this.createMainStorageName=function(a){return a?StorageNames$2.currentStorageName+"_"+a:StorageNames$2.currentStorageName},this.createProductStorageName=function(a){return a?StorageNames$2.currentStorageProductsName+"_"+a:StorageNames$2.currentStorageProductsName},this.converted=converted,this.findKeyInObject=findKeyInObject,this.parseNumber=parseNumber,this.inArray=inArray,this.isObject=isObject,this.decoded=decoded,this.returnConvertedBoolean=returnConvertedBoolean,this.Validators=Validators;}
482
483
 
483
484
  var Messages$8=Constants.Messages,androidBridgeNameBase="mParticleAndroid",iosBridgeNameBase="mParticle";function NativeSdkHelpers(a){var b=this;this.isBridgeV2Available=function(a){if(!a)return !1;var b=iosBridgeNameBase+"_"+a+"_v2";// iOS v2 bridge
484
485
  return !!(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.hasOwnProperty(b))||!!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName===b)||!!window.hasOwnProperty(androidBridgeNameBase+"_"+a+"_v2");// other iOS v2 bridge
@@ -499,8 +500,9 @@ var Messages$5=Constants.Messages;function Ecommerce(a){var b=this;// sanitizes
499
500
  this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty("Id")&&(b.TransactionId=a.Id),a.hasOwnProperty("Affiliation")&&(b.Affiliation=a.Affiliation),a.hasOwnProperty("CouponCode")&&(b.CouponCode=a.CouponCode),a.hasOwnProperty("Revenue")&&(b.TotalAmount=this.sanitizeAmount(a.Revenue,"Revenue")),a.hasOwnProperty("Shipping")&&(b.ShippingAmount=this.sanitizeAmount(a.Shipping,"Shipping")),a.hasOwnProperty("Tax")&&(b.TaxAmount=this.sanitizeAmount(a.Tax,"Tax")),a.hasOwnProperty("Step")&&(b.CheckoutStep=a.Step),a.hasOwnProperty("Option")&&(b.CheckoutOptions=a.Option);},this.getProductActionEventName=function(a){switch(a){case Types.ProductActionType.AddToCart:return "AddToCart";case Types.ProductActionType.AddToWishlist:return "AddToWishlist";case Types.ProductActionType.Checkout:return "Checkout";case Types.ProductActionType.CheckoutOption:return "CheckoutOption";case Types.ProductActionType.Click:return "Click";case Types.ProductActionType.Purchase:return "Purchase";case Types.ProductActionType.Refund:return "Refund";case Types.ProductActionType.RemoveFromCart:return "RemoveFromCart";case Types.ProductActionType.RemoveFromWishlist:return "RemoveFromWishlist";case Types.ProductActionType.ViewDetail:return "ViewDetail";case Types.ProductActionType.Unknown:default:return "Unknown";}},this.getPromotionActionEventName=function(a){return a===Types.PromotionActionType.PromotionClick?"PromotionClick":a===Types.PromotionActionType.PromotionView?"PromotionView":"Unknown"},this.convertProductActionToEventType=function(b){return b===Types.ProductActionType.AddToCart?Types.CommerceEventType.ProductAddToCart:b===Types.ProductActionType.AddToWishlist?Types.CommerceEventType.ProductAddToWishlist:b===Types.ProductActionType.Checkout?Types.CommerceEventType.ProductCheckout:b===Types.ProductActionType.CheckoutOption?Types.CommerceEventType.ProductCheckoutOption:b===Types.ProductActionType.Click?Types.CommerceEventType.ProductClick:b===Types.ProductActionType.Purchase?Types.CommerceEventType.ProductPurchase:b===Types.ProductActionType.Refund?Types.CommerceEventType.ProductRefund:b===Types.ProductActionType.RemoveFromCart?Types.CommerceEventType.ProductRemoveFromCart:b===Types.ProductActionType.RemoveFromWishlist?Types.CommerceEventType.ProductRemoveFromWishlist:b===Types.ProductActionType.Unknown?Types.EventType.Unknown:b===Types.ProductActionType.ViewDetail?Types.CommerceEventType.ProductViewDetail:(a.Logger.error("Could not convert product action type "+b+" to event type"),null)},this.convertPromotionActionToEventType=function(b){return b===Types.PromotionActionType.PromotionClick?Types.CommerceEventType.PromotionClick:b===Types.PromotionActionType.PromotionView?Types.CommerceEventType.PromotionView:(a.Logger.error("Could not convert promotion action type "+b+" to event type"),null)},this.generateExpandedEcommerceName=function(a,b){return "eCommerce - "+a+" - "+(b?"Total":"Item")},this.extractProductAttributes=function(a,b){b.CouponCode&&(a["Coupon Code"]=b.CouponCode),b.Brand&&(a.Brand=b.Brand),b.Category&&(a.Category=b.Category),b.Name&&(a.Name=b.Name),b.Sku&&(a.Id=b.Sku),b.Price&&(a["Item Price"]=b.Price),b.Quantity&&(a.Quantity=b.Quantity),b.Position&&(a.Position=b.Position),b.Variant&&(a.Variant=b.Variant),a["Total Product Amount"]=b.TotalAmount||0;},this.extractTransactionId=function(a,b){b.TransactionId&&(a["Transaction Id"]=b.TransactionId);},this.extractActionAttributes=function(a,c){b.extractTransactionId(a,c),c.Affiliation&&(a.Affiliation=c.Affiliation),c.CouponCode&&(a["Coupon Code"]=c.CouponCode),c.TotalAmount&&(a["Total Amount"]=c.TotalAmount),c.ShippingAmount&&(a["Shipping Amount"]=c.ShippingAmount),c.TaxAmount&&(a["Tax Amount"]=c.TaxAmount),c.CheckoutOptions&&(a["Checkout Options"]=c.CheckoutOptions),c.CheckoutStep&&(a["Checkout Step"]=c.CheckoutStep);},this.extractPromotionAttributes=function(a,b){b.Id&&(a.Id=b.Id),b.Creative&&(a.Creative=b.Creative),b.Name&&(a.Name=b.Name),b.Position&&(a.Position=b.Position);},this.buildProductList=function(a,b){return b?Array.isArray(b)?b:[b]:a.ShoppingCart.ProductList},this.createProduct=function(b,c,d,e,f,g,h,i,j,k){return (k=a._Helpers.sanitizeAttributes(k,b),"string"!=typeof b)?(a.Logger.error("Name is required when creating a product"),null):a._Helpers.Validators.isStringOrNumber(c)?a._Helpers.Validators.isStringOrNumber(d)?(d=a._Helpers.parseNumber(d),i&&!a._Helpers.Validators.isNumber(i)&&(a.Logger.error("Position must be a number, it will be set to null."),i=null),e=a._Helpers.Validators.isStringOrNumber(e)?a._Helpers.parseNumber(e):1,{Name:b,Sku:c,Price:d,Quantity:e,Brand:h,Variant:f,Category:g,Position:i,CouponCode:j,TotalAmount:e*d,Attributes:k}):(a.Logger.error("Price is required when creating a product, and must be a string or a number"),null):(a.Logger.error("SKU is required when creating a product, and must be a string or a number"),null)},this.createPromotion=function(b,c,d,e){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Creative:c,Name:d,Position:e}:(a.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired),null)},this.createImpression=function(b,c){return "string"==typeof b?c?{Name:b,Product:c}:(a.Logger.error("Product is required when creating an impression."),null):(a.Logger.error("Name is required when creating an impression."),null)},this.createTransactionAttributes=function(b,c,d,e,f,g){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Affiliation:c,CouponCode:d,Revenue:e,Shipping:f,Tax:g}:(a.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired),null)},this.expandProductImpression=function(c){var d=[];return c.ProductImpressions?(c.ProductImpressions.forEach(function(e){e.ProductList&&e.ProductList.forEach(function(f){var g=a._Helpers.extend(!1,{},c.EventAttributes);if(f.Attributes)for(var h in f.Attributes)g[h]=f.Attributes[h];b.extractProductAttributes(g,f),e.ProductImpressionList&&(g["Product Impression List"]=e.ProductImpressionList);var i=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName("Impression"),data:g,eventType:Types.EventType.Transaction});d.push(i);});}),d):d},this.expandCommerceEvent=function(a){return a?b.expandProductAction(a).concat(b.expandPromotionAction(a)).concat(b.expandProductImpression(a)):null},this.expandPromotionAction=function(c){var d=[];if(!c.PromotionAction)return d;var e=c.PromotionAction.PromotionList;return e.forEach(function(e){var f=a._Helpers.extend(!1,{},c.EventAttributes);b.extractPromotionAttributes(f,e);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(c.PromotionAction.PromotionActionType)),data:f,eventType:Types.EventType.Transaction});d.push(g);}),d},this.expandProductAction=function(c){var d=[];if(!c.ProductAction)return d;var e=!1;if(c.ProductAction.ProductActionType===Types.ProductActionType.Purchase||c.ProductAction.ProductActionType===Types.ProductActionType.Refund){var f=a._Helpers.extend(!1,{},c.EventAttributes);f["Product Count"]=c.ProductAction.ProductList?c.ProductAction.ProductList.length:0,b.extractActionAttributes(f,c.ProductAction),c.CurrencyCode&&(f["Currency Code"]=c.CurrencyCode);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType),!0),data:f,eventType:Types.EventType.Transaction});d.push(g);}else e=!0;var h=c.ProductAction.ProductList;return h?(h.forEach(function(f){var g=a._Helpers.extend(!1,c.EventAttributes,f.Attributes);e?b.extractActionAttributes(g,c.ProductAction):b.extractTransactionId(g,c.ProductAction),b.extractProductAttributes(g,f);var h=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType)),data:g,eventType:Types.EventType.Transaction});d.push(h);}),d):d},this.createCommerceEventObject=function(b){var c;return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(c=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce}),c.EventName="eCommerce - ",c.CurrencyCode=a._Store.currencyCode,c.ShoppingCart=[],c.CustomFlags=b,c):(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(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
500
501
  return a._Helpers.parseNumber(b)};}
501
502
 
502
- function createSDKConfig(a){var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(c in Constants.DefaultUrls)b[c]=Constants.DefaultUrls[c];return b}function Store(a,b){var c={isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,migrationData:{},serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:"",configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},migratingToIDSyncCookies:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[]};for(var d in c)this[d]=c[d];// Set configuration to default settings
503
- if(this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){if(a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&b._Helpers.returnConvertedBoolean(a.isDevelopmentMode),a.hasOwnProperty("v1SecureServiceUrl")&&(this.SDKConfig.v1SecureServiceUrl=a.v1SecureServiceUrl),a.hasOwnProperty("v2SecureServiceUrl")&&(this.SDKConfig.v2SecureServiceUrl=a.v2SecureServiceUrl),a.hasOwnProperty("v3SecureServiceUrl")&&(this.SDKConfig.v3SecureServiceUrl=a.v3SecureServiceUrl),a.hasOwnProperty("identityUrl")&&(this.SDKConfig.identityUrl=a.identityUrl),a.hasOwnProperty("aliasUrl")&&(this.SDKConfig.aliasUrl=a.aliasUrl),a.hasOwnProperty("configUrl")&&(this.SDKConfig.configUrl=a.configUrl),a.hasOwnProperty("logLevel")&&(this.SDKConfig.logLevel=a.logLevel),this.SDKConfig.useNativeSdk=!!a.hasOwnProperty("useNativeSdk")&&a.useNativeSdk,a.hasOwnProperty("kits")&&(this.SDKConfig.kits=a.kits),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 e=a.identityCallback;b._Helpers.Validators.isFunction(e)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(e)," . 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},a.dataPlan.hasOwnProperty("planId")&&("string"==typeof a.dataPlan.planId?b._Helpers.isSlug(a.dataPlan.planId)?this.SDKConfig.dataPlan.PlanId=a.dataPlan.planId:b.Logger.error("Your data plan id must be in a slug format"):b.Logger.error("Your data plan id must be a string")),a.dataPlan.hasOwnProperty("planVersion")&&("number"==typeof a.dataPlan.planVersion?this.SDKConfig.dataPlan.PlanVersion=a.dataPlan.planVersion:b.Logger.error("Your data plan version must be a number"))),this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,a.hasOwnProperty("customFlags")&&(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 f=a.dataPlanOptions;f.hasOwnProperty("dataPlanVersion")&&f.hasOwnProperty("blockUserAttributes")&&f.hasOwnProperty("blockEventAttributes")&&f.hasOwnProperty("blockEvents")&&f.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)),a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventsV3)||(this.SDKConfig.flags[Constants.FeatureFlags.EventsV3]=0),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventBatchingIntervalMillis)||(this.SDKConfig.flags[Constants.FeatureFlags.EventBatchingIntervalMillis]=Constants.DefaultConfig.uploadInterval),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.ReportBatching)||(this.SDKConfig.flags[Constants.FeatureFlags.ReportBatching]=!1);}}
503
+ function createSDKConfig(a){// TODO: Refactor to create a default config object
504
+ 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.DefaultUrls)b[c]=Constants.DefaultUrls[c];return b}function Store(a,b){var c={isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,migrationData:{},serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},migratingToIDSyncCookies:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[]};for(var d in c)this[d]=c[d];// Set configuration to default settings
505
+ if(this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){if(a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&b._Helpers.returnConvertedBoolean(a.isDevelopmentMode),a.hasOwnProperty("v1SecureServiceUrl")&&(this.SDKConfig.v1SecureServiceUrl=a.v1SecureServiceUrl),a.hasOwnProperty("v2SecureServiceUrl")&&(this.SDKConfig.v2SecureServiceUrl=a.v2SecureServiceUrl),a.hasOwnProperty("v3SecureServiceUrl")&&(this.SDKConfig.v3SecureServiceUrl=a.v3SecureServiceUrl),a.hasOwnProperty("identityUrl")&&(this.SDKConfig.identityUrl=a.identityUrl),a.hasOwnProperty("aliasUrl")&&(this.SDKConfig.aliasUrl=a.aliasUrl),a.hasOwnProperty("configUrl")&&(this.SDKConfig.configUrl=a.configUrl),a.hasOwnProperty("logLevel")&&(this.SDKConfig.logLevel=a.logLevel),this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},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 e=a.identityCallback;b._Helpers.Validators.isFunction(e)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(e)+" . 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 f=a.dataPlan;f.planId&&(isDataPlanSlug(f.planId)?this.SDKConfig.dataPlan.PlanId=f.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),f.planVersion&&(isNumber(f.planVersion)?this.SDKConfig.dataPlan.PlanVersion=f.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 g=a.dataPlanOptions;g.hasOwnProperty("dataPlanVersion")&&g.hasOwnProperty("blockUserAttributes")&&g.hasOwnProperty("blockEventAttributes")&&g.hasOwnProperty("blockEvents")&&g.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)),a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventsV3)||(this.SDKConfig.flags[Constants.FeatureFlags.EventsV3]=0),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventBatchingIntervalMillis)||(this.SDKConfig.flags[Constants.FeatureFlags.EventBatchingIntervalMillis]=Constants.DefaultConfig.uploadInterval),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.ReportBatching)||(this.SDKConfig.flags[Constants.FeatureFlags.ReportBatching]=!1);}}
504
506
 
505
507
  function Logger(a){var b=this,c=a.logLevel||"warning";this.logger=a.hasOwnProperty("logger")?a.logger:new ConsoleLogger,this.verbose=function(a){"none"!==c&&b.logger.verbose&&"verbose"===c&&b.logger.verbose(a);},this.warning=function(a){"none"!==c&&b.logger.warning&&("verbose"===c||"warning"===c)&&b.logger.warning(a);},this.error=function(a){"none"!==c&&b.logger.error&&b.logger.error(a);},this.setLogLevel=function(a){c=a;};}function ConsoleLogger(){this.verbose=function(a){console&&console.info&&console.info(a);},this.error=function(a){console&&console.error&&console.error(a);},this.warning=function(a){console&&console.warn&&console.warn(a);};}
506
508
 
@@ -736,7 +738,7 @@ if(!d||!Array.isArray(d))l=!0;else if(n.length!==d.length)l=!0;else for(var c=0;
736
738
  * @return {Array} array of cart products
737
739
  * @deprecated
738
740
  */getCartProducts:function getCartProducts(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().getCartProducts() will be removed in future releases"),t._Persistence.getCartProducts(e)}}},this.parseIdentityResponse=function(r,i,n,o,a){var d,g,l,u,p=t.Identity.getUser(i),c={},y=p?p.getUserIdentities().userIdentities:{},I=t._Helpers.extend({},y);t._Store.identityCallInFlight=!1;try{if(t.Logger.verbose("Parsing \""+a+"\" identity response from server"),r.responseText&&(l=JSON.parse(r.responseText),l.hasOwnProperty("is_logged_in")&&(t._Store.isLoggedIn=l.is_logged_in)),(!p||p.getMPID()&&l.mpid&&l.mpid!==p.getMPID())&&(t._Store.mpid=l.mpid,p&&t._Persistence.setLastSeenTime(i),!t._Persistence.getFirstSeenTime(l.mpid)&&(g=!0),t._Persistence.setFirstSeenTime(l.mpid)),200===r.status){if("modify"===a)c=t._Identity.IdentityRequest.combineUserIdentities(y,o.userIdentities),t._Persistence.saveUserIdentitiesToPersistence(i,c);else {var _=s.IdentityAPI.getUser(l.mpid),v=_?_.getUserIdentities().userIdentities:{},m=t._Helpers.extend({},v);//if there is any previous migration data
739
- if(t.Logger.verbose("Successfully parsed Identity Response"),"identify"==a&&p&&l.mpid===p.getMPID()&&t._Persistence.setFirstSeenTime(l.mpid),u=t._Store.currentSessionMPIDs.indexOf(l.mpid),t._Store.sessionId&&l.mpid&&i!==l.mpid&&0>u&&t._Store.currentSessionMPIDs.push(l.mpid),-1<u&&(t._Store.currentSessionMPIDs=t._Store.currentSessionMPIDs.slice(0,u).concat(t._Store.currentSessionMPIDs.slice(u+1,t._Store.currentSessionMPIDs.length)),t._Store.currentSessionMPIDs.push(l.mpid)),t._CookieSyncManager.attemptCookieSync(i,l.mpid,g),s.checkIdentitySwap(i,l.mpid,t._Store.currentSessionMPIDs),Object.keys(t._Store.migrationData).length){c=t._Store.migrationData.userIdentities||{};var S=t._Store.migrationData.userAttributes||{};t._Persistence.saveUserAttributesToPersistence(l.mpid,S);}else o&&o.userIdentities&&Object.keys(o.userIdentities).length&&(c=s.IdentityRequest.combineUserIdentities(v,o.userIdentities));t._Persistence.saveUserIdentitiesToPersistence(l.mpid,c),t._Persistence.update(),t._Persistence.findPrevCookiesBasedOnUI(o),t._Store.context=l.context||t._Store.context;}if(d=t.Identity.getCurrentUser(),o&&o.onUserAlias&&t._Helpers.Validators.isFunction(o.onUserAlias))try{t.Logger.warning("Deprecated function onUserAlias will be removed in future releases"),o.onUserAlias(p,d);}catch(s){t.Logger.error("There was an error with your onUserAlias function - "+s);}var P=t._Persistence.getPersistence();d&&(t._Persistence.storeDataInMemory(P,d.getMPID()),(!p||d.getMPID()!==p.getMPID()||p.isLoggedIn()!==d.isLoggedIn())&&t._Forwarders.initForwarders(d.getUserIdentities().userIdentities,t._APIClient.prepareForwardingStats),t._Forwarders.setForwarderUserIdentities(d.getUserIdentities().userIdentities),t._Forwarders.setForwarderOnIdentityComplete(d,a),t._Forwarders.setForwarderOnUserIdentified(d,a));var b={};for(var A in c)b[Types.IdentityType.getIdentityName(t._Helpers.parseNumber(A))]=c[A];s.sendUserIdentityChangeEvent(b,a,l.mpid,"modify"===a?I:m);}n?0===r.status?t._Helpers.invokeCallback(n,HTTPCodes$2.noHttpCoverage,l||null,d):t._Helpers.invokeCallback(n,r.status,l||null,d):l&&l.errors&&l.errors.length&&t.Logger.error("Received HTTP response code of "+r.status+" - "+l.errors[0].message),t._APIClient.processQueuedEvents();}catch(s){n&&t._Helpers.invokeCallback(n,r.status,l||null),t.Logger.error("Error parsing JSON response from Identity server: "+s);}},this.sendUserIdentityChangeEvent=function(e,r,i,n){var o,a;if(t._APIClient.shouldEnableBatching()&&(i||"modify"===r))for(var d in o=this.IdentityAPI.getUser(i),e)if(n[d]!==e[d]){var g=!n[d];a=s.createUserIdentityChange(d,e[d],n[d],g,o),t._APIClient.sendEventToServer(a);}},this.createUserIdentityChange=function(e,s,r,i,n){var o;return o=t._ServerModel.createEventObject({messageType:Types.MessageType.UserIdentityChange,userIdentityChanges:{New:{IdentityType:e,Identity:s,CreatedThisBatch:i},Old:{IdentityType:e,Identity:r,CreatedThisBatch:!1}},userInMemory:n}),o},this.sendUserAttributeChangeEvent=function(e,r,i,n,o,a){if(t._APIClient.shouldEnableBatching()){var d=s.createUserAttributeChange(e,r,i,n,o,a);d&&t._APIClient.sendEventToServer(d);}},this.createUserAttributeChange=function(e,s,r,i,n,o){r||(r=null);var a;return s!==r&&(a=t._ServerModel.createEventObject({messageType:Types.MessageType.UserAttributeChange,userAttributeChanges:{UserAttributeName:e,New:s,Old:r||null,Deleted:n,IsNewAttribute:i}},o)),a};}
741
+ if(t.Logger.verbose("Successfully parsed Identity Response"),"identify"==a&&p&&l.mpid===p.getMPID()&&t._Persistence.setFirstSeenTime(l.mpid),u=t._Store.currentSessionMPIDs.indexOf(l.mpid),t._Store.sessionId&&l.mpid&&i!==l.mpid&&0>u&&t._Store.currentSessionMPIDs.push(l.mpid),-1<u&&(t._Store.currentSessionMPIDs=t._Store.currentSessionMPIDs.slice(0,u).concat(t._Store.currentSessionMPIDs.slice(u+1,t._Store.currentSessionMPIDs.length)),t._Store.currentSessionMPIDs.push(l.mpid)),t._CookieSyncManager.attemptCookieSync(i,l.mpid,g),s.checkIdentitySwap(i,l.mpid,t._Store.currentSessionMPIDs),Object.keys(t._Store.migrationData).length){c=t._Store.migrationData.userIdentities||{};var S=t._Store.migrationData.userAttributes||{};t._Persistence.saveUserAttributesToPersistence(l.mpid,S);}else o&&o.userIdentities&&Object.keys(o.userIdentities).length&&(c=s.IdentityRequest.combineUserIdentities(v,o.userIdentities));t._Persistence.saveUserIdentitiesToPersistence(l.mpid,c),t._Persistence.update(),t._Persistence.findPrevCookiesBasedOnUI(o),t._Store.context=l.context||t._Store.context;}if(d=t.Identity.getCurrentUser(),o&&o.onUserAlias&&t._Helpers.Validators.isFunction(o.onUserAlias))try{t.Logger.warning("Deprecated function onUserAlias will be removed in future releases"),o.onUserAlias(p,d);}catch(s){t.Logger.error("There was an error with your onUserAlias function - "+s);}var P=t._Persistence.getPersistence();d&&(t._Persistence.storeDataInMemory(P,d.getMPID()),(!p||d.getMPID()!==p.getMPID()||p.isLoggedIn()!==d.isLoggedIn())&&t._Forwarders.initForwarders(d.getUserIdentities().userIdentities,t._APIClient.prepareForwardingStats),t._Forwarders.setForwarderUserIdentities(d.getUserIdentities().userIdentities),t._Forwarders.setForwarderOnIdentityComplete(d,a),t._Forwarders.setForwarderOnUserIdentified(d,a));var b={};for(var A in c)b[Types.IdentityType.getIdentityName(t._Helpers.parseNumber(A))]=c[A];s.sendUserIdentityChangeEvent(b,a,l.mpid,"modify"===a?I:m);}n?0===r.status?t._Helpers.invokeCallback(n,HTTPCodes$2.noHttpCoverage,l||null,d):t._Helpers.invokeCallback(n,r.status,l||null,d):l&&l.errors&&l.errors.length&&t.Logger.error("Received HTTP response code of "+r.status+" - "+l.errors[0].message),t._APIClient.processQueuedEvents();}catch(s){n&&t._Helpers.invokeCallback(n,r.status,l||null),t.Logger.error("Error parsing JSON response from Identity server: "+s);}},this.sendUserIdentityChangeEvent=function(e,r,i,n){var o,a;if(t._APIClient.shouldEnableBatching()&&(i||"modify"===r))for(var d in o=this.IdentityAPI.getUser(i),e)if(n[d]!==e[d]){var g=!n[d];a=s.createUserIdentityChange(d,e[d],n[d],g,o),t._APIClient.sendEventToServer(a);}},this.createUserIdentityChange=function(e,s,r,i,n){var o;return o=t._ServerModel.createEventObject({messageType:Types.MessageType.UserIdentityChange,userIdentityChanges:{New:{IdentityType:e,Identity:s,CreatedThisBatch:i},Old:{IdentityType:e,Identity:r,CreatedThisBatch:!1}},userInMemory:n}),o},this.sendUserAttributeChangeEvent=function(e,r,i,n,o,a){if(t._APIClient.shouldEnableBatching()){var d=s.createUserAttributeChange(e,r,i,n,o,a);d&&t._APIClient.sendEventToServer(d);}},this.createUserAttributeChange=function(e,s,r,i,n,o){"undefined"==typeof r&&(r=null);var a;return s!==r&&(a=t._ServerModel.createEventObject({messageType:Types.MessageType.UserAttributeChange,userAttributeChanges:{UserAttributeName:e,New:s,Old:r,Deleted:n,IsNewAttribute:i}},o)),a};}
740
742
 
741
743
  function Consent(a){var b=this,c="data_sale_opt_out";// this function is called when consent is required to determine if a cookie sync should happen, or a forwarder should be initialized
742
744
  this.isEnabledForUserConsent=function(b,c){if(!b||!b.values||!b.values.length)return !0;if(!c)return !1;var d,e={},f=c.getConsentState();if(f){// the server hashes consent purposes in the following way:
@@ -32,7 +32,7 @@ function _defineProperty(obj, key, value) {
32
32
 
33
33
  var _TriggerUploadType,MessageType$1={SessionStart:1,SessionEnd:2,PageView:3,PageEvent:4,CrashReport:5,OptOut:6,AppStateTransition:10,Profile:14,Commerce:16,Media:20,UserAttributeChange:17,UserIdentityChange:18},TriggerUploadType=(_TriggerUploadType={},_defineProperty(_TriggerUploadType,MessageType$1.Commerce,1),_defineProperty(_TriggerUploadType,MessageType$1.UserAttributeChange,1),_defineProperty(_TriggerUploadType,MessageType$1.UserIdentityChange,1),_TriggerUploadType),EventType={Unknown:0,Navigation:1,Location:2,Search:3,Transaction:4,UserContent:5,UserPreference:6,Social:7,Other:8,Media:9,getName:function getName(a){return a===EventType.Unknown?"Unknown":a===EventType.Navigation?"Navigation":a===EventType.Location?"Location":a===EventType.Search?"Search":a===EventType.Transaction?"Transaction":a===EventType.UserContent?"User Content":a===EventType.UserPreference?"User Preference":a===EventType.Social?"Social":a===CommerceEventType.ProductAddToCart?"Product Added to Cart":a===CommerceEventType.ProductAddToWishlist?"Product Added to Wishlist":a===CommerceEventType.ProductCheckout?"Product Checkout":a===CommerceEventType.ProductCheckoutOption?"Product Checkout Options":a===CommerceEventType.ProductClick?"Product Click":a===CommerceEventType.ProductImpression?"Product Impression":a===CommerceEventType.ProductPurchase?"Product Purchased":a===CommerceEventType.ProductRefund?"Product Refunded":a===CommerceEventType.ProductRemoveFromCart?"Product Removed From Cart":a===CommerceEventType.ProductRemoveFromWishlist?"Product Removed from Wishlist":a===CommerceEventType.ProductViewDetail?"Product View Details":a===CommerceEventType.PromotionClick?"Promotion Click":a===CommerceEventType.PromotionView?"Promotion View":"Other"}},CommerceEventType={ProductAddToCart:10,ProductRemoveFromCart:11,ProductCheckout:12,ProductCheckoutOption:13,ProductClick:14,ProductViewDetail:15,ProductPurchase:16,ProductRefund:17,PromotionView:18,PromotionClick:19,ProductAddToWishlist:20,ProductRemoveFromWishlist:21,ProductImpression:22},IdentityType={Other:0,CustomerId:1,Facebook:2,Twitter:3,Google:4,Microsoft:5,Yahoo:6,Email:7,FacebookCustomAudienceId:9,Other2:10,Other3:11,Other4:12,Other5:13,Other6:14,Other7:15,Other8:16,Other9:17,Other10:18,MobileNumber:19,PhoneNumber2:20,PhoneNumber3:21};IdentityType.isValid=function(a){if("number"==typeof a)for(var b in IdentityType)if(IdentityType.hasOwnProperty(b)&&IdentityType[b]===a)return !0;return !1},IdentityType.getName=function(a){return a===window.mParticle.IdentityType.CustomerId?"Customer ID":a===window.mParticle.IdentityType.Facebook?"Facebook ID":a===window.mParticle.IdentityType.Twitter?"Twitter ID":a===window.mParticle.IdentityType.Google?"Google ID":a===window.mParticle.IdentityType.Microsoft?"Microsoft ID":a===window.mParticle.IdentityType.Yahoo?"Yahoo ID":a===window.mParticle.IdentityType.Email?"Email":a===window.mParticle.IdentityType.FacebookCustomAudienceId?"Facebook App User ID":"Other ID"},IdentityType.getIdentityType=function(a){return "other"===a?IdentityType.Other:"customerid"===a?IdentityType.CustomerId:"facebook"===a?IdentityType.Facebook:"twitter"===a?IdentityType.Twitter:"google"===a?IdentityType.Google:"microsoft"===a?IdentityType.Microsoft:"yahoo"===a?IdentityType.Yahoo:"email"===a?IdentityType.Email:"facebookcustomaudienceid"===a?IdentityType.FacebookCustomAudienceId:"other2"===a?IdentityType.Other2:"other3"===a?IdentityType.Other3:"other4"===a?IdentityType.Other4:"other5"===a?IdentityType.Other5:"other6"===a?IdentityType.Other6:"other7"===a?IdentityType.Other7:"other8"===a?IdentityType.Other8:"other9"===a?IdentityType.Other9:"other10"===a?IdentityType.Other10:"mobile_number"===a?IdentityType.MobileNumber:"phone_number_2"===a?IdentityType.PhoneNumber2:!("phone_number_3"!=a)&&IdentityType.PhoneNumber3},IdentityType.getIdentityName=function(a){return a===IdentityType.Other?"other":a===IdentityType.CustomerId?"customerid":a===IdentityType.Facebook?"facebook":a===IdentityType.Twitter?"twitter":a===IdentityType.Google?"google":a===IdentityType.Microsoft?"microsoft":a===IdentityType.Yahoo?"yahoo":a===IdentityType.Email?"email":a===IdentityType.FacebookCustomAudienceId?"facebookcustomaudienceid":a===IdentityType.Other2?"other2":a===IdentityType.Other3?"other3":a===IdentityType.Other4?"other4":a===IdentityType.Other5?"other5":a===IdentityType.Other6?"other6":a===IdentityType.Other7?"other7":a===IdentityType.Other8?"other8":a===IdentityType.Other9?"other9":a===IdentityType.Other10?"other10":a===IdentityType.MobileNumber?"mobile_number":a===IdentityType.PhoneNumber2?"phone_number_2":a===IdentityType.PhoneNumber3?"phone_number_3":void 0};var ProductActionType={Unknown:0,AddToCart:1,RemoveFromCart:2,Checkout:3,CheckoutOption:4,Click:5,ViewDetail:6,Purchase:7,Refund:8,AddToWishlist:9,RemoveFromWishlist:10};ProductActionType.getName=function(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"},ProductActionType.getExpansionName=function(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};PromotionActionType.getName=function(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"},PromotionActionType.getExpansionName=function(a){return a===PromotionActionType.PromotionView?"view":a===PromotionActionType.PromotionClick?"click":"unknown"};var ProfileMessageType={Logout:3},ApplicationTransitionType$1={AppInit:1};var Types = {MessageType:MessageType$1,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,TriggerUploadType:TriggerUploadType};
34
34
 
35
- var version = "2.17.2";
35
+ var version = "2.17.4";
36
36
 
37
37
  var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{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"},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
38
38
  },DefaultUrls:{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/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},SDKv2NonMPIDCookieKeys:{gs:1,cu:1,l:1,globalSettings:1,currentUserMPID:1},HTTPCodes:{noHttpCoverage:-1,activeIdentityRequest:-2,activeSession:-3,validationIssue:-4,nativeIdentityRequest:-5,loggingDisabledOrMissingAPIKey:-6,tooManyRequests:429},FeatureFlags:{ReportBatching:"reportBatching",EventsV3:"eventsV3",EventBatchingIntervalMillis:"eventBatchingIntervalMillis"},DefaultInstance:"default_instance"};
@@ -379,7 +379,7 @@ var b=parseInt(a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventsV3),10);if
379
379
  // need to be set, or if we are still fetching the config (self hosted only), and so require delaying events
380
380
  return g&&(f=g.getMPID()),a._Store.requireDelay=a._Helpers.isDelayedByIntegration(a._preInit.integrationDelays,a._Store.integrationDelayTimeoutStart,Date.now()),f&&!a._Store.requireDelay&&a._Store.configurationLoaded?void(this.processQueuedEvents(),c&&e.shouldUploadEvent&&(this.shouldEnableBatching()?this.queueEventForBatchUpload(c):this.sendSingleEventToServer(c)),c&&c.EventName!==Types.MessageType.AppStateTransition&&(b&&b.kitBlockingEnabled&&(c=b.createBlockedEvent(c)),c&&a._Forwarders.sendEventToForwarders(c))):(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.sendSingleEventToServer=function(b){if(b.EventDataType!==Types.MessageType.Media){var c,d=function xhrCallback(){4===c.readyState&&(a.Logger.verbose("Received "+c.statusText+" from server"),a._Persistence.update());};if(!b)return void a.Logger.error(Messages$9.ErrorMessages.EventEmpty);if(a.Logger.verbose(Messages$9.InformationMessages.SendHttp),c=a._Helpers.createXHR(d),c)try{c.open("post",a._Helpers.createServiceUrl(a._Store.SDKConfig.v2SecureServiceUrl,a._Store.devToken)+"/Events"),c.send(JSON.stringify(a._ServerModel.convertEventToDTO(b)));}catch(b){a.Logger.error("Error sending event to mParticle servers. "+b);}}},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.sendSingleForwardingStatsToServer=function(b){var c,d;try{var e=function xhrCallback(){4===f.readyState&&202===f.status&&a.Logger.verbose("Successfully sent "+f.statusText+" from server");},f=a._Helpers.createXHR(e);c=a._Helpers.createServiceUrl(a._Store.SDKConfig.v1SecureServiceUrl,a._Store.devToken),d=b,f&&(f.open("post",c+"/Forwarding"),f.send(JSON.stringify(d)));}catch(b){a.Logger.error("Error sending forwarding stats to mParticle servers.");}},this.prepareForwardingStats=function(b,d){var e,f=a._Forwarders.getForwarderStatsQueue();b&&b.isVisible&&(e={mid:b.id,esid:b.eventSubscriptionId,n:d.EventName,attrs:d.EventAttributes,sdk:d.SDKVersion,dt:d.EventDataType,et:d.EventCategory,dbg:d.Debug,ct:d.Timestamp,eec:d.ExpandedEventCount,dp:d.DataPlan},a._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)?(f.push(e),a._Forwarders.setForwarderStatsQueue(f)):c.sendSingleForwardingStatsToServer(e));};}
381
381
 
382
- var slugify = {exports: {}};
382
+ var slugify$1 = {exports: {}};
383
383
 
384
384
  (function (module, exports) {
385
385
  (function (name, root, factory) {
@@ -443,14 +443,15 @@ var slugify = {exports: {}};
443
443
 
444
444
  return replace
445
445
  }));
446
- } (slugify));
446
+ } (slugify$1));
447
447
 
448
- var Slugify = slugify.exports;
448
+ var slugify = slugify$1.exports;
449
449
 
450
- var inArray=function(a,b){var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c<d;c++)if(c in a&&a[c]===b)return !0;return !1},findKeyInObject=function(a,b){if(b&&a)for(var c in a)if(a.hasOwnProperty(c)&&c.toLowerCase()===b.toLowerCase())return c;return null},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a};
450
+ var inArray=function(a,b){var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c<d;c++)if(c in a&&a[c]===b)return !0;return !1},findKeyInObject=function(a,b){if(b&&a)for(var c in a)if(a.hasOwnProperty(c)&&c.toLowerCase()===b.toLowerCase())return c;return null},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a},isString=function(a){return "string"==typeof a},isNumber=function(a){return "number"==typeof a},isFunction=function(a){return "function"==typeof a},isDataPlanSlug=function(a){return isString(a)&&a===slugify(a)},isStringOrNumber=function(a){return isString(a)||isNumber(a)};
451
451
 
452
- var Validators={isValidAttributeValue:function isValidAttributeValue(a){return a!==void 0&&!isObject(a)&&!Array.isArray(a)},// Neither null nor undefined can be a valid Key
453
- isValidKeyValue:function isValidKeyValue(a){return !(!a||isObject(a)||Array.isArray(a)||this.isFunction(a))},isStringOrNumber:function isStringOrNumber(a){return "string"==typeof a||"number"==typeof a},isNumber:function isNumber(a){return "number"==typeof a},isFunction:function isFunction(a){return "function"==typeof a},validateIdentities:function validateIdentities(a,b){var c={userIdentities:1,onUserAlias:1,copyUserAttributes:1};if(a){if("modify"===b&&(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
452
+ var Validators={// From ./utils
453
+ isNumber:isNumber,isFunction:isFunction,isStringOrNumber:isStringOrNumber,isValidAttributeValue:function isValidAttributeValue(a){return a!==void 0&&!isObject(a)&&!Array.isArray(a)},// Neither null nor undefined can be a valid Key
454
+ isValidKeyValue:function isValidKeyValue(a){return !(!a||isObject(a)||Array.isArray(a)||this.isFunction(a))},validateIdentities:function validateIdentities(a,b){var c={userIdentities:1,onUserAlias:1,copyUserAttributes:1};if(a){if("modify"===b&&(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
454
455
  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
455
456
  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}}};
456
457
 
@@ -478,7 +479,7 @@ return d// if the placeholder was passed, return
478
479
  /[018]/g,// zeroes, ones, and eights with
479
480
  c.generateUniqueId// random hex digits
480
481
  )},this.filterUserIdentities=function(a,b){var d=[];if(a&&Object.keys(a).length)for(var e in a)if(a.hasOwnProperty(e)){var f=Types.IdentityType.getIdentityType(e);if(!c.inArray(b,f)){var g={Type:f,Identity:a[e]};f===Types.IdentityType.CustomerId?d.unshift(g):d.push(g);}}return d},this.filterUserIdentitiesForForwarders=function(a,b){var d={};if(a&&Object.keys(a).length)for(var e in a)if(a.hasOwnProperty(e)){var f=Types.IdentityType.getIdentityType(e);c.inArray(b,f)||(d[e]=a[e]);}return d},this.filterUserAttributes=function(a,b){var d={};if(a&&Object.keys(a).length)for(var e in a)if(a.hasOwnProperty(e)){var f=c.generateHash(e);c.inArray(b,f)||(d[e]=a[e]);}return d},this.isEventType=function(a){for(var b in Types.EventType)if(Types.EventType.hasOwnProperty(b)&&Types.EventType[b]===a)return !0;return !1},this.parseStringOrNumber=function(a){return Validators.isStringOrNumber(a)?a:null},this.generateHash=function(a){var b,c=0,d=0;if(void 0===a||null===a)return 0;if(a=a.toString().toLowerCase(),Array.prototype.reduce)return a.split("").reduce(function(c,d){return c=(c<<5)-c+d.charCodeAt(0),c&c},0);if(0===a.length)return c;for(d=0;d<a.length;d++)b=a.charCodeAt(d),c=(c<<5)-c+b,c&=c;return c},this.sanitizeAttributes=function(b,d){if(!b||!c.isObject(b))return null;var e={};for(var f in b)// Make sure that attribute values are not objects or arrays, which are not valid
481
- b.hasOwnProperty(f)&&c.Validators.isValidAttributeValue(b[f])?e[f]=b[f]:a.Logger.warning("For '"+d+"', the corresponding attribute value of '"+f+"' must be a string, number, boolean, or null.");return e},this.isDelayedByIntegration=function(b,c,d){if(d-c>a._Store.SDKConfig.integrationDelayTimeout)return !1;for(var e in b){if(!0===b[e])return !0;continue}return !1},this.createMainStorageName=function(a){return a?StorageNames$2.currentStorageName+"_"+a:StorageNames$2.currentStorageName},this.createProductStorageName=function(a){return a?StorageNames$2.currentStorageProductsName+"_"+a:StorageNames$2.currentStorageProductsName},this.isSlug=function(a){return a===Slugify(a)},this.converted=converted,this.findKeyInObject=findKeyInObject,this.parseNumber=parseNumber,this.inArray=inArray,this.isObject=isObject,this.decoded=decoded,this.returnConvertedBoolean=returnConvertedBoolean,this.Validators=Validators;}
482
+ b.hasOwnProperty(f)&&c.Validators.isValidAttributeValue(b[f])?e[f]=b[f]:a.Logger.warning("For '"+d+"', the corresponding attribute value of '"+f+"' must be a string, number, boolean, or null.");return e},this.isDelayedByIntegration=function(b,c,d){if(d-c>a._Store.SDKConfig.integrationDelayTimeout)return !1;for(var e in b){if(!0===b[e])return !0;continue}return !1},this.createMainStorageName=function(a){return a?StorageNames$2.currentStorageName+"_"+a:StorageNames$2.currentStorageName},this.createProductStorageName=function(a){return a?StorageNames$2.currentStorageProductsName+"_"+a:StorageNames$2.currentStorageProductsName},this.converted=converted,this.findKeyInObject=findKeyInObject,this.parseNumber=parseNumber,this.inArray=inArray,this.isObject=isObject,this.decoded=decoded,this.returnConvertedBoolean=returnConvertedBoolean,this.Validators=Validators;}
482
483
 
483
484
  var Messages$8=Constants.Messages,androidBridgeNameBase="mParticleAndroid",iosBridgeNameBase="mParticle";function NativeSdkHelpers(a){var b=this;this.isBridgeV2Available=function(a){if(!a)return !1;var b=iosBridgeNameBase+"_"+a+"_v2";// iOS v2 bridge
484
485
  return !!(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.hasOwnProperty(b))||!!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName===b)||!!window.hasOwnProperty(androidBridgeNameBase+"_"+a+"_v2");// other iOS v2 bridge
@@ -499,8 +500,9 @@ var Messages$5=Constants.Messages;function Ecommerce(a){var b=this;// sanitizes
499
500
  this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty("Id")&&(b.TransactionId=a.Id),a.hasOwnProperty("Affiliation")&&(b.Affiliation=a.Affiliation),a.hasOwnProperty("CouponCode")&&(b.CouponCode=a.CouponCode),a.hasOwnProperty("Revenue")&&(b.TotalAmount=this.sanitizeAmount(a.Revenue,"Revenue")),a.hasOwnProperty("Shipping")&&(b.ShippingAmount=this.sanitizeAmount(a.Shipping,"Shipping")),a.hasOwnProperty("Tax")&&(b.TaxAmount=this.sanitizeAmount(a.Tax,"Tax")),a.hasOwnProperty("Step")&&(b.CheckoutStep=a.Step),a.hasOwnProperty("Option")&&(b.CheckoutOptions=a.Option);},this.getProductActionEventName=function(a){switch(a){case Types.ProductActionType.AddToCart:return "AddToCart";case Types.ProductActionType.AddToWishlist:return "AddToWishlist";case Types.ProductActionType.Checkout:return "Checkout";case Types.ProductActionType.CheckoutOption:return "CheckoutOption";case Types.ProductActionType.Click:return "Click";case Types.ProductActionType.Purchase:return "Purchase";case Types.ProductActionType.Refund:return "Refund";case Types.ProductActionType.RemoveFromCart:return "RemoveFromCart";case Types.ProductActionType.RemoveFromWishlist:return "RemoveFromWishlist";case Types.ProductActionType.ViewDetail:return "ViewDetail";case Types.ProductActionType.Unknown:default:return "Unknown";}},this.getPromotionActionEventName=function(a){return a===Types.PromotionActionType.PromotionClick?"PromotionClick":a===Types.PromotionActionType.PromotionView?"PromotionView":"Unknown"},this.convertProductActionToEventType=function(b){return b===Types.ProductActionType.AddToCart?Types.CommerceEventType.ProductAddToCart:b===Types.ProductActionType.AddToWishlist?Types.CommerceEventType.ProductAddToWishlist:b===Types.ProductActionType.Checkout?Types.CommerceEventType.ProductCheckout:b===Types.ProductActionType.CheckoutOption?Types.CommerceEventType.ProductCheckoutOption:b===Types.ProductActionType.Click?Types.CommerceEventType.ProductClick:b===Types.ProductActionType.Purchase?Types.CommerceEventType.ProductPurchase:b===Types.ProductActionType.Refund?Types.CommerceEventType.ProductRefund:b===Types.ProductActionType.RemoveFromCart?Types.CommerceEventType.ProductRemoveFromCart:b===Types.ProductActionType.RemoveFromWishlist?Types.CommerceEventType.ProductRemoveFromWishlist:b===Types.ProductActionType.Unknown?Types.EventType.Unknown:b===Types.ProductActionType.ViewDetail?Types.CommerceEventType.ProductViewDetail:(a.Logger.error("Could not convert product action type "+b+" to event type"),null)},this.convertPromotionActionToEventType=function(b){return b===Types.PromotionActionType.PromotionClick?Types.CommerceEventType.PromotionClick:b===Types.PromotionActionType.PromotionView?Types.CommerceEventType.PromotionView:(a.Logger.error("Could not convert promotion action type "+b+" to event type"),null)},this.generateExpandedEcommerceName=function(a,b){return "eCommerce - "+a+" - "+(b?"Total":"Item")},this.extractProductAttributes=function(a,b){b.CouponCode&&(a["Coupon Code"]=b.CouponCode),b.Brand&&(a.Brand=b.Brand),b.Category&&(a.Category=b.Category),b.Name&&(a.Name=b.Name),b.Sku&&(a.Id=b.Sku),b.Price&&(a["Item Price"]=b.Price),b.Quantity&&(a.Quantity=b.Quantity),b.Position&&(a.Position=b.Position),b.Variant&&(a.Variant=b.Variant),a["Total Product Amount"]=b.TotalAmount||0;},this.extractTransactionId=function(a,b){b.TransactionId&&(a["Transaction Id"]=b.TransactionId);},this.extractActionAttributes=function(a,c){b.extractTransactionId(a,c),c.Affiliation&&(a.Affiliation=c.Affiliation),c.CouponCode&&(a["Coupon Code"]=c.CouponCode),c.TotalAmount&&(a["Total Amount"]=c.TotalAmount),c.ShippingAmount&&(a["Shipping Amount"]=c.ShippingAmount),c.TaxAmount&&(a["Tax Amount"]=c.TaxAmount),c.CheckoutOptions&&(a["Checkout Options"]=c.CheckoutOptions),c.CheckoutStep&&(a["Checkout Step"]=c.CheckoutStep);},this.extractPromotionAttributes=function(a,b){b.Id&&(a.Id=b.Id),b.Creative&&(a.Creative=b.Creative),b.Name&&(a.Name=b.Name),b.Position&&(a.Position=b.Position);},this.buildProductList=function(a,b){return b?Array.isArray(b)?b:[b]:a.ShoppingCart.ProductList},this.createProduct=function(b,c,d,e,f,g,h,i,j,k){return (k=a._Helpers.sanitizeAttributes(k,b),"string"!=typeof b)?(a.Logger.error("Name is required when creating a product"),null):a._Helpers.Validators.isStringOrNumber(c)?a._Helpers.Validators.isStringOrNumber(d)?(d=a._Helpers.parseNumber(d),i&&!a._Helpers.Validators.isNumber(i)&&(a.Logger.error("Position must be a number, it will be set to null."),i=null),e=a._Helpers.Validators.isStringOrNumber(e)?a._Helpers.parseNumber(e):1,{Name:b,Sku:c,Price:d,Quantity:e,Brand:h,Variant:f,Category:g,Position:i,CouponCode:j,TotalAmount:e*d,Attributes:k}):(a.Logger.error("Price is required when creating a product, and must be a string or a number"),null):(a.Logger.error("SKU is required when creating a product, and must be a string or a number"),null)},this.createPromotion=function(b,c,d,e){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Creative:c,Name:d,Position:e}:(a.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired),null)},this.createImpression=function(b,c){return "string"==typeof b?c?{Name:b,Product:c}:(a.Logger.error("Product is required when creating an impression."),null):(a.Logger.error("Name is required when creating an impression."),null)},this.createTransactionAttributes=function(b,c,d,e,f,g){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Affiliation:c,CouponCode:d,Revenue:e,Shipping:f,Tax:g}:(a.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired),null)},this.expandProductImpression=function(c){var d=[];return c.ProductImpressions?(c.ProductImpressions.forEach(function(e){e.ProductList&&e.ProductList.forEach(function(f){var g=a._Helpers.extend(!1,{},c.EventAttributes);if(f.Attributes)for(var h in f.Attributes)g[h]=f.Attributes[h];b.extractProductAttributes(g,f),e.ProductImpressionList&&(g["Product Impression List"]=e.ProductImpressionList);var i=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName("Impression"),data:g,eventType:Types.EventType.Transaction});d.push(i);});}),d):d},this.expandCommerceEvent=function(a){return a?b.expandProductAction(a).concat(b.expandPromotionAction(a)).concat(b.expandProductImpression(a)):null},this.expandPromotionAction=function(c){var d=[];if(!c.PromotionAction)return d;var e=c.PromotionAction.PromotionList;return e.forEach(function(e){var f=a._Helpers.extend(!1,{},c.EventAttributes);b.extractPromotionAttributes(f,e);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(c.PromotionAction.PromotionActionType)),data:f,eventType:Types.EventType.Transaction});d.push(g);}),d},this.expandProductAction=function(c){var d=[];if(!c.ProductAction)return d;var e=!1;if(c.ProductAction.ProductActionType===Types.ProductActionType.Purchase||c.ProductAction.ProductActionType===Types.ProductActionType.Refund){var f=a._Helpers.extend(!1,{},c.EventAttributes);f["Product Count"]=c.ProductAction.ProductList?c.ProductAction.ProductList.length:0,b.extractActionAttributes(f,c.ProductAction),c.CurrencyCode&&(f["Currency Code"]=c.CurrencyCode);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType),!0),data:f,eventType:Types.EventType.Transaction});d.push(g);}else e=!0;var h=c.ProductAction.ProductList;return h?(h.forEach(function(f){var g=a._Helpers.extend(!1,c.EventAttributes,f.Attributes);e?b.extractActionAttributes(g,c.ProductAction):b.extractTransactionId(g,c.ProductAction),b.extractProductAttributes(g,f);var h=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType)),data:g,eventType:Types.EventType.Transaction});d.push(h);}),d):d},this.createCommerceEventObject=function(b){var c;return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(c=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce}),c.EventName="eCommerce - ",c.CurrencyCode=a._Store.currencyCode,c.ShoppingCart=[],c.CustomFlags=b,c):(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(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
500
501
  return a._Helpers.parseNumber(b)};}
501
502
 
502
- function createSDKConfig(a){var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(c in Constants.DefaultUrls)b[c]=Constants.DefaultUrls[c];return b}function Store(a,b){var c={isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,migrationData:{},serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:"",configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},migratingToIDSyncCookies:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[]};for(var d in c)this[d]=c[d];// Set configuration to default settings
503
- if(this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){if(a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&b._Helpers.returnConvertedBoolean(a.isDevelopmentMode),a.hasOwnProperty("v1SecureServiceUrl")&&(this.SDKConfig.v1SecureServiceUrl=a.v1SecureServiceUrl),a.hasOwnProperty("v2SecureServiceUrl")&&(this.SDKConfig.v2SecureServiceUrl=a.v2SecureServiceUrl),a.hasOwnProperty("v3SecureServiceUrl")&&(this.SDKConfig.v3SecureServiceUrl=a.v3SecureServiceUrl),a.hasOwnProperty("identityUrl")&&(this.SDKConfig.identityUrl=a.identityUrl),a.hasOwnProperty("aliasUrl")&&(this.SDKConfig.aliasUrl=a.aliasUrl),a.hasOwnProperty("configUrl")&&(this.SDKConfig.configUrl=a.configUrl),a.hasOwnProperty("logLevel")&&(this.SDKConfig.logLevel=a.logLevel),this.SDKConfig.useNativeSdk=!!a.hasOwnProperty("useNativeSdk")&&a.useNativeSdk,a.hasOwnProperty("kits")&&(this.SDKConfig.kits=a.kits),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 e=a.identityCallback;b._Helpers.Validators.isFunction(e)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(e)," . 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},a.dataPlan.hasOwnProperty("planId")&&("string"==typeof a.dataPlan.planId?b._Helpers.isSlug(a.dataPlan.planId)?this.SDKConfig.dataPlan.PlanId=a.dataPlan.planId:b.Logger.error("Your data plan id must be in a slug format"):b.Logger.error("Your data plan id must be a string")),a.dataPlan.hasOwnProperty("planVersion")&&("number"==typeof a.dataPlan.planVersion?this.SDKConfig.dataPlan.PlanVersion=a.dataPlan.planVersion:b.Logger.error("Your data plan version must be a number"))),this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,a.hasOwnProperty("customFlags")&&(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 f=a.dataPlanOptions;f.hasOwnProperty("dataPlanVersion")&&f.hasOwnProperty("blockUserAttributes")&&f.hasOwnProperty("blockEventAttributes")&&f.hasOwnProperty("blockEvents")&&f.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)),a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventsV3)||(this.SDKConfig.flags[Constants.FeatureFlags.EventsV3]=0),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventBatchingIntervalMillis)||(this.SDKConfig.flags[Constants.FeatureFlags.EventBatchingIntervalMillis]=Constants.DefaultConfig.uploadInterval),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.ReportBatching)||(this.SDKConfig.flags[Constants.FeatureFlags.ReportBatching]=!1);}}
503
+ function createSDKConfig(a){// TODO: Refactor to create a default config object
504
+ 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.DefaultUrls)b[c]=Constants.DefaultUrls[c];return b}function Store(a,b){var c={isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,migrationData:{},serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},migratingToIDSyncCookies:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[]};for(var d in c)this[d]=c[d];// Set configuration to default settings
505
+ if(this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){if(a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&b._Helpers.returnConvertedBoolean(a.isDevelopmentMode),a.hasOwnProperty("v1SecureServiceUrl")&&(this.SDKConfig.v1SecureServiceUrl=a.v1SecureServiceUrl),a.hasOwnProperty("v2SecureServiceUrl")&&(this.SDKConfig.v2SecureServiceUrl=a.v2SecureServiceUrl),a.hasOwnProperty("v3SecureServiceUrl")&&(this.SDKConfig.v3SecureServiceUrl=a.v3SecureServiceUrl),a.hasOwnProperty("identityUrl")&&(this.SDKConfig.identityUrl=a.identityUrl),a.hasOwnProperty("aliasUrl")&&(this.SDKConfig.aliasUrl=a.aliasUrl),a.hasOwnProperty("configUrl")&&(this.SDKConfig.configUrl=a.configUrl),a.hasOwnProperty("logLevel")&&(this.SDKConfig.logLevel=a.logLevel),this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},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 e=a.identityCallback;b._Helpers.Validators.isFunction(e)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(e)+" . 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 f=a.dataPlan;f.planId&&(isDataPlanSlug(f.planId)?this.SDKConfig.dataPlan.PlanId=f.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),f.planVersion&&(isNumber(f.planVersion)?this.SDKConfig.dataPlan.PlanVersion=f.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 g=a.dataPlanOptions;g.hasOwnProperty("dataPlanVersion")&&g.hasOwnProperty("blockUserAttributes")&&g.hasOwnProperty("blockEventAttributes")&&g.hasOwnProperty("blockEvents")&&g.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)),a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventsV3)||(this.SDKConfig.flags[Constants.FeatureFlags.EventsV3]=0),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.EventBatchingIntervalMillis)||(this.SDKConfig.flags[Constants.FeatureFlags.EventBatchingIntervalMillis]=Constants.DefaultConfig.uploadInterval),this.SDKConfig.flags.hasOwnProperty(Constants.FeatureFlags.ReportBatching)||(this.SDKConfig.flags[Constants.FeatureFlags.ReportBatching]=!1);}}
504
506
 
505
507
  function Logger(a){var b=this,c=a.logLevel||"warning";this.logger=a.hasOwnProperty("logger")?a.logger:new ConsoleLogger,this.verbose=function(a){"none"!==c&&b.logger.verbose&&"verbose"===c&&b.logger.verbose(a);},this.warning=function(a){"none"!==c&&b.logger.warning&&("verbose"===c||"warning"===c)&&b.logger.warning(a);},this.error=function(a){"none"!==c&&b.logger.error&&b.logger.error(a);},this.setLogLevel=function(a){c=a;};}function ConsoleLogger(){this.verbose=function(a){console&&console.info&&console.info(a);},this.error=function(a){console&&console.error&&console.error(a);},this.warning=function(a){console&&console.warn&&console.warn(a);};}
506
508
 
@@ -736,7 +738,7 @@ if(!d||!Array.isArray(d))l=!0;else if(n.length!==d.length)l=!0;else for(var c=0;
736
738
  * @return {Array} array of cart products
737
739
  * @deprecated
738
740
  */getCartProducts:function getCartProducts(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().getCartProducts() will be removed in future releases"),t._Persistence.getCartProducts(e)}}},this.parseIdentityResponse=function(r,i,n,o,a){var d,g,l,u,p=t.Identity.getUser(i),c={},y=p?p.getUserIdentities().userIdentities:{},I=t._Helpers.extend({},y);t._Store.identityCallInFlight=!1;try{if(t.Logger.verbose("Parsing \""+a+"\" identity response from server"),r.responseText&&(l=JSON.parse(r.responseText),l.hasOwnProperty("is_logged_in")&&(t._Store.isLoggedIn=l.is_logged_in)),(!p||p.getMPID()&&l.mpid&&l.mpid!==p.getMPID())&&(t._Store.mpid=l.mpid,p&&t._Persistence.setLastSeenTime(i),!t._Persistence.getFirstSeenTime(l.mpid)&&(g=!0),t._Persistence.setFirstSeenTime(l.mpid)),200===r.status){if("modify"===a)c=t._Identity.IdentityRequest.combineUserIdentities(y,o.userIdentities),t._Persistence.saveUserIdentitiesToPersistence(i,c);else {var _=s.IdentityAPI.getUser(l.mpid),v=_?_.getUserIdentities().userIdentities:{},m=t._Helpers.extend({},v);//if there is any previous migration data
739
- if(t.Logger.verbose("Successfully parsed Identity Response"),"identify"==a&&p&&l.mpid===p.getMPID()&&t._Persistence.setFirstSeenTime(l.mpid),u=t._Store.currentSessionMPIDs.indexOf(l.mpid),t._Store.sessionId&&l.mpid&&i!==l.mpid&&0>u&&t._Store.currentSessionMPIDs.push(l.mpid),-1<u&&(t._Store.currentSessionMPIDs=t._Store.currentSessionMPIDs.slice(0,u).concat(t._Store.currentSessionMPIDs.slice(u+1,t._Store.currentSessionMPIDs.length)),t._Store.currentSessionMPIDs.push(l.mpid)),t._CookieSyncManager.attemptCookieSync(i,l.mpid,g),s.checkIdentitySwap(i,l.mpid,t._Store.currentSessionMPIDs),Object.keys(t._Store.migrationData).length){c=t._Store.migrationData.userIdentities||{};var S=t._Store.migrationData.userAttributes||{};t._Persistence.saveUserAttributesToPersistence(l.mpid,S);}else o&&o.userIdentities&&Object.keys(o.userIdentities).length&&(c=s.IdentityRequest.combineUserIdentities(v,o.userIdentities));t._Persistence.saveUserIdentitiesToPersistence(l.mpid,c),t._Persistence.update(),t._Persistence.findPrevCookiesBasedOnUI(o),t._Store.context=l.context||t._Store.context;}if(d=t.Identity.getCurrentUser(),o&&o.onUserAlias&&t._Helpers.Validators.isFunction(o.onUserAlias))try{t.Logger.warning("Deprecated function onUserAlias will be removed in future releases"),o.onUserAlias(p,d);}catch(s){t.Logger.error("There was an error with your onUserAlias function - "+s);}var P=t._Persistence.getPersistence();d&&(t._Persistence.storeDataInMemory(P,d.getMPID()),(!p||d.getMPID()!==p.getMPID()||p.isLoggedIn()!==d.isLoggedIn())&&t._Forwarders.initForwarders(d.getUserIdentities().userIdentities,t._APIClient.prepareForwardingStats),t._Forwarders.setForwarderUserIdentities(d.getUserIdentities().userIdentities),t._Forwarders.setForwarderOnIdentityComplete(d,a),t._Forwarders.setForwarderOnUserIdentified(d,a));var b={};for(var A in c)b[Types.IdentityType.getIdentityName(t._Helpers.parseNumber(A))]=c[A];s.sendUserIdentityChangeEvent(b,a,l.mpid,"modify"===a?I:m);}n?0===r.status?t._Helpers.invokeCallback(n,HTTPCodes$2.noHttpCoverage,l||null,d):t._Helpers.invokeCallback(n,r.status,l||null,d):l&&l.errors&&l.errors.length&&t.Logger.error("Received HTTP response code of "+r.status+" - "+l.errors[0].message),t._APIClient.processQueuedEvents();}catch(s){n&&t._Helpers.invokeCallback(n,r.status,l||null),t.Logger.error("Error parsing JSON response from Identity server: "+s);}},this.sendUserIdentityChangeEvent=function(e,r,i,n){var o,a;if(t._APIClient.shouldEnableBatching()&&(i||"modify"===r))for(var d in o=this.IdentityAPI.getUser(i),e)if(n[d]!==e[d]){var g=!n[d];a=s.createUserIdentityChange(d,e[d],n[d],g,o),t._APIClient.sendEventToServer(a);}},this.createUserIdentityChange=function(e,s,r,i,n){var o;return o=t._ServerModel.createEventObject({messageType:Types.MessageType.UserIdentityChange,userIdentityChanges:{New:{IdentityType:e,Identity:s,CreatedThisBatch:i},Old:{IdentityType:e,Identity:r,CreatedThisBatch:!1}},userInMemory:n}),o},this.sendUserAttributeChangeEvent=function(e,r,i,n,o,a){if(t._APIClient.shouldEnableBatching()){var d=s.createUserAttributeChange(e,r,i,n,o,a);d&&t._APIClient.sendEventToServer(d);}},this.createUserAttributeChange=function(e,s,r,i,n,o){r||(r=null);var a;return s!==r&&(a=t._ServerModel.createEventObject({messageType:Types.MessageType.UserAttributeChange,userAttributeChanges:{UserAttributeName:e,New:s,Old:r||null,Deleted:n,IsNewAttribute:i}},o)),a};}
741
+ if(t.Logger.verbose("Successfully parsed Identity Response"),"identify"==a&&p&&l.mpid===p.getMPID()&&t._Persistence.setFirstSeenTime(l.mpid),u=t._Store.currentSessionMPIDs.indexOf(l.mpid),t._Store.sessionId&&l.mpid&&i!==l.mpid&&0>u&&t._Store.currentSessionMPIDs.push(l.mpid),-1<u&&(t._Store.currentSessionMPIDs=t._Store.currentSessionMPIDs.slice(0,u).concat(t._Store.currentSessionMPIDs.slice(u+1,t._Store.currentSessionMPIDs.length)),t._Store.currentSessionMPIDs.push(l.mpid)),t._CookieSyncManager.attemptCookieSync(i,l.mpid,g),s.checkIdentitySwap(i,l.mpid,t._Store.currentSessionMPIDs),Object.keys(t._Store.migrationData).length){c=t._Store.migrationData.userIdentities||{};var S=t._Store.migrationData.userAttributes||{};t._Persistence.saveUserAttributesToPersistence(l.mpid,S);}else o&&o.userIdentities&&Object.keys(o.userIdentities).length&&(c=s.IdentityRequest.combineUserIdentities(v,o.userIdentities));t._Persistence.saveUserIdentitiesToPersistence(l.mpid,c),t._Persistence.update(),t._Persistence.findPrevCookiesBasedOnUI(o),t._Store.context=l.context||t._Store.context;}if(d=t.Identity.getCurrentUser(),o&&o.onUserAlias&&t._Helpers.Validators.isFunction(o.onUserAlias))try{t.Logger.warning("Deprecated function onUserAlias will be removed in future releases"),o.onUserAlias(p,d);}catch(s){t.Logger.error("There was an error with your onUserAlias function - "+s);}var P=t._Persistence.getPersistence();d&&(t._Persistence.storeDataInMemory(P,d.getMPID()),(!p||d.getMPID()!==p.getMPID()||p.isLoggedIn()!==d.isLoggedIn())&&t._Forwarders.initForwarders(d.getUserIdentities().userIdentities,t._APIClient.prepareForwardingStats),t._Forwarders.setForwarderUserIdentities(d.getUserIdentities().userIdentities),t._Forwarders.setForwarderOnIdentityComplete(d,a),t._Forwarders.setForwarderOnUserIdentified(d,a));var b={};for(var A in c)b[Types.IdentityType.getIdentityName(t._Helpers.parseNumber(A))]=c[A];s.sendUserIdentityChangeEvent(b,a,l.mpid,"modify"===a?I:m);}n?0===r.status?t._Helpers.invokeCallback(n,HTTPCodes$2.noHttpCoverage,l||null,d):t._Helpers.invokeCallback(n,r.status,l||null,d):l&&l.errors&&l.errors.length&&t.Logger.error("Received HTTP response code of "+r.status+" - "+l.errors[0].message),t._APIClient.processQueuedEvents();}catch(s){n&&t._Helpers.invokeCallback(n,r.status,l||null),t.Logger.error("Error parsing JSON response from Identity server: "+s);}},this.sendUserIdentityChangeEvent=function(e,r,i,n){var o,a;if(t._APIClient.shouldEnableBatching()&&(i||"modify"===r))for(var d in o=this.IdentityAPI.getUser(i),e)if(n[d]!==e[d]){var g=!n[d];a=s.createUserIdentityChange(d,e[d],n[d],g,o),t._APIClient.sendEventToServer(a);}},this.createUserIdentityChange=function(e,s,r,i,n){var o;return o=t._ServerModel.createEventObject({messageType:Types.MessageType.UserIdentityChange,userIdentityChanges:{New:{IdentityType:e,Identity:s,CreatedThisBatch:i},Old:{IdentityType:e,Identity:r,CreatedThisBatch:!1}},userInMemory:n}),o},this.sendUserAttributeChangeEvent=function(e,r,i,n,o,a){if(t._APIClient.shouldEnableBatching()){var d=s.createUserAttributeChange(e,r,i,n,o,a);d&&t._APIClient.sendEventToServer(d);}},this.createUserAttributeChange=function(e,s,r,i,n,o){"undefined"==typeof r&&(r=null);var a;return s!==r&&(a=t._ServerModel.createEventObject({messageType:Types.MessageType.UserAttributeChange,userAttributeChanges:{UserAttributeName:e,New:s,Old:r,Deleted:n,IsNewAttribute:i}},o)),a};}
740
742
 
741
743
  function Consent(a){var b=this,c="data_sale_opt_out";// this function is called when consent is required to determine if a cookie sync should happen, or a forwarder should be initialized
742
744
  this.isEnabledForUserConsent=function(b,c){if(!b||!b.values||!b.values.length)return !0;if(!c)return !1;var d,e={},f=c.getConsentState();if(f){// the server hashes consent purposes in the following way:
package/dist/mparticle.js CHANGED
@@ -720,7 +720,7 @@ var mParticle = (function () {
720
720
  TriggerUploadType: TriggerUploadType
721
721
  };
722
722
 
723
- var version = "2.17.2";
723
+ var version = "2.17.4";
724
724
 
725
725
  var Constants = {
726
726
  sdkVersion: version,
@@ -2555,7 +2555,7 @@ var mParticle = (function () {
2555
2555
  };
2556
2556
  }
2557
2557
 
2558
- var slugify = {exports: {}};
2558
+ var slugify$1 = {exports: {}};
2559
2559
 
2560
2560
  (function (module, exports) {
2561
2561
  (function (name, root, factory) {
@@ -2619,9 +2619,9 @@ var mParticle = (function () {
2619
2619
 
2620
2620
  return replace
2621
2621
  }));
2622
- } (slugify));
2622
+ } (slugify$1));
2623
2623
 
2624
- var Slugify = slugify.exports;
2624
+ var slugify = slugify$1.exports;
2625
2625
 
2626
2626
  var inArray = function inArray(items, name) {
2627
2627
  var i = 0;
@@ -2689,7 +2689,32 @@ var mParticle = (function () {
2689
2689
  return s;
2690
2690
  };
2691
2691
 
2692
+ var isString = function isString(value) {
2693
+ return typeof value === 'string';
2694
+ };
2695
+
2696
+ var isNumber = function isNumber(value) {
2697
+ return typeof value === 'number';
2698
+ };
2699
+
2700
+ var isFunction = function isFunction(fn) {
2701
+ return typeof fn === 'function';
2702
+ }; // TODO: Refactor this to a regex
2703
+
2704
+
2705
+ var isDataPlanSlug = function isDataPlanSlug(str) {
2706
+ return isString(str) && str === slugify(str);
2707
+ };
2708
+
2709
+ var isStringOrNumber = function isStringOrNumber(value) {
2710
+ return isString(value) || isNumber(value);
2711
+ };
2712
+
2692
2713
  var Validators = {
2714
+ // From ./utils
2715
+ isNumber: isNumber,
2716
+ isFunction: isFunction,
2717
+ isStringOrNumber: isStringOrNumber,
2693
2718
  isValidAttributeValue: function isValidAttributeValue(value) {
2694
2719
  return value !== undefined && !isObject(value) && !Array.isArray(value);
2695
2720
  },
@@ -2697,15 +2722,6 @@ var mParticle = (function () {
2697
2722
  isValidKeyValue: function isValidKeyValue(key) {
2698
2723
  return Boolean(key && !isObject(key) && !Array.isArray(key) && !this.isFunction(key));
2699
2724
  },
2700
- isStringOrNumber: function isStringOrNumber(value) {
2701
- return typeof value === 'string' || typeof value === 'number';
2702
- },
2703
- isNumber: function isNumber(value) {
2704
- return typeof value === 'number';
2705
- },
2706
- isFunction: function isFunction(fn) {
2707
- return typeof fn === 'function';
2708
- },
2709
2725
  validateIdentities: function validateIdentities(identityApiData, method) {
2710
2726
  var validIdentityRequestKeys = {
2711
2727
  userIdentities: 1,
@@ -3220,10 +3236,6 @@ var mParticle = (function () {
3220
3236
  } else {
3221
3237
  return StorageNames$2.currentStorageProductsName;
3222
3238
  }
3223
- };
3224
-
3225
- this.isSlug = function (str) {
3226
- return str === Slugify(str);
3227
3239
  }; // Utility Functions
3228
3240
 
3229
3241
 
@@ -4137,6 +4149,7 @@ var mParticle = (function () {
4137
4149
  }
4138
4150
 
4139
4151
  function createSDKConfig(config) {
4152
+ // TODO: Refactor to create a default config object
4140
4153
  var sdkConfig = {};
4141
4154
 
4142
4155
  for (var prop in Constants.DefaultConfig) {
@@ -4146,14 +4159,14 @@ var mParticle = (function () {
4146
4159
  }
4147
4160
 
4148
4161
  if (config) {
4149
- for (prop in config) {
4162
+ for (var prop in config) {
4150
4163
  if (config.hasOwnProperty(prop)) {
4151
4164
  sdkConfig[prop] = config[prop];
4152
4165
  }
4153
4166
  }
4154
4167
  }
4155
4168
 
4156
- for (prop in Constants.DefaultUrls) {
4169
+ for (var prop in Constants.DefaultUrls) {
4157
4170
  sdkConfig[prop] = Constants.DefaultUrls[prop];
4158
4171
  }
4159
4172
 
@@ -4182,7 +4195,7 @@ var mParticle = (function () {
4182
4195
  eventQueue: [],
4183
4196
  currencyCode: null,
4184
4197
  globalTimer: null,
4185
- context: '',
4198
+ context: null,
4186
4199
  configurationLoaded: false,
4187
4200
  identityCallInFlight: false,
4188
4201
  SDKConfig: {},
@@ -4248,15 +4261,8 @@ var mParticle = (function () {
4248
4261
  this.SDKConfig.logLevel = config.logLevel;
4249
4262
  }
4250
4263
 
4251
- if (config.hasOwnProperty('useNativeSdk')) {
4252
- this.SDKConfig.useNativeSdk = config.useNativeSdk;
4253
- } else {
4254
- this.SDKConfig.useNativeSdk = false;
4255
- }
4256
-
4257
- if (config.hasOwnProperty('kits')) {
4258
- this.SDKConfig.kits = config.kits;
4259
- }
4264
+ this.SDKConfig.useNativeSdk = !!config.useNativeSdk;
4265
+ this.SDKConfig.kits = config.kits || {};
4260
4266
 
4261
4267
  if (config.hasOwnProperty('isIOS')) {
4262
4268
  this.SDKConfig.isIOS = config.isIOS;
@@ -4306,7 +4312,7 @@ var mParticle = (function () {
4306
4312
  if (mpInstance._Helpers.Validators.isFunction(callback)) {
4307
4313
  this.SDKConfig.identityCallback = config.identityCallback;
4308
4314
  } else {
4309
- mpInstance.Logger.warning('The optional callback must be a function. You tried entering a(n) ' + _typeof(callback), ' . Callback not set. Please set your callback again.');
4315
+ mpInstance.Logger.warning('The optional callback must be a function. You tried entering a(n) ' + _typeof(callback) + ' . Callback not set. Please set your callback again.');
4310
4316
  }
4311
4317
  }
4312
4318
 
@@ -4327,26 +4333,25 @@ var mParticle = (function () {
4327
4333
  PlanVersion: null,
4328
4334
  PlanId: null
4329
4335
  };
4336
+ var dataPlan = config.dataPlan;
4330
4337
 
4331
- if (config.dataPlan.hasOwnProperty('planId')) {
4332
- if (typeof config.dataPlan.planId === 'string') {
4333
- if (mpInstance._Helpers.isSlug(config.dataPlan.planId)) {
4334
- this.SDKConfig.dataPlan.PlanId = config.dataPlan.planId;
4335
- } else {
4336
- mpInstance.Logger.error('Your data plan id must be in a slug format');
4337
- }
4338
+ if (dataPlan.planId) {
4339
+ if (isDataPlanSlug(dataPlan.planId)) {
4340
+ this.SDKConfig.dataPlan.PlanId = dataPlan.planId;
4338
4341
  } else {
4339
- mpInstance.Logger.error('Your data plan id must be a string');
4342
+ mpInstance.Logger.error('Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)');
4340
4343
  }
4341
4344
  }
4342
4345
 
4343
- if (config.dataPlan.hasOwnProperty('planVersion')) {
4344
- if (typeof config.dataPlan.planVersion === 'number') {
4345
- this.SDKConfig.dataPlan.PlanVersion = config.dataPlan.planVersion;
4346
+ if (dataPlan.planVersion) {
4347
+ if (isNumber(dataPlan.planVersion)) {
4348
+ this.SDKConfig.dataPlan.PlanVersion = dataPlan.planVersion;
4346
4349
  } else {
4347
4350
  mpInstance.Logger.error('Your data plan version must be a number');
4348
4351
  }
4349
4352
  }
4353
+ } else {
4354
+ this.SDKConfig.dataPlan = {};
4350
4355
  }
4351
4356
 
4352
4357
  if (config.hasOwnProperty('forceHttps')) {
@@ -4356,9 +4361,7 @@ var mParticle = (function () {
4356
4361
  } // Some forwarders require custom flags on initialization, so allow them to be set using config object
4357
4362
 
4358
4363
 
4359
- if (config.hasOwnProperty('customFlags')) {
4360
- this.SDKConfig.customFlags = config.customFlags;
4361
- }
4364
+ this.SDKConfig.customFlags = config.customFlags || {};
4362
4365
 
4363
4366
  if (config.hasOwnProperty('minWebviewBridgeVersion')) {
4364
4367
  this.SDKConfig.minWebviewBridgeVersion = config.minWebviewBridgeVersion;
@@ -8138,7 +8141,7 @@ var mParticle = (function () {
8138
8141
  };
8139
8142
 
8140
8143
  this.createUserAttributeChange = function (key, newValue, previousUserAttributeValue, isNewAttribute, deleted, user) {
8141
- if (!previousUserAttributeValue) {
8144
+ if (typeof previousUserAttributeValue === 'undefined') {
8142
8145
  previousUserAttributeValue = null;
8143
8146
  }
8144
8147
 
@@ -8150,7 +8153,7 @@ var mParticle = (function () {
8150
8153
  userAttributeChanges: {
8151
8154
  UserAttributeName: key,
8152
8155
  New: newValue,
8153
- Old: previousUserAttributeValue || null,
8156
+ Old: previousUserAttributeValue,
8154
8157
  Deleted: deleted,
8155
8158
  IsNewAttribute: isNewAttribute
8156
8159
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.17.2",
3
+ "version": "2.17.4",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
package/src/helpers.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import Types from './types';
2
2
  import Constants from './constants';
3
- import Slugify from 'slugify';
4
3
  import * as utils from './utils';
5
4
  import Validators from './validators';
6
5
 
@@ -505,10 +504,6 @@ export default function Helpers(mpInstance) {
505
504
  }
506
505
  };
507
506
 
508
- this.isSlug = function(str) {
509
- return str === Slugify(str);
510
- };
511
-
512
507
  // Utility Functions
513
508
  this.converted = utils.converted;
514
509
  this.findKeyInObject = utils.findKeyInObject;
package/src/identity.js CHANGED
@@ -1819,7 +1819,7 @@ export default function Identity(mpInstance) {
1819
1819
  deleted,
1820
1820
  user
1821
1821
  ) {
1822
- if (!previousUserAttributeValue) {
1822
+ if (typeof previousUserAttributeValue === 'undefined') {
1823
1823
  previousUserAttributeValue = null;
1824
1824
  }
1825
1825
  var userAttributeChangeEvent;
@@ -1830,7 +1830,7 @@ export default function Identity(mpInstance) {
1830
1830
  userAttributeChanges: {
1831
1831
  UserAttributeName: key,
1832
1832
  New: newValue,
1833
- Old: previousUserAttributeValue || null,
1833
+ Old: previousUserAttributeValue,
1834
1834
  Deleted: deleted,
1835
1835
  IsNewAttribute: isNewAttribute,
1836
1836
  },
@@ -1,5 +1,9 @@
1
- import * as EventsApi from '@mparticle/event-models';
2
- import { DataPlanVersion, DataPlan } from '@mparticle/data-planning-models';
1
+ import { DataPlanVersion } from '@mparticle/data-planning-models';
2
+ import { Batch } from '@mparticle/event-models';
3
+ import { MPConfiguration, SDKEventCustomFlags } from '@mparticle/web-sdk';
4
+ import { SDKConfig } from './store';
5
+ import { Dictionary } from './utils';
6
+ import Validators from './validators';
3
7
 
4
8
  export interface SDKEvent {
5
9
  DeviceId: string;
@@ -116,59 +120,77 @@ export interface SDKProduct {
116
120
  }
117
121
 
118
122
  export interface MParticleWebSDK {
119
- addForwarder(mockForwarder: any);
123
+ addForwarder(mockForwarder: MPForwarder): void;
120
124
  Identity: SDKIdentityApi;
121
125
  Logger: SDKLoggerApi;
122
126
  _Store: SDKStoreApi;
123
127
  _Helpers: SDKHelpersApi;
124
- config: SDKConfig;
128
+ config: SDKInitConfig;
125
129
  _resetForTests(MPConfig: SDKConfig): void;
126
- init(apiKey: string, config: SDKConfig): void;
130
+ init(apiKey: string, config: SDKInitConfig, instanceName?: string): void;
127
131
  getInstance();
128
132
  ServerModel();
129
133
  upload();
130
134
  setPosition(lat: number | string, lng: number | string): void;
131
- logEvent(eventName: string, eventType?: number, attrs?: { [key: string]: string }): void;
135
+ logEvent(
136
+ eventName: string,
137
+ eventType?: number,
138
+ attrs?: { [key: string]: string },
139
+ customFlags?: SDKEventCustomFlags
140
+ ): void;
132
141
  logBaseEvent(event: any): void;
133
142
  eCommerce: any;
134
143
  logLevel: string;
135
144
  ProductActionType: SDKProductActionType;
136
145
  generateHash(value: string);
146
+ isIOS?: boolean;
137
147
  }
138
148
 
139
- export interface SDKConfig {
140
- isDevelopmentMode?: boolean;
141
- logger: {
142
- error?(msg);
143
- warning?(msg)
144
- verbose?(msg)
145
- };
146
- onCreateBatch(batch: EventsApi.Batch): EventsApi.Batch;
147
- dataPlan: DataPlanConfig;
148
- appVersion?: string;
149
- package?: string;
150
- flags?: { [key: string]: string | number };
151
- kitConfigs: any;
152
- appName?: string;
153
- logLevel?: string;
149
+ export type LogLevelType = 'none' | 'verbose' | 'warning' | 'error';
150
+
151
+ // TODO: Create true types for Kits and Kit Configs
152
+ export type KitConfigs = Dictionary;
153
+ export type Kit = Dictionary;
154
+ export type MPForwarder = Dictionary;
155
+
156
+ // TODO: This should eventually be moved into wherever init logic lives
157
+ // TODO: Replace/Merge this with MPConfiguration in @types/mparticle__web-sdk
158
+ // SDK Init Config represents the config that is passed into mParticle.init when
159
+ // the sdk is initialized.
160
+ // Currently, this extends MPConfiguration in @types/mparticle__web-sdk
161
+ // and the two will be merged in once the Store module is refactored
162
+ export interface SDKInitConfig
163
+ extends Omit<MPConfiguration, 'dataPlan' | 'logLevel'> {
164
+ dataPlan?: DataPlanConfig | KitBlockerDataPlan; // TODO: These should be eventually split into two different attributes
165
+ logLevel?: LogLevelType;
166
+
167
+ kitConfigs?: KitConfigs[];
168
+ kits?: Dictionary<Kit>;
169
+ dataPlanOptions?: KitBlockerOptions;
170
+ flags?: Dictionary;
171
+
172
+ aliasMaxWindow: number;
173
+ deviceId?: string;
174
+ forceHttps?: boolean;
175
+ aliasUrl?: string;
176
+ configUrl?: string;
177
+ identityUrl?: string;
178
+ integrationDelayTimeout: number;
179
+ isIOS?: boolean;
180
+ maxProducts: number;
181
+ requestConfig?: boolean;
154
182
  sessionTimeout?: number;
183
+ useNativeSdk?: boolean;
155
184
  useCookieStorage?: boolean;
156
- cookieDomain?: string;
157
- workspaceToken: string;
158
- requiredWebviewBridgeName: string;
159
- minWebviewBridgeVersion: number;
160
- isIOS?: boolean;
161
- identifyRequest: { [key: string]: {[key: string]: string} };
162
- identityCallback: (result) => void;
163
- requestConfig: boolean;
164
- dataPlanOptions: KitBlockerOptions // when the user provides their own data plan
165
- dataPlanResult?: DataPlanResult // when the data plan comes from the server via /config
185
+ v1SecureServiceUrl?: string;
186
+ v2SecureServiceUrl?: string;
187
+ v3SecureServiceUrl?: string;
166
188
  }
167
189
 
168
190
  export interface DataPlanConfig {
169
191
  planId?: string;
170
192
  planVersion?: number;
171
- document?: DataPlanResult // when the data plan comes from the server via /mparticle.js
193
+ document?: DataPlanResult; // when the data plan comes from the server via /mparticle.js
172
194
  }
173
195
 
174
196
  export interface SDKIdentityApi {
@@ -182,9 +204,11 @@ export interface SDKIdentityApi {
182
204
 
183
205
  export interface SDKHelpersApi {
184
206
  createServiceUrl(arg0: string, arg1: string): void;
185
- parseNumber(value: number)
207
+ parseNumber(value: number);
186
208
  generateUniqueId();
187
- isObject(item: any)
209
+ isObject(item: any);
210
+ returnConvertedBoolean(data: string | boolean | number): boolean;
211
+ Validators: typeof Validators;
188
212
  }
189
213
 
190
214
  export interface SDKLoggerApi {
@@ -205,7 +229,7 @@ export interface SDKConfigApi {
205
229
  v3SecureServiceUrl?: string;
206
230
  isDevelopmentMode: boolean;
207
231
  appVersion?: string;
208
- onCreateBatch(batch: EventsApi.Batch): EventsApi.Batch
232
+ onCreateBatch(batch: Batch): Batch;
209
233
  }
210
234
  export interface MParticleUser {
211
235
  getMPID(): string;
@@ -267,7 +291,7 @@ export interface KitBlockerOptions {
267
291
  }
268
292
 
269
293
  export interface KitBlockerDataPlan {
270
- document: DataPlanResult
294
+ document: DataPlanResult;
271
295
  }
272
296
 
273
297
  export interface DataPlanResult {
@@ -280,30 +304,30 @@ export interface DataPlanResult {
280
304
  id: boolean;
281
305
  };
282
306
  };
283
- error_message?: string
307
+ error_message?: string;
284
308
  }
285
309
 
286
310
  export enum SDKIdentityTypeEnum {
287
- other = "other",
288
- customerId = "customerid",
289
- facebook = "facebook",
290
- twitter = "twitter",
291
- google = "google",
292
- microsoft = "microsoft",
293
- yahoo = "yahoo",
294
- email = "email",
295
- alias = "alias",
296
- facebookCustomAudienceId = "facebookcustomaudienceid",
297
- otherId2 = "other2",
298
- otherId3 = "other3",
299
- otherId4 = "other4",
300
- otherId5 = "other5",
301
- otherId6 = "other6",
302
- otherId7 = "other7",
303
- otherId8 = "other8",
304
- otherId9 = "other9",
305
- otherId10 = "other10",
306
- mobileNumber = "mobile_number",
307
- phoneNumber2 = "phone_number_2",
308
- phoneNumber3 = "phone_number_3"
309
- }
311
+ other = 'other',
312
+ customerId = 'customerid',
313
+ facebook = 'facebook',
314
+ twitter = 'twitter',
315
+ google = 'google',
316
+ microsoft = 'microsoft',
317
+ yahoo = 'yahoo',
318
+ email = 'email',
319
+ alias = 'alias',
320
+ facebookCustomAudienceId = 'facebookcustomaudienceid',
321
+ otherId2 = 'other2',
322
+ otherId3 = 'other3',
323
+ otherId4 = 'other4',
324
+ otherId5 = 'other5',
325
+ otherId6 = 'other6',
326
+ otherId7 = 'other7',
327
+ otherId8 = 'other8',
328
+ otherId9 = 'other9',
329
+ otherId10 = 'other10',
330
+ mobileNumber = 'mobile_number',
331
+ phoneNumber2 = 'phone_number_2',
332
+ phoneNumber3 = 'phone_number_3',
333
+ }
@@ -1,30 +1,156 @@
1
+ import { Batch } from '@mparticle/event-models';
2
+ import { Context } from '@mparticle/event-models';
3
+ import {
4
+ DataPlanConfig,
5
+ MPID,
6
+ IdentifyRequest,
7
+ IdentityCallback,
8
+ SDKEventCustomFlags,
9
+ } from '@mparticle/web-sdk';
1
10
  import Constants from './constants';
11
+ import {
12
+ DataPlanResult,
13
+ Kit,
14
+ KitBlockerOptions,
15
+ KitConfigs,
16
+ LogLevelType,
17
+ MParticleWebSDK,
18
+ MPForwarder,
19
+ SDKConsentState,
20
+ SDKDataPlan,
21
+ SDKEvent,
22
+ SDKGeoLocation,
23
+ SDKInitConfig,
24
+ SDKProduct,
25
+ } from './sdkRuntimeModels';
26
+ import { isNumber, isDataPlanSlug, Dictionary } from './utils';
27
+
28
+ // This represents the runtime configuration of the SDK AFTER
29
+ // initialization has been complete and all settings and
30
+ // configurations have been stitched together.
31
+ export interface SDKConfig {
32
+ isDevelopmentMode?: boolean;
33
+ logger: {
34
+ error?(msg);
35
+ warning?(msg);
36
+ verbose?(msg);
37
+ };
38
+ onCreateBatch(batch: Batch): Batch;
39
+ customFlags?: SDKEventCustomFlags;
40
+ dataPlan: SDKDataPlan;
41
+ dataPlanOptions: KitBlockerOptions; // when the user provides their own data plan
42
+ dataPlanResult?: DataPlanResult; // when the data plan comes from the server via /config
43
+
44
+ appName?: string;
45
+ appVersion?: string;
46
+ package?: string;
47
+ flags?: { [key: string]: string | number | boolean };
48
+ kitConfigs: KitConfigs[];
49
+ kits: Dictionary<Kit>;
50
+ logLevel?: LogLevelType;
51
+ cookieDomain?: string;
52
+ maxCookieSize?: number | undefined;
53
+ minWebviewBridgeVersion: 1 | 2 | undefined;
54
+ identifyRequest: IdentifyRequest;
55
+ identityCallback: IdentityCallback;
56
+ integrationDelayTimeout: number;
57
+
58
+ aliasMaxWindow: number;
59
+ deviceId?: string;
60
+ forceHttps?: boolean;
61
+ aliasUrl?: string;
62
+ configUrl?: string;
63
+ identityUrl?: string;
64
+ isIOS?: boolean;
65
+ maxProducts: number;
66
+ requestConfig?: boolean;
67
+ sessionTimeout?: number;
68
+ useNativeSdk?: boolean;
69
+ useCookieStorage?: boolean;
70
+ v1SecureServiceUrl?: string;
71
+ v2SecureServiceUrl?: string;
72
+ v3SecureServiceUrl?: string;
73
+ }
74
+
75
+ function createSDKConfig(config: SDKInitConfig): SDKConfig {
76
+ // TODO: Refactor to create a default config object
77
+ const sdkConfig = {} as SDKConfig;
2
78
 
3
- function createSDKConfig(config) {
4
- var sdkConfig = {};
5
- for (var prop in Constants.DefaultConfig) {
79
+ for (const prop in Constants.DefaultConfig) {
6
80
  if (Constants.DefaultConfig.hasOwnProperty(prop)) {
7
81
  sdkConfig[prop] = Constants.DefaultConfig[prop];
8
82
  }
9
83
  }
10
84
 
11
85
  if (config) {
12
- for (prop in config) {
86
+ for (const prop in config) {
13
87
  if (config.hasOwnProperty(prop)) {
14
88
  sdkConfig[prop] = config[prop];
15
89
  }
16
90
  }
17
91
  }
18
92
 
19
- for (prop in Constants.DefaultUrls) {
93
+ for (const prop in Constants.DefaultUrls) {
20
94
  sdkConfig[prop] = Constants.DefaultUrls[prop];
21
95
  }
22
96
 
23
97
  return sdkConfig;
24
98
  }
25
99
 
26
- export default function Store(config, mpInstance) {
27
- var defaultStore = {
100
+ // TODO: Placeholder Types, MigrationData is temporary and will be removed in the future to reduce SDK size
101
+ export type PixelConfiguration = Dictionary;
102
+ export type MigrationData = Dictionary;
103
+ export type ServerSettings = Dictionary;
104
+
105
+ // Temporary Interface until Store can be refactored as a class
106
+ export interface IStore {
107
+ isEnabled: boolean;
108
+ sessionAttributes: Dictionary;
109
+ currentSessionMPIDs: MPID[];
110
+ consentState: SDKConsentState | null;
111
+ sessionId: string | null;
112
+ isFirstRun: boolean;
113
+ clientId: string;
114
+ deviceId: string;
115
+ devToken: string | null;
116
+ migrationData: MigrationData;
117
+ serverSettings: ServerSettings;
118
+ dateLastEventSent: number | null;
119
+ sessionStartDate: number | null;
120
+ currentPosition: SDKGeoLocation | null;
121
+ isTracking: boolean;
122
+ watchPositionId: number | null;
123
+ cartProducts: SDKProduct[];
124
+ eventQueue: SDKEvent[];
125
+ currencyCode: string | null;
126
+ globalTimer: number | null;
127
+ context: Context | null;
128
+ configurationLoaded: boolean;
129
+ identityCallInFlight: boolean;
130
+ SDKConfig: Partial<SDKConfig>;
131
+ migratingToIDSyncCookies: boolean; // TODO: Remove when we archive Web SDK v1
132
+ nonCurrentUserMPIDs: Record<MPID, Dictionary>;
133
+ identifyCalled: boolean;
134
+ isLoggedIn: boolean;
135
+ cookieSyncDates: Dictionary<number>;
136
+ integrationAttributes: Dictionary<Dictionary<string>>;
137
+ requireDelay: boolean;
138
+ isLocalStorageAvailable: boolean | null;
139
+ storageName: string | null;
140
+ prodStorageName: string | null;
141
+ activeForwarders: MPForwarder[];
142
+ kits: Dictionary<MPForwarder>;
143
+ configuredForwarders: MPForwarder[];
144
+ pixelConfigurations: PixelConfiguration[];
145
+ integrationDelayTimeoutStart: number; // UNIX Timestamp
146
+ }
147
+
148
+ export default function Store(
149
+ this: IStore,
150
+ config: SDKInitConfig,
151
+ mpInstance: MParticleWebSDK
152
+ ) {
153
+ const defaultStore: Partial<IStore> = {
28
154
  isEnabled: true,
29
155
  sessionAttributes: {},
30
156
  currentSessionMPIDs: [],
@@ -45,7 +171,7 @@ export default function Store(config, mpInstance) {
45
171
  eventQueue: [],
46
172
  currencyCode: null,
47
173
  globalTimer: null,
48
- context: '',
174
+ context: null,
49
175
  configurationLoaded: false,
50
176
  identityCallInFlight: false,
51
177
  SDKConfig: {},
@@ -113,14 +239,9 @@ export default function Store(config, mpInstance) {
113
239
  this.SDKConfig.logLevel = config.logLevel;
114
240
  }
115
241
 
116
- if (config.hasOwnProperty('useNativeSdk')) {
117
- this.SDKConfig.useNativeSdk = config.useNativeSdk;
118
- } else {
119
- this.SDKConfig.useNativeSdk = false;
120
- }
121
- if (config.hasOwnProperty('kits')) {
122
- this.SDKConfig.kits = config.kits;
123
- }
242
+ this.SDKConfig.useNativeSdk = !!config.useNativeSdk;
243
+
244
+ this.SDKConfig.kits = config.kits || {};
124
245
 
125
246
  if (config.hasOwnProperty('isIOS')) {
126
247
  this.SDKConfig.isIOS = config.isIOS;
@@ -177,8 +298,8 @@ export default function Store(config, mpInstance) {
177
298
  } else {
178
299
  mpInstance.Logger.warning(
179
300
  'The optional callback must be a function. You tried entering a(n) ' +
180
- typeof callback,
181
- ' . Callback not set. Please set your callback again.'
301
+ typeof callback +
302
+ ' . Callback not set. Please set your callback again.'
182
303
  );
183
304
  }
184
305
  }
@@ -200,32 +321,29 @@ export default function Store(config, mpInstance) {
200
321
  PlanVersion: null,
201
322
  PlanId: null,
202
323
  };
203
- if (config.dataPlan.hasOwnProperty('planId')) {
204
- if (typeof config.dataPlan.planId === 'string') {
205
- if (mpInstance._Helpers.isSlug(config.dataPlan.planId)) {
206
- this.SDKConfig.dataPlan.PlanId = config.dataPlan.planId;
207
- } else {
208
- mpInstance.Logger.error(
209
- 'Your data plan id must be in a slug format'
210
- );
211
- }
324
+
325
+ const dataPlan = config.dataPlan as DataPlanConfig;
326
+ if (dataPlan.planId) {
327
+ if (isDataPlanSlug(dataPlan.planId)) {
328
+ this.SDKConfig.dataPlan.PlanId = dataPlan.planId;
212
329
  } else {
213
330
  mpInstance.Logger.error(
214
- 'Your data plan id must be a string'
331
+ 'Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)'
215
332
  );
216
333
  }
217
334
  }
218
335
 
219
- if (config.dataPlan.hasOwnProperty('planVersion')) {
220
- if (typeof config.dataPlan.planVersion === 'number') {
221
- this.SDKConfig.dataPlan.PlanVersion =
222
- config.dataPlan.planVersion;
336
+ if (dataPlan.planVersion) {
337
+ if (isNumber(dataPlan.planVersion)) {
338
+ this.SDKConfig.dataPlan.PlanVersion = dataPlan.planVersion;
223
339
  } else {
224
340
  mpInstance.Logger.error(
225
341
  'Your data plan version must be a number'
226
342
  );
227
343
  }
228
344
  }
345
+ } else {
346
+ this.SDKConfig.dataPlan = {};
229
347
  }
230
348
 
231
349
  if (config.hasOwnProperty('forceHttps')) {
@@ -235,9 +353,7 @@ export default function Store(config, mpInstance) {
235
353
  }
236
354
 
237
355
  // Some forwarders require custom flags on initialization, so allow them to be set using config object
238
- if (config.hasOwnProperty('customFlags')) {
239
- this.SDKConfig.customFlags = config.customFlags;
240
- }
356
+ this.SDKConfig.customFlags = config.customFlags || {};
241
357
 
242
358
  if (config.hasOwnProperty('minWebviewBridgeVersion')) {
243
359
  this.SDKConfig.minWebviewBridgeVersion =
package/src/utils.ts CHANGED
@@ -1,5 +1,10 @@
1
+ import slugify from 'slugify';
2
+
1
3
  type valueof<T> = T[keyof T];
2
4
 
5
+ // Placeholder for Dictionary-like Types
6
+ export type Dictionary<V = any> = Record<string, V>;
7
+
3
8
  const inArray = (items: any[], name: string): boolean => {
4
9
  let i = 0;
5
10
 
@@ -70,6 +75,17 @@ const converted = (s: string): string => {
70
75
  return s;
71
76
  };
72
77
 
78
+ const isString = (value: any): boolean => typeof value === 'string';
79
+ const isNumber = (value: any): boolean => typeof value === 'number';
80
+ const isFunction = (fn: any): boolean => typeof fn === 'function';
81
+
82
+ // TODO: Refactor this to a regex
83
+ const isDataPlanSlug = (str: string): boolean =>
84
+ isString(str) && str === slugify(str);
85
+
86
+ const isStringOrNumber = (value: any): boolean =>
87
+ isString(value) || isNumber(value);
88
+
73
89
  export {
74
90
  valueof,
75
91
  converted,
@@ -79,4 +95,9 @@ export {
79
95
  isObject,
80
96
  parseNumber,
81
97
  returnConvertedBoolean,
98
+ isString,
99
+ isNumber,
100
+ isFunction,
101
+ isStringOrNumber,
102
+ isDataPlanSlug,
82
103
  };
package/src/validators.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import Types from './types';
2
- import { isObject } from './utils';
2
+ import { isFunction, isNumber, isObject, isStringOrNumber } from './utils';
3
3
  import Constants from './constants';
4
4
  import { IdentityApiData } from '@mparticle/web-sdk';
5
5
  import { valueof } from './utils';
@@ -12,6 +12,11 @@ type ValidationIdentitiesReturn = {
12
12
  };
13
13
 
14
14
  const Validators = {
15
+ // From ./utils
16
+ isNumber,
17
+ isFunction,
18
+ isStringOrNumber,
19
+
15
20
  isValidAttributeValue: function(value: any): boolean {
16
21
  return value !== undefined && !isObject(value) && !Array.isArray(value);
17
22
  },
@@ -26,18 +31,6 @@ const Validators = {
26
31
  );
27
32
  },
28
33
 
29
- isStringOrNumber: function(value: any): boolean {
30
- return typeof value === 'string' || typeof value === 'number';
31
- },
32
-
33
- isNumber: function(value: any): boolean {
34
- return typeof value === 'number';
35
- },
36
-
37
- isFunction: (fn: any): boolean => {
38
- return typeof fn === 'function';
39
- },
40
-
41
34
  validateIdentities: function(
42
35
  identityApiData: IdentityApiData,
43
36
  method?: IdentityAPIMethod