@mparticle/web-sdk 2.19.2 → 2.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mparticle.common.js +60 -19
- package/dist/mparticle.esm.js +60 -19
- package/dist/mparticle.js +249 -125
- package/package.json +3 -2
- package/src/batchUploader.ts +100 -63
- package/src/forwarders.js +181 -92
- package/src/helpers.js +5 -0
- package/src/identity.js +10 -6
- package/src/mockBatchCreator.ts +1 -0
- package/src/mp-instance.js +2 -0
- package/src/persistence.interfaces.ts +138 -0
- package/src/persistence.js +3 -0
- package/src/sdkRuntimeModels.ts +3 -1
- package/src/store.ts +9 -3
- package/src/vault.ts +21 -74
package/dist/mparticle.esm.js
CHANGED
|
@@ -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},Environment={Production:"production",Development:"development"};var Types = {MessageType:MessageType$1,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,TriggerUploadType:TriggerUploadType,Environment:Environment};
|
|
34
34
|
|
|
35
|
-
var version = "2.
|
|
35
|
+
var version = "2.20.0";
|
|
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"};
|
|
@@ -438,11 +438,28 @@ return null;case Types.MessageType.SessionEnd:return convertSessionEndEvent(a);c
|
|
|
438
438
|
//spanning_mpids: sdkEvent.SessionMpids
|
|
439
439
|
};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.sessionEnd,data:c}}function convertSessionStartEvent(a){var b=convertBaseEventData(a),c={};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.sessionStart,data:c}}function convertPageViewEvent(a){var b=convertBaseEventData(a),c={custom_flags:a.CustomFlags,screen_name:a.EventName};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.screenView,data:c}}function convertOptOutEvent(a){var b=convertBaseEventData(a),c={is_opted_out:a.OptOut};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.optOut,data:c}}function convertCustomEvent(a){var b=convertBaseEventData(a),c={custom_event_type:convertSdkEventType(a.EventCategory),custom_flags:a.CustomFlags,event_name:a.EventName};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.customEvent,data:c}}function convertSdkEventType(a){return a===Types.EventType.Other?dist.CustomEventDataCustomEventTypeEnum.other:a===Types.EventType.Location?dist.CustomEventDataCustomEventTypeEnum.location:a===Types.EventType.Navigation?dist.CustomEventDataCustomEventTypeEnum.navigation:a===Types.EventType.Search?dist.CustomEventDataCustomEventTypeEnum.search:a===Types.EventType.Social?dist.CustomEventDataCustomEventTypeEnum.social:a===Types.EventType.Transaction?dist.CustomEventDataCustomEventTypeEnum.transaction:a===Types.EventType.UserContent?dist.CustomEventDataCustomEventTypeEnum.userContent:a===Types.EventType.UserPreference?dist.CustomEventDataCustomEventTypeEnum.userPreference:a===Types.EventType.Media?dist.CustomEventDataCustomEventTypeEnum.media:a===Types.CommerceEventType.ProductAddToCart?dist.CommerceEventDataCustomEventTypeEnum.addToCart:a===Types.CommerceEventType.ProductAddToWishlist?dist.CommerceEventDataCustomEventTypeEnum.addToWishlist:a===Types.CommerceEventType.ProductCheckout?dist.CommerceEventDataCustomEventTypeEnum.checkout:a===Types.CommerceEventType.ProductCheckoutOption?dist.CommerceEventDataCustomEventTypeEnum.checkoutOption:a===Types.CommerceEventType.ProductClick?dist.CommerceEventDataCustomEventTypeEnum.click:a===Types.CommerceEventType.ProductImpression?dist.CommerceEventDataCustomEventTypeEnum.impression:a===Types.CommerceEventType.ProductPurchase?dist.CommerceEventDataCustomEventTypeEnum.purchase:a===Types.CommerceEventType.ProductRefund?dist.CommerceEventDataCustomEventTypeEnum.refund:a===Types.CommerceEventType.ProductRemoveFromCart?dist.CommerceEventDataCustomEventTypeEnum.removeFromCart:a===Types.CommerceEventType.ProductRemoveFromWishlist?dist.CommerceEventDataCustomEventTypeEnum.removeFromWishlist:a===Types.CommerceEventType.ProductViewDetail?dist.CommerceEventDataCustomEventTypeEnum.viewDetail:a===Types.CommerceEventType.PromotionClick?dist.CommerceEventDataCustomEventTypeEnum.promotionClick:a===Types.CommerceEventType.PromotionView?dist.CommerceEventDataCustomEventTypeEnum.promotionView:dist.CustomEventDataCustomEventTypeEnum.unknown}function convertBaseEventData(a){var b={timestamp_unixtime_ms:a.Timestamp,session_uuid:a.SessionId,session_start_unixtime_ms:a.SessionStartDate,custom_attributes:a.EventAttributes,location:convertSDKLocation(a.Location),source_message_id:a.SourceMessageId};return b}function convertSDKLocation(a){return a&&Object.keys(a).length?{latitude:a.lat,longitude:a.lng}:null}function convertUserAttributeChangeEvent(a){var b=convertBaseEventData(a),c={user_attribute_name:a.UserAttributeChanges.UserAttributeName,new:a.UserAttributeChanges.New,old:a.UserAttributeChanges.Old,deleted:a.UserAttributeChanges.Deleted,is_new_attribute:a.UserAttributeChanges.IsNewAttribute};return c=__assign(__assign({},c),b),{event_type:dist.EventTypeEnum.userAttributeChange,data:c}}function convertUserIdentityChangeEvent(a){var b=convertBaseEventData(a),c={new:{identity_type:convertUserIdentityTypeToServerIdentityType(a.UserIdentityChanges.New.IdentityType),identity:a.UserIdentityChanges.New.Identity||null,timestamp_unixtime_ms:a.Timestamp,created_this_batch:a.UserIdentityChanges.New.CreatedThisBatch},old:{identity_type:convertUserIdentityTypeToServerIdentityType(a.UserIdentityChanges.Old.IdentityType),identity:a.UserIdentityChanges.Old.Identity||null,timestamp_unixtime_ms:a.Timestamp,created_this_batch:a.UserIdentityChanges.Old.CreatedThisBatch}};return c=Object.assign(c,b),{event_type:dist.EventTypeEnum.userIdentityChange,data:c}}function convertUserIdentityTypeToServerIdentityType(a){return a===SDKIdentityTypeEnum.other?dist.IdentityTypeEnum.other:a===SDKIdentityTypeEnum.customerId?dist.IdentityTypeEnum.customerId:a===SDKIdentityTypeEnum.facebook?dist.IdentityTypeEnum.facebook:a===SDKIdentityTypeEnum.twitter?dist.IdentityTypeEnum.twitter:a===SDKIdentityTypeEnum.google?dist.IdentityTypeEnum.google:a===SDKIdentityTypeEnum.microsoft?dist.IdentityTypeEnum.microsoft:a===SDKIdentityTypeEnum.yahoo?dist.IdentityTypeEnum.yahoo:a===SDKIdentityTypeEnum.email?dist.IdentityTypeEnum.email:a===SDKIdentityTypeEnum.alias?dist.IdentityTypeEnum.alias:a===SDKIdentityTypeEnum.facebookCustomAudienceId?dist.IdentityTypeEnum.facebookCustomAudienceId:a===SDKIdentityTypeEnum.otherId2?dist.IdentityTypeEnum.otherId2:a===SDKIdentityTypeEnum.otherId3?dist.IdentityTypeEnum.otherId3:a===SDKIdentityTypeEnum.otherId4?dist.IdentityTypeEnum.otherId4:a===SDKIdentityTypeEnum.otherId5?dist.IdentityTypeEnum.otherId5:a===SDKIdentityTypeEnum.otherId6?dist.IdentityTypeEnum.otherId6:a===SDKIdentityTypeEnum.otherId7?dist.IdentityTypeEnum.otherId7:a===SDKIdentityTypeEnum.otherId8?dist.IdentityTypeEnum.otherId8:a===SDKIdentityTypeEnum.otherId9?dist.IdentityTypeEnum.otherId9:a===SDKIdentityTypeEnum.otherId10?dist.IdentityTypeEnum.otherId10:a===SDKIdentityTypeEnum.mobileNumber?dist.IdentityTypeEnum.mobileNumber:a===SDKIdentityTypeEnum.phoneNumber2?dist.IdentityTypeEnum.phoneNumber2:a===SDKIdentityTypeEnum.phoneNumber3?dist.IdentityTypeEnum.phoneNumber3:void 0}
|
|
440
440
|
|
|
441
|
-
|
|
441
|
+
/**
|
|
442
|
+
* BatchUploader contains all the logic to upload batches to mParticle.
|
|
443
|
+
* It queues events as they come in and at set intervals turns them into batches.
|
|
444
|
+
* It then attempts to upload them to mParticle.
|
|
445
|
+
*
|
|
446
|
+
* These uploads happen on an interval basis using window.fetch or XHR
|
|
447
|
+
* requests, depending on what is available in the browser.
|
|
448
|
+
*
|
|
449
|
+
* Uploads can also be triggered on browser visibility/focus changes via an
|
|
450
|
+
* event listener, which then uploads to mPartice via the browser's Beacon API.
|
|
451
|
+
*/var BatchUploader=/** @class */function(){/**
|
|
452
|
+
* Creates an instance of a BatchUploader
|
|
453
|
+
* @param {MParticleWebSDK} mpInstance - the mParticle SDK instance
|
|
454
|
+
* @param {number} uploadInterval - the desired upload interval in milliseconds
|
|
455
|
+
*/function a(b,c){this.mpInstance=b,this.uploadIntervalMillis=c,this.batchingEnabled=c>=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis<a.MINIMUM_INTERVAL_MILLIS&&(this.uploadIntervalMillis=a.MINIMUM_INTERVAL_MILLIS),this.eventsQueuedForProcessing=[],this.batchesQueuedForProcessing=[];var d=this.mpInstance._Store,e=d.SDKConfig,f=d.devToken,g=this.mpInstance._Helpers.createServiceUrl(e.v3SecureServiceUrl,f);this.uploadUrl="".concat(g,"/events"),this.uploader=window.fetch?new FetchUploader(this.uploadUrl):new XHRUploader(this.uploadUrl),this.triggerUploadInterval(!0,!1),this.addEventListeners();}// Adds listeners to be used trigger Navigator.sendBeacon if the browser
|
|
456
|
+
// loses focus for any reason, such as closing browser tab or minimizing window
|
|
457
|
+
return a.prototype.addEventListeners=function(){var a=this;// visibility change is a document property, not window
|
|
458
|
+
document.addEventListener("visibilitychange",function(){a.prepareAndUpload(!1,a.isBeaconAvailable());}),window.addEventListener("beforeunload",function(){a.prepareAndUpload(!1,a.isBeaconAvailable());}),window.addEventListener("pagehide",function(){a.prepareAndUpload(!1,a.isBeaconAvailable());});},a.prototype.isBeaconAvailable=function(){return !!navigator.sendBeacon},a.prototype.triggerUploadInterval=function(a,b){var c=this;void 0===a&&(a=!1),void 0===b&&(b=!1),setTimeout(function(){c.prepareAndUpload(a,b);},this.uploadIntervalMillis);},a.prototype.queueEvent=function(a){isEmpty(a)||(this.eventsQueuedForProcessing.push(a),this.mpInstance.Logger.verbose("Queuing event: ".concat(JSON.stringify(a))),this.mpInstance.Logger.verbose("Queued event count: ".concat(this.eventsQueuedForProcessing.length)),(!this.batchingEnabled||Types.TriggerUploadType[a.EventDataType])&&this.prepareAndUpload(!1,!1));},a.createNewBatches=function(a,b,c){if(!b||!a||!a.length)return null;//bucket by MPID, and then by session, ordered by timestamp
|
|
442
459
|
for(var d,e=[],f=new Map,g=0,h=a;g<h.length;g++){//on initial startup, there may be events logged without an mpid.
|
|
443
|
-
if(d=h[g],!d.MPID){var i=b.getMPID();d.MPID=i;}var j=f.get(d.MPID);j||(j=[]),j.push(d),f.set(d.MPID,j);}for(var k=0,l=Array.from(f.entries());k<l.length;k++){for(var m=l[k],i=m[0],n=m[1],o=new Map,p=0,q=n;p<q.length;p++){var d=q[p],j=o.get(d.SessionId);j||(j=[]),j.push(d),o.set(d.SessionId,j);}for(var r=0,s=Array.from(o.entries());r<s.length;r++){var t=s[r],u=convertEvents(i,t[1],c),v=c._Store.SDKConfig.onCreateBatch;v&&(u=v(u),u?u.modified=!0:c.Logger.warning("Skiping batch upload because no batch was returned from onCreateBatch callback")),u&&e.push(u);}}return e},a.prototype.prepareAndUpload=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j
|
|
444
|
-
return b.error("HTTP error status ".concat(
|
|
445
|
-
return b.error("HTTP error status ".concat(
|
|
460
|
+
if(d=h[g],!d.MPID){var i=b.getMPID();d.MPID=i;}var j=f.get(d.MPID);j||(j=[]),j.push(d),f.set(d.MPID,j);}for(var k=0,l=Array.from(f.entries());k<l.length;k++){for(var m=l[k],i=m[0],n=m[1],o=new Map,p=0,q=n;p<q.length;p++){var d=q[p],j=o.get(d.SessionId);j||(j=[]),j.push(d),o.set(d.SessionId,j);}for(var r=0,s=Array.from(o.entries());r<s.length;r++){var t=s[r],u=convertEvents(i,t[1],c),v=c._Store.SDKConfig.onCreateBatch;v&&(u=v(u),u?u.modified=!0:c.Logger.warning("Skiping batch upload because no batch was returned from onCreateBatch callback")),u&&e.push(u);}}return e},a.prototype.prepareAndUpload=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j;return __generator(this,function(k){switch(k.label){case 0:return d=this.mpInstance.Identity.getCurrentUser(),e=this.eventsQueuedForProcessing,this.eventsQueuedForProcessing=[],f=a.createNewBatches(e,d,this.mpInstance),isEmpty(f)||(i=this.batchesQueuedForProcessing).push.apply(i,f),g=this.batchesQueuedForProcessing,this.batchesQueuedForProcessing=[],[4/*yield*/,this.uploadBatches(this.mpInstance.Logger,g,c)];case 1:return h=k.sent(),isEmpty(h)||(j=this.batchesQueuedForProcessing).unshift.apply(j,h),b&&this.triggerUploadInterval(b,!1),[2/*return*/];}})})},a.prototype.uploadBatches=function(b,c,d){return __awaiter(this,void 0,void 0,function(){var e,f,g,h,j,k;return __generator(this,function(i){switch(i.label){case 0:if(e=c.filter(function(a){return !isEmpty(a.events)}),isEmpty(e))return [2/*return*/,null];b.verbose("Uploading batches: ".concat(JSON.stringify(e))),b.verbose("Batch count: ".concat(e.length)),f=0,i.label=1;case 1:return f<e.length?(g={method:"POST",headers:{Accept:a.CONTENT_TYPE,"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify(e[f])},!(d&&this.isBeaconAvailable()))?[3/*break*/,2]:(h=new Blob([g.body],{type:"text/plain;charset=UTF-8"}),navigator.sendBeacon(this.uploadUrl,h),[3/*break*/,5]):[3/*break*/,6];case 2:return i.trys.push([2,4,,5]),[4/*yield*/,this.uploader.upload(g)];case 3:if(j=i.sent(),200<=j.status&&300>j.status)b.verbose("Upload success for request ID: ".concat(e[f].source_request_id));else {if(500<=j.status||429===j.status)// Server error, add back current batches and try again later
|
|
461
|
+
return b.error("HTTP error status ".concat(j.status," received")),[2/*return*/,e.slice(f,e.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads.
|
|
462
|
+
return b.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),b.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,e.slice(f,e.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null];}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a}();var AsyncUploader=/** @class */function(){function a(a){this.url=a;}return a}(),FetchUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,fetch(this.url,a)];case 1:return b=c.sent(),[2/*return*/,b];}})})},b}(AsyncUploader),XHRUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,this.makeRequest(this.url,a.body)];case 1:return b=c.sent(),[2/*return*/,b];}})})},b.prototype.makeRequest=function(a,b){return __awaiter(this,void 0,void 0,function(){var c;return __generator(this,function(){return c=new XMLHttpRequest,[2/*return*/,new Promise(function(d,e){c.onreadystatechange=function(){4!==c.readyState||(200<=c.status&&300>c.status?d(c):e(c));},c.open("post",a),c.send(b);})]})})},b}(AsyncUploader);
|
|
446
463
|
|
|
447
464
|
var Messages$9=Constants.Messages;function APIClient(a,b){this.uploader=null;var c=this;this.queueEventForBatchUpload=function(b){if(!this.uploader){var c=a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis);this.uploader=new BatchUploader(a,c);}this.uploader.queueEvent(b),a._Persistence.update();},this.shouldEnableBatching=function(){// Returns a string of a number that must be parsed
|
|
448
465
|
// Invalid strings will be parsed to NaN which is falsey
|
|
@@ -482,7 +499,7 @@ return d// if the placeholder was passed, return
|
|
|
482
499
|
.replace(// replacing
|
|
483
500
|
/[018]/g,// zeroes, ones, and eights with
|
|
484
501
|
c.generateUniqueId// random hex digits
|
|
485
|
-
)},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.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
|
|
502
|
+
)},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.isFilteredUserAttribute=function(a,b){var d=c.generateHash(a);return b&&c.inArray(b,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.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
|
|
486
503
|
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.parseStringOrNumber=parseStringOrNumber,this.Validators=Validators;}
|
|
487
504
|
|
|
488
505
|
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
|
|
@@ -533,8 +550,8 @@ return a._Helpers.parseNumber(b)};}
|
|
|
533
550
|
|
|
534
551
|
function createSDKConfig(a){// TODO: Refactor to create a default config object
|
|
535
552
|
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}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels
|
|
536
|
-
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:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1}};for(var d in c)this[d]=c[d];// Set configuration to default settings
|
|
537
|
-
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);}}
|
|
553
|
+
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:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1}};for(var d in c)this[d]=c[d];// Set configuration to default settings
|
|
554
|
+
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.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var 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);}}
|
|
538
555
|
|
|
539
556
|
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);};}
|
|
540
557
|
|
|
@@ -600,7 +617,27 @@ this.migrate=function(){try{b();}catch(b){a._Persistence.expireCookies(StorageNa
|
|
|
600
617
|
function filteredMparticleUser(a,b,c,d){var e=this;return {getUserIdentities:function getUserIdentities(){var e={},f=c._Persistence.getUserIdentities(a);for(var g in f)if(f.hasOwnProperty(g)){var h=Types.IdentityType.getIdentityName(c._Helpers.parseNumber(g));d&&(!d||d.isIdentityBlocked(h))||(//if identity type is not blocked
|
|
601
618
|
e[h]=f[g]);}return e=c._Helpers.filterUserIdentitiesForForwarders(e,b.userIdentityFilters),{userIdentities:e}},getMPID:function getMPID(){return a},getUserAttributesLists:function getUserAttributesLists(a){var b,f={};for(var g in b=e.getAllUserAttributes(),b)b.hasOwnProperty(g)&&Array.isArray(b[g])&&(d&&(!d||d.isAttributeKeyBlocked(g))||(f[g]=b[g].slice()));return f=c._Helpers.filterUserAttributes(f,a.userAttributeFilters),f},getAllUserAttributes:function getAllUserAttributes(){var e={},f=c._Persistence.getAllUserAttributes(a);if(f)for(var g in f)f.hasOwnProperty(g)&&(d&&(!d||d.isAttributeKeyBlocked(g))||(Array.isArray(f[g])?e[g]=f[g].slice():e[g]=f[g]));return e=c._Helpers.filterUserAttributes(e,b.userAttributeFilters),e}}}
|
|
602
619
|
|
|
603
|
-
function Forwarders(a,b){var c=this
|
|
620
|
+
function Forwarders(a,b){var c=this,d={setUserAttribute:"setUserAttribute",removeUserAttribute:"removeUserAttribute"};// Processing forwarders is a 2 step process:
|
|
621
|
+
// 1. Configure the kit
|
|
622
|
+
// 2. Initialize the kit
|
|
623
|
+
// There are 2 types of kits:
|
|
624
|
+
// 1. UI-enabled kits
|
|
625
|
+
// 2. Sideloaded kits.
|
|
626
|
+
// These are kits that are enabled via the mParticle UI.
|
|
627
|
+
// A kit that is UI-enabled will have a kit configuration that returns from
|
|
628
|
+
// the server, or in rare cases, is passed in by the developer.
|
|
629
|
+
// The kit configuration will be compared with the kit constructors to determine
|
|
630
|
+
// if there is a match before being initialized.
|
|
631
|
+
// Only kits that are configured properly can be active and used for kit forwarding.
|
|
632
|
+
// Sideloaded kits are not configured in the UI and do not have kit configurations
|
|
633
|
+
// They are automatically added to active forwarders.
|
|
634
|
+
// TODO: Sideloading kits currently requires the use of a register method
|
|
635
|
+
// which requires an object on which to be registered.
|
|
636
|
+
// In the future, when all kits are moved to the config rather than
|
|
637
|
+
// there being a separate process for MP configured kits and
|
|
638
|
+
// sideloaded kits, this will need to be refactored.
|
|
639
|
+
// kits can be included via mParticle UI, or via sideloaded kit config API
|
|
640
|
+
this.initForwarders=function(b,d){var e=a.Identity.getCurrentUser();!a._Store.webviewBridgeEnabled&&a._Store.configuredForwarders&&(a._Store.configuredForwarders.sort(function(a,b){return a.settings.PriorityValue=a.settings.PriorityValue||0,b.settings.PriorityValue=b.settings.PriorityValue||0,-1*(a.settings.PriorityValue-b.settings.PriorityValue)}),a._Store.activeForwarders=a._Store.configuredForwarders.filter(function(f){if(!a._Consent.isEnabledForUserConsent(f.filteringConsentRuleValues,e))return !1;if(!c.isEnabledForUserAttributes(f.filteringUserAttributeValue,e))return !1;if(!c.isEnabledForUnknownUser(f.excludeAnonymousUser,e))return !1;var g=a._Helpers.filterUserIdentities(b,f.userIdentityFilters),h=a._Helpers.filterUserAttributes(e?e.getAllUserAttributes():{},f.userAttributeFilters);return f.initialized||(f.logger=a.Logger,f.init(f.settings,d,!1,null,h,g,a._Store.SDKConfig.appVersion,a._Store.SDKConfig.appName,a._Store.SDKConfig.customFlags,a._Store.clientId),f.initialized=!0),!0}));},this.isEnabledForUserAttributes=function(b,c){if(!b||!a._Helpers.isObject(b)||!Object.keys(b).length)return !0;var d,e,f;if(!c)return !1;f=c.getAllUserAttributes();var g=!1;try{if(f&&a._Helpers.isObject(f)&&Object.keys(f).length)for(var h in f)if(f.hasOwnProperty(h)&&(d=a._Helpers.generateHash(h).toString(),e=a._Helpers.generateHash(f[h]).toString(),d===b.userAttributeName&&e===b.userAttributeValue)){g=!0;break}return !b||b.includeOnMatch===g}catch(a){// in any error scenario, err on side of returning true and forwarding event
|
|
604
641
|
return !0}},this.isEnabledForUnknownUser=function(a,b){return !!(b&&b.isLoggedIn()||!a)},this.applyToForwarders=function(b,c){a._Store.activeForwarders.length&&a._Store.activeForwarders.forEach(function(d){var e=d[b];if(e)try{var f=d[b](c);f&&a.Logger.verbose(f);}catch(b){a.Logger.verbose(b);}});},this.sendEventToForwarders=function(b){var c,d,e,f=function(b,c){b.UserIdentities&&b.UserIdentities.length&&b.UserIdentities.forEach(function(d,e){a._Helpers.inArray(c,d.Type)&&(b.UserIdentities.splice(e,1),0<e&&e--);});},g=function(b,c){var d;if(c)for(var e in b.EventAttributes)b.EventAttributes.hasOwnProperty(e)&&(d=a._Helpers.generateHash(b.EventCategory+b.EventName+e),a._Helpers.inArray(c,d)&&delete b.EventAttributes[e]);},h=function(b,c){return !!(b&&b.length&&a._Helpers.inArray(b,c))},j=[Types.MessageType.PageEvent,Types.MessageType.PageView,Types.MessageType.Commerce];if(!a._Store.webviewBridgeEnabled&&a._Store.activeForwarders){d=a._Helpers.generateHash(b.EventCategory+b.EventName),e=a._Helpers.generateHash(b.EventCategory);for(var k=0;k<a._Store.activeForwarders.length;k++){// Check attribute forwarding rule. This rule allows users to only forward an event if a
|
|
605
642
|
// specific attribute exists and has a specific value. Alternatively, they can specify
|
|
606
643
|
// that an event not be forwarded if the specified attribute name and value exists.
|
|
@@ -610,8 +647,12 @@ if(-1<j.indexOf(b.EventDataType)&&a._Store.activeForwarders[k].filteringEventAtt
|
|
|
610
647
|
if(b.EventAttributes)for(var m in b.EventAttributes){var n;if(n=a._Helpers.generateHash(m).toString(),n===a._Store.activeForwarders[k].filteringEventAttributeValue.eventAttributeName&&(l={name:n,value:a._Helpers.generateHash(b.EventAttributes[m]).toString()}),l)break}var o=null!==l&&l.value===a._Store.activeForwarders[k].filteringEventAttributeValue.eventAttributeValue,p=!0===a._Store.activeForwarders[k].filteringEventAttributeValue.includeOnMatch?o:!o;if(!p)continue}// Clone the event object, as we could be sending different attributes to each forwarder
|
|
611
648
|
// Check event filtering rules
|
|
612
649
|
if(c={},c=a._Helpers.extend(!0,c,b),b.EventDataType===Types.MessageType.PageEvent&&(h(a._Store.activeForwarders[k].eventNameFilters,d)||h(a._Store.activeForwarders[k].eventTypeFilters,e)))continue;else if(b.EventDataType===Types.MessageType.Commerce&&h(a._Store.activeForwarders[k].eventTypeFilters,e))continue;else if(b.EventDataType===Types.MessageType.PageView&&h(a._Store.activeForwarders[k].screenNameFilters,d))continue;// Check attribute filtering rules
|
|
613
|
-
if(c.EventAttributes&&(b.EventDataType===Types.MessageType.PageEvent?g(c,a._Store.activeForwarders[k].attributeFilters):b.EventDataType===Types.MessageType.PageView&&g(c,a._Store.activeForwarders[k].screenAttributeFilters)),f(c,a._Store.activeForwarders[k].userIdentityFilters),c.UserAttributes=a._Helpers.filterUserAttributes(c.UserAttributes,a._Store.activeForwarders[k].userAttributeFilters),a._Store.activeForwarders[k].process){a.Logger.verbose("Sending message to forwarder: "+a._Store.activeForwarders[k].name);var q=a._Store.activeForwarders[k].process(c);q&&a.Logger.verbose(q);}}}},this.
|
|
614
|
-
for(var f in
|
|
650
|
+
if(c.EventAttributes&&(b.EventDataType===Types.MessageType.PageEvent?g(c,a._Store.activeForwarders[k].attributeFilters):b.EventDataType===Types.MessageType.PageView&&g(c,a._Store.activeForwarders[k].screenAttributeFilters)),f(c,a._Store.activeForwarders[k].userIdentityFilters),c.UserAttributes=a._Helpers.filterUserAttributes(c.UserAttributes,a._Store.activeForwarders[k].userAttributeFilters),a._Store.activeForwarders[k].process){a.Logger.verbose("Sending message to forwarder: "+a._Store.activeForwarders[k].name);var q=a._Store.activeForwarders[k].process(c);q&&a.Logger.verbose(q);}}}},this.handleForwarderUserAttributes=function(c,e,f){b&&b.isAttributeKeyBlocked(e)||!a._Store.activeForwarders.length||a._Store.activeForwarders.forEach(function(b){var g=b[c];if(g&&!a._Helpers.isFilteredUserAttribute(e,b.userAttributeFilters))try{var h;c===d.setUserAttribute?h=b.setUserAttribute(e,f):c===d.removeUserAttribute&&(h=b.removeUserAttribute(e)),h&&a.Logger.verbose(h);}catch(b){a.Logger.error(b);}});},this.setForwarderUserIdentities=function(b){a._Store.activeForwarders.forEach(function(c){var d=a._Helpers.filterUserIdentities(b,c.userIdentityFilters);c.setUserIdentity&&d.forEach(function(b){var d=c.setUserIdentity(b.Identity,b.Type);d&&a.Logger.verbose(d);});});},this.setForwarderOnUserIdentified=function(c){a._Store.activeForwarders.forEach(function(d){var e=filteredMparticleUser(c.getMPID(),d,a,b);if(d.onUserIdentified){var f=d.onUserIdentified(e);f&&a.Logger.verbose(f);}});},this.setForwarderOnIdentityComplete=function(c,d){var e;a._Store.activeForwarders.forEach(function(f){var g=filteredMparticleUser(c.getMPID(),f,a,b);"identify"===d?f.onIdentifyComplete&&(e=f.onIdentifyComplete(g),e&&a.Logger.verbose(e)):"login"===d?f.onLoginComplete&&(e=f.onLoginComplete(g),e&&a.Logger.verbose(e)):"logout"===d?f.onLogoutComplete&&(e=f.onLogoutComplete(g),e&&a.Logger.verbose(e)):"modify"==d&&f.onModifyComplete&&(e=f.onModifyComplete(g),e&&a.Logger.verbose(e));});},this.getForwarderStatsQueue=function(){return a._Persistence.forwardingStatsBatches.forwardingStatsEventQueue},this.setForwarderStatsQueue=function(b){a._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=b;},this.processForwarders=function(b,d){b?(this.processUIEnabledKits(b),this.processSideloadedKits(b),c.initForwarders(a._Store.SDKConfig.identifyRequest.userIdentities,d)):a.Logger.warning("No config was passed. Cannot process forwarders");},this.processUIEnabledKits=function(b){try{Array.isArray(b.kitConfigs)&&b.kitConfigs.length&&b.kitConfigs.forEach(function(a){c.configureUIEnabledKit(a);});}catch(b){a.Logger.error("MP Kits not configured propertly. Kits may not be initialized. "+b);}},this.configureUIEnabledKit=function(b){var c=null,d=b,e={};// If there are kits inside of mpInstance._Store.SDKConfig.kits, then mParticle is self hosted
|
|
651
|
+
for(var f in isEmpty(a._Store.SDKConfig.kits)?!isEmpty(a._preInit.forwarderConstructors)&&a._preInit.forwarderConstructors.forEach(function(a){e[a.name]=a;}):e=a._Store.SDKConfig.kits,e)if(f===d.name&&(d.isDebug===a._Store.SDKConfig.isDevelopmentMode||d.isSandbox===a._Store.SDKConfig.isDevelopmentMode)){c=this.returnConfiguredKit(e[f],d),a._Store.configuredForwarders.push(c);break}},this.processSideloadedKits=function(b){try{if(Array.isArray(b.sideloadedKits)){var d={kits:{}};// First register each kit's constructor onto sideloadedKits,
|
|
652
|
+
// which is typed { kits: Dictionary<constructor> }.
|
|
653
|
+
// The constructors are keyed by the name of the kit.
|
|
654
|
+
// Then configure each kit
|
|
655
|
+
for(var e in b.sideloadedKits.forEach(function(a){a.register(d);}),d.kits){var f=d.kits[e];c.configureSideloadedKit(f);}}}catch(b){a.Logger.error("Sideloaded Kits not configured propertly. Kits may not be initialized. "+b);}},this.configureSideloadedKit=function(b){a._Store.configuredForwarders.push(this.returnConfiguredKit(b));},this.returnConfiguredKit=function(a){var b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},c=new a.constructor;return c.id=b.moduleId,c.isSandbox=b.isDebug||b.isSandbox,c.hasSandbox="true"===b.hasDebugString,c.isVisible=b.isVisible||!0,c.settings=b.settings||{},c.eventNameFilters=b.eventNameFilters||[],c.eventTypeFilters=b.eventTypeFilters||[],c.attributeFilters=b.attributeFilters||[],c.screenNameFilters=b.screenNameFilters||[],c.screenAttributeFilters=b.screenAttributeFilters||[],c.userIdentityFilters=b.userIdentityFilters||[],c.userAttributeFilters=b.userAttributeFilters||[],c.filteringEventAttributeValue=b.filteringEventAttributeValue||{},c.filteringUserAttributeValue=b.filteringUserAttributeValue||{},c.eventSubscriptionId=b.eventSubscriptionId||null,c.filteringConsentRuleValues=b.filteringConsentRuleValues||{},c.excludeAnonymousUser=b.excludeAnonymousUser||!1,c},this.configurePixel=function(b){(b.isDebug===a._Store.SDKConfig.isDevelopmentMode||b.isProduction!==a._Store.SDKConfig.isDevelopmentMode)&&a._Store.pixelConfigurations.push(b);},this.processPixelConfigs=function(b){try{isEmpty(b.pixelConfigs)||b.pixelConfigs.forEach(function(a){c.configurePixel(a);});}catch(b){a.Logger.error("Cookie Sync configs not configured propertly. Cookie Sync may not be initialized. "+b);}};}
|
|
615
656
|
|
|
616
657
|
// TODO: This file is no longer the server model because the web SDK payload
|
|
617
658
|
var MessageType=Types.MessageType,ApplicationTransitionType=Types.ApplicationTransitionType;// TODO: Make this a pure function that returns a new object
|
|
@@ -718,7 +759,7 @@ combineUserIdentities:function combineUserIdentities(e,s){var r={},i=t._Helpers.
|
|
|
718
759
|
* @method setUserAttribute
|
|
719
760
|
* @param {String} key
|
|
720
761
|
* @param {String} value
|
|
721
|
-
*/setUserAttribute:function setUserAttribute(s,i){var n,o,a,d;if(t._SessionManager.resetSessionTimer(),t._Helpers.canLog()){if(!t._Helpers.Validators.isValidAttributeValue(i))return void t.Logger.error(Messages$2.ErrorMessages.BadAttribute);if(!t._Helpers.Validators.isValidKeyValue(s))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttribute,JSON.stringify({key:s,value:i}));else {n=t._Persistence.getPersistence(),o=this.getAllUserAttributes();var g=t._Helpers.findKeyInObject(o,s);g?(d=!1,a=o[g],delete o[g]):d=!0,o[s]=i,n&&n[e]&&(n[e].ua=o,t._Persistence.savePersistence(n,e)),r.sendUserAttributeChangeEvent(s,i,a,d,!1,this),t._Forwarders.initForwarders(r.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.
|
|
762
|
+
*/setUserAttribute:function setUserAttribute(s,i){var n,o,a,d;if(t._SessionManager.resetSessionTimer(),t._Helpers.canLog()){if(!t._Helpers.Validators.isValidAttributeValue(i))return void t.Logger.error(Messages$2.ErrorMessages.BadAttribute);if(!t._Helpers.Validators.isValidKeyValue(s))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttribute,JSON.stringify({key:s,value:i}));else {n=t._Persistence.getPersistence(),o=this.getAllUserAttributes();var g=t._Helpers.findKeyInObject(o,s);g?(d=!1,a=o[g],delete o[g]):d=!0,o[s]=i,n&&n[e]&&(n[e].ua=o,t._Persistence.savePersistence(n,e)),r.sendUserAttributeChangeEvent(s,i,a,d,!1,this),t._Forwarders.initForwarders(r.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.handleForwarderUserAttributes("setUserAttribute",s,i);}}},/**
|
|
722
763
|
* Set multiple user attributes
|
|
723
764
|
* @method setUserAttributes
|
|
724
765
|
* @param {Object} user attribute object with keys of the attribute type, and value of the attribute value
|
|
@@ -726,7 +767,7 @@ combineUserIdentities:function combineUserIdentities(e,s){var r={},i=t._Helpers.
|
|
|
726
767
|
* Removes a specific user attribute
|
|
727
768
|
* @method removeUserAttribute
|
|
728
769
|
* @param {String} key
|
|
729
|
-
*/removeUserAttribute:function removeUserAttribute(s){var i,n;if(t._SessionManager.resetSessionTimer(),!t._Helpers.Validators.isValidKeyValue(s))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveUserAttribute,JSON.stringify({key:s,value:null}));else {i=t._Persistence.getPersistence(),n=this.getAllUserAttributes();var o=t._Helpers.findKeyInObject(n,s);o&&(s=o);var a=n[s]?n[s].toString():null;delete n[s],i&&i[e]&&(i[e].ua=n,t._Persistence.savePersistence(i,e)),r.sendUserAttributeChangeEvent(s,null,a,!1,!0,this),t._Forwarders.initForwarders(r.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.
|
|
770
|
+
*/removeUserAttribute:function removeUserAttribute(s){var i,n;if(t._SessionManager.resetSessionTimer(),!t._Helpers.Validators.isValidKeyValue(s))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveUserAttribute,JSON.stringify({key:s,value:null}));else {i=t._Persistence.getPersistence(),n=this.getAllUserAttributes();var o=t._Helpers.findKeyInObject(n,s);o&&(s=o);var a=n[s]?n[s].toString():null;delete n[s],i&&i[e]&&(i[e].ua=n,t._Persistence.savePersistence(i,e)),r.sendUserAttributeChangeEvent(s,null,a,!1,!0,this),t._Forwarders.initForwarders(r.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.handleForwarderUserAttributes("removeUserAttribute",s,null);}},/**
|
|
730
771
|
* Sets a list of user attributes
|
|
731
772
|
* @method setUserAttributeList
|
|
732
773
|
* @param {String} key
|
|
@@ -734,10 +775,10 @@ combineUserIdentities:function combineUserIdentities(e,s){var r={},i=t._Helpers.
|
|
|
734
775
|
*/setUserAttributeList:function setUserAttributeList(s,n){var o,a,d,g,l;if(t._SessionManager.resetSessionTimer(),!t._Helpers.Validators.isValidKeyValue(s))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(!Array.isArray(n))return void t.Logger.error("The value you passed in to setUserAttributeList must be an array. You passed in a "+("undefined"==typeof value?"undefined":_typeof(value)));var u=n.slice();if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttributeList,JSON.stringify({key:s,value:u}));else {o=t._Persistence.getPersistence(),a=this.getAllUserAttributes();var p=t._Helpers.findKeyInObject(a,s);if(p?(g=!1,d=a[p],delete a[p]):g=!0,a[s]=u,o&&o[e]&&(o[e].ua=a,t._Persistence.savePersistence(o,e)),t._APIClient.shouldEnableBatching()){// If the new attributeList length is different previous, then there is a change event.
|
|
735
776
|
// Loop through new attributes list, see if they are all in the same index as previous user attributes list
|
|
736
777
|
// If there are any changes, break, and immediately send a userAttributeChangeEvent with full array as a value
|
|
737
|
-
if(!d||!Array.isArray(d))l=!0;else if(n.length!==d.length)l=!0;else for(var c=0;c<n.length;c++)if(d[c]!==n[c]){l=!0;break}l&&r.sendUserAttributeChangeEvent(s,n,d,g,!1,this);}t._Forwarders.initForwarders(r.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.
|
|
778
|
+
if(!d||!Array.isArray(d))l=!0;else if(n.length!==d.length)l=!0;else for(var c=0;c<n.length;c++)if(d[c]!==n[c]){l=!0;break}l&&r.sendUserAttributeChangeEvent(s,n,d,g,!1,this);}t._Forwarders.initForwarders(r.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.handleForwarderUserAttributes("setUserAttribute",s,u);}},/**
|
|
738
779
|
* Removes all user attributes
|
|
739
780
|
* @method removeAllUserAttributes
|
|
740
|
-
*/removeAllUserAttributes:function removeAllUserAttributes(){var e;if(t._SessionManager.resetSessionTimer(),t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveAllUserAttributes);else if(e=this.getAllUserAttributes(),t._Forwarders.initForwarders(r.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),e)for(var s in e)e.hasOwnProperty(s)&&t._Forwarders.
|
|
781
|
+
*/removeAllUserAttributes:function removeAllUserAttributes(){var e;if(t._SessionManager.resetSessionTimer(),t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveAllUserAttributes);else if(e=this.getAllUserAttributes(),t._Forwarders.initForwarders(r.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),e)for(var s in e)e.hasOwnProperty(s)&&t._Forwarders.handleForwarderUserAttributes("removeUserAttribute",s,null),this.removeUserAttribute(s);},/**
|
|
741
782
|
* Returns all user attribute keys that have values that are arrays
|
|
742
783
|
* @method getUserAttributesLists
|
|
743
784
|
* @return {Object} an object of only keys with array values. Example: { attr1: [1, 2, 3], attr2: ['a', 'b', 'c'] }
|
|
@@ -778,8 +819,8 @@ if(!d||!Array.isArray(d))l=!0;else if(n.length!==d.length)l=!0;else for(var c=0;
|
|
|
778
819
|
* @method getCartProducts
|
|
779
820
|
* @return {Array} array of cart products
|
|
780
821
|
* @deprecated
|
|
781
|
-
*/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={},
|
|
782
|
-
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
|
|
822
|
+
*/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={},I=p?p.getUserIdentities().userIdentities:{},y=t._Helpers.extend({},I);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(I,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
|
|
823
|
+
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 P=t._Store.migrationData.userAttributes||{};t._Persistence.saveUserAttributesToPersistence(l.mpid,P);}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 S=t._Persistence.getPersistence();d&&(t._Persistence.storeDataInMemory(S,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?y: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};}
|
|
783
824
|
|
|
784
825
|
var CCPAPurpose="data_sale_opt_out";function Consent(a){var b=this;// this function is called when consent is required to
|
|
785
826
|
// determine if a cookie sync should happen, or a
|
|
@@ -1197,7 +1238,7 @@ var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(fu
|
|
|
1197
1238
|
function completeSDKInitialization(a,b,c){var d=createKitBlocker(b,c);if(c._APIClient=new APIClient(c,d),c._Forwarders=new Forwarders(c,d),b.flags){if(b.flags.hasOwnProperty(Constants.FeatureFlags.EventsV3)){// TODO: Remove this after 8/12/2022
|
|
1198
1239
|
if("100"!==b.flags[Constants.FeatureFlags.EventsV3]){c.Logger.warning("mParticle will be enabling Event Batching for all customers on July 12, 2022. For more details, please see our docs: https://docs.mparticle.com/developers/sdk/web/getting-started/");}c._Store.SDKConfig.flags[Constants.FeatureFlags.EventsV3]=b.flags[Constants.FeatureFlags.EventsV3];}b.flags.hasOwnProperty(Constants.FeatureFlags.EventBatchingIntervalMillis)&&(c._Store.SDKConfig.flags[Constants.FeatureFlags.EventBatchingIntervalMillis]=b.flags[Constants.FeatureFlags.EventBatchingIntervalMillis]);}if(c._Store.storageName=c._Helpers.createMainStorageName(b.workspaceToken),c._Store.prodStorageName=c._Helpers.createProductStorageName(b.workspaceToken),b.hasOwnProperty("workspaceToken")?c._Store.SDKConfig.workspaceToken=b.workspaceToken:c.Logger.warning("You should have a workspaceToken on your config object for security purposes."),b.hasOwnProperty("requiredWebviewBridgeName")?c._Store.SDKConfig.requiredWebviewBridgeName=b.requiredWebviewBridgeName:b.hasOwnProperty("workspaceToken")&&(c._Store.SDKConfig.requiredWebviewBridgeName=b.workspaceToken),c._Store.webviewBridgeEnabled=c._NativeSdkHelpers.isWebviewEnabled(c._Store.SDKConfig.requiredWebviewBridgeName,c._Store.SDKConfig.minWebviewBridgeVersion),c._Store.configurationLoaded=!0,c._Store.webviewBridgeEnabled||(c._Migrations.migrate(),c._Persistence.initializeStorage()),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:"$src_env",value:"webview"})),a&&c._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:"$src_key",value:a}));else {var e;// If no initialIdentityRequest is passed in, we set the user identities to what is currently in cookies for the identify request
|
|
1199
1240
|
if(c._Helpers.isObject(c._Store.SDKConfig.identifyRequest)&&c._Helpers.isObject(c._Store.SDKConfig.identifyRequest.userIdentities)&&0===Object.keys(c._Store.SDKConfig.identifyRequest.userIdentities).length||!c._Store.SDKConfig.identifyRequest){var f={};if(e=c.Identity.getCurrentUser(),e){var g=e.getUserIdentities().userIdentities||{};for(var h in g)g.hasOwnProperty(h)&&(f[h]=g[h]);}c._Store.SDKConfig.identifyRequest={userIdentities:f};}// If migrating from pre-IDSync to IDSync, a sessionID will exist and an identify request will not have been fired, so we need this check
|
|
1200
|
-
c._Store.migratingToIDSyncCookies&&(c.Identity.identify(c._Store.SDKConfig.identifyRequest,c._Store.SDKConfig.identityCallback),c._Store.migratingToIDSyncCookies=!1),e=c.Identity.getCurrentUser(),c._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer(),c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._SessionManager.initialize(),c._Events.logAST(),!c._Store.identifyCalled&&c._Store.SDKConfig.identityCallback&&e&&e.getMPID()&&c._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return c._Identity.mParticleUser(e.getMPID())},getPreviousUser:function getPreviousUser(){var a=c.Identity.getUsers(),b=a.shift();return b&&e&&b.getMPID()===e.getMPID()&&(b=a.shift()),b||null},body:{mpid:e.getMPID(),is_logged_in:c._Store.isLoggedIn,matched_identities:e.getUserIdentities().userIdentities,context:null,is_ephemeral:!1}});}c._Store.isInitialized=!0,c._preInit.readyQueue&&c._preInit.readyQueue.length&&(c._preInit.readyQueue.forEach(function(a){c._Helpers.Validators.isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a,c);}),c._preInit.readyQueue=[]),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK:
|
|
1241
|
+
c._Store.migratingToIDSyncCookies&&(c.Identity.identify(c._Store.SDKConfig.identifyRequest,c._Store.SDKConfig.identityCallback),c._Store.migratingToIDSyncCookies=!1),e=c.Identity.getCurrentUser(),c._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer(),c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),!c._Store.identifyCalled&&c._Store.SDKConfig.identityCallback&&e&&e.getMPID()&&c._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return c._Identity.mParticleUser(e.getMPID())},getPreviousUser:function getPreviousUser(){var a=c.Identity.getUsers(),b=a.shift();return b&&e&&b.getMPID()===e.getMPID()&&(b=a.shift()),b||null},body:{mpid:e.getMPID(),is_logged_in:c._Store.isLoggedIn,matched_identities:e.getUserIdentities().userIdentities,context:null,is_ephemeral:!1}});}c._Store.isInitialized=!0,c._preInit.readyQueue&&c._preInit.readyQueue.length&&(c._preInit.readyQueue.forEach(function(a){c._Helpers.Validators.isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a,c);}),c._preInit.readyQueue=[]),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK:
|
|
1201
1242
|
1. Manually via config.dataPlanOptions (this takes priority)
|
|
1202
1243
|
If not passed in manually, we user the server provided via either
|
|
1203
1244
|
2. Snippet via /mparticle.js endpoint (config.dataPlan.document)
|
|
@@ -1208,7 +1249,7 @@ if(mParticle[c[0]])mParticle[d].apply(this,c);else {var e=d.split(".");try{for(v
|
|
|
1208
1249
|
|
|
1209
1250
|
// This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise!
|
|
1210
1251
|
var mockFunction=function(){return null},_BatchValidator=/** @class */function(){function a(){}return a.prototype.getMPInstance=function(){return {// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method
|
|
1211
|
-
_Helpers:{sanitizeAttributes:window.mParticle.getInstance()._Helpers.sanitizeAttributes,generateHash:function generateHash(){return "mockHash"},generateUniqueId:function generateUniqueId(){return "mockId"},extend:window.mParticle.getInstance()._Helpers.extend,createServiceUrl:mockFunction,parseNumber:mockFunction,isObject:mockFunction,returnConvertedBoolean:mockFunction,Validators:null},_resetForTests:mockFunction,_APIClient:null,_Consent:null,_Forwarders:null,_NativeSdkHelpers:null,_Persistence:null,_preInit:null,Consent:null,_ServerModel:null,_SessionManager:null,_Store:{sessionId:"mockSessionId",devToken:"test_dev_token",isFirstRun:!0,isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,clientId:null,deviceId: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,migratingToIDSyncCookies:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,integrationDelayTimeoutStart:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},SDKConfig:{isDevelopmentMode:!1,onCreateBatch:mockFunction}},config:null,eCommerce:null,Identity:{getCurrentUser:mockFunction,IdentityAPI:{},identify:mockFunction,login:mockFunction,logout:mockFunction,modify:mockFunction},Logger:{verbose:mockFunction,error:mockFunction,warning:mockFunction},ProductActionType:null,ServerModel:null,addForwarder:mockFunction,generateHash:mockFunction,getAppVersion:mockFunction,getAppName:mockFunction,getInstance:mockFunction,init:mockFunction,logBaseEvent:mockFunction,logEvent:mockFunction,logLevel:"none",setPosition:mockFunction,upload:mockFunction}},a.prototype.returnBatch=function(a){var b=this.getMPInstance(),c=new ServerModel(b).createEventObject(a),d=convertEvents("0",[c],b);return d},a}();
|
|
1252
|
+
_Helpers:{sanitizeAttributes:window.mParticle.getInstance()._Helpers.sanitizeAttributes,generateHash:function generateHash(){return "mockHash"},generateUniqueId:function generateUniqueId(){return "mockId"},extend:window.mParticle.getInstance()._Helpers.extend,createServiceUrl:mockFunction,parseNumber:mockFunction,isObject:mockFunction,returnConvertedBoolean:mockFunction,Validators:null},_resetForTests:mockFunction,_APIClient:null,_Consent:null,_Forwarders:null,_NativeSdkHelpers:null,_Persistence:null,_preInit:null,Consent:null,_ServerModel:null,_SessionManager:null,_Store:{sessionId:"mockSessionId",sideloadedKits:[],devToken:"test_dev_token",isFirstRun:!0,isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,clientId:null,deviceId: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,migratingToIDSyncCookies:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,integrationDelayTimeoutStart:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},SDKConfig:{isDevelopmentMode:!1,onCreateBatch:mockFunction}},config:null,eCommerce:null,Identity:{getCurrentUser:mockFunction,IdentityAPI:{},identify:mockFunction,login:mockFunction,logout:mockFunction,modify:mockFunction},Logger:{verbose:mockFunction,error:mockFunction,warning:mockFunction},ProductActionType:null,ServerModel:null,addForwarder:mockFunction,generateHash:mockFunction,getAppVersion:mockFunction,getAppName:mockFunction,getInstance:mockFunction,init:mockFunction,logBaseEvent:mockFunction,logEvent:mockFunction,logLevel:"none",setPosition:mockFunction,upload:mockFunction}},a.prototype.returnBatch=function(a){var b=this.getMPInstance(),c=new ServerModel(b).createEventObject(a),d=convertEvents("0",[c],b);return d},a}();
|
|
1212
1253
|
|
|
1213
1254
|
Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.prototype.map||(Array.prototype.map=Polyfill.map),Array.prototype.filter||(Array.prototype.filter=Polyfill.filter),Array.isArray||(Array.prototype.isArray=Polyfill.isArray);function mParticle$1(){var a=this;// Only leaving this here in case any clients are trying to access mParticle.Store, to prevent from throwing
|
|
1214
1255
|
/**
|