@mparticle/web-sdk 2.19.0 → 2.19.2
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 +53 -37
- package/dist/mparticle.esm.js +53 -37
- package/dist/mparticle.js +181 -162
- package/package.json +1 -1
- package/src/apiClient.ts +1 -1
- package/src/batchUploader.ts +109 -146
- package/src/{consent.js → consent.ts} +228 -72
- package/src/cookieSyncManager.js +40 -0
- package/src/mockBatchCreator.ts +3 -0
- package/src/sdkRuntimeModels.ts +4 -3
- package/src/sdkToEventsApiConverter.ts +1 -1
- package/src/serverModel.ts +34 -32
- package/src/store.ts +5 -4
- package/src/consent.interfaces.ts +0 -89
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.19.
|
|
35
|
+
var version = "2.19.2";
|
|
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,34 +438,17 @@ 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
|
-
|
|
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
|
|
441
|
+
var BatchUploader=/** @class */function(){function a(b,c){var d=this;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.pendingEvents=[],this.pendingUploads=[];var e=this.mpInstance._Store,f=e.SDKConfig,g=e.devToken,h=this.mpInstance._Helpers.createServiceUrl(f.v3SecureServiceUrl,g);this.uploadUrl="".concat(h,"/events"),setTimeout(function(){d.prepareAndUpload(!0,!1);},this.uploadIntervalMillis),this.addEventListeners();}return a.prototype.addEventListeners=function(){var a=this;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.queueEvent=function(a){isEmpty(a)||(this.pendingEvents.push(a),this.mpInstance.Logger.verbose("Queuing event: ".concat(JSON.stringify(a))),this.mpInstance.Logger.verbose("Queued event count: ".concat(this.pendingEvents.length)),(!this.batchingEnabled||Types.TriggerUploadType[a.EventDataType])&&this.prepareAndUpload(!1,!1));},a.createNewUploads=function(a,b,c){if(!b||!a||!a.length)return null;//bucket by MPID, and then by session, ordered by timestamp
|
|
459
442
|
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.
|
|
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,k=this;return __generator(this,function(){return d=this.mpInstance.Identity.getCurrentUser(),e=this.
|
|
461
|
-
|
|
462
|
-
return
|
|
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,k=this;return __generator(this,function(l){switch(l.label){case 0:return d=this.mpInstance.Identity.getCurrentUser(),e=this.pendingEvents,this.pendingEvents=[],f=a.createNewUploads(e,d,this.mpInstance),f&&f.length&&(i=this.pendingUploads).push.apply(i,f),g=this.pendingUploads,this.pendingUploads=[],[4/*yield*/,this.upload(this.mpInstance.Logger,g,c)];case 1:return h=l.sent(),h&&h.length&&(j=this.pendingUploads).unshift.apply(j,h),b&&setTimeout(function(){k.prepareAndUpload(!0,!1);},this.uploadIntervalMillis),[2/*return*/];}})})},a.prototype.upload=function(b,c,d){return __awaiter(this,void 0,void 0,function(){var e,f,g,h,j,k,l;return __generator(this,function(i){switch(i.label){case 0:if(f=c.filter(function(a){return !isEmpty(a.events)}),isEmpty(f))return [2/*return*/,null];b.verbose("Uploading batches: ".concat(JSON.stringify(f))),b.verbose("Batch count: ".concat(f.length)),g=0,i.label=1;case 1:return g<f.length?(h={method:"POST",headers:{Accept:a.CONTENT_TYPE,"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify(f[g])},!(d&&this.isBeaconAvailable()))?[3/*break*/,2]:(j=new Blob([h.body],{type:"text/plain;charset=UTF-8"}),navigator.sendBeacon(this.uploadUrl,j),[3/*break*/,6]):[3/*break*/,7];case 2:e||(window.fetch?e=new FetchUploader(this.uploadUrl,b):e=new XHRUploader(this.uploadUrl,b)),i.label=3;case 3:return i.trys.push([3,5,,6]),[4/*yield*/,e.upload(h,f,g)];case 4:if(k=i.sent(),200<=k.status&&300>k.status)b.verbose("Upload success for request ID: ".concat(f[g].source_request_id));else {if(500<=k.status||429===k.status)//server error, add back current events and try again later
|
|
444
|
+
return b.error("HTTP error status ".concat(k.status," received")),[2/*return*/,f.slice(g,f.length)];if(401<=k.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads.
|
|
445
|
+
return b.error("HTTP error status ".concat(k.status," while uploading - please verify your API key.")),[2/*return*/,null]}return [3/*break*/,6];case 5:return l=i.sent(),b.error("Error sending event to mParticle servers. ".concat(l)),[2/*return*/,f.slice(g,f.length)];case 6:return g++,[3/*break*/,1];case 7: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,b){this.url=a,this.logger=b;}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,this.logger,a.body)];case 1:return b=c.sent(),[2/*return*/,b];}})})},b.prototype.makeRequest=function(a,b,c){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(){return b=new XMLHttpRequest,[2/*return*/,new Promise(function(d,e){b.onreadystatechange=function(){4!==b.readyState||(200<=b.status&&300>b.status?d(b):e(b));},b.open("post",a),b.send(c);})]})})},b}(AsyncUploader);
|
|
463
446
|
|
|
464
447
|
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
|
|
465
448
|
// Invalid strings will be parsed to NaN which is falsey
|
|
466
449
|
var b=parseInt(a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventsV3),10);if(!b)return !1;var c=a._Helpers.getRampNumber(a._Store.deviceId);return b>=c},this.processQueuedEvents=function(){var b,d=a.Identity.getCurrentUser();if(d&&(b=d.getMPID()),a._Store.eventQueue.length&&b){var e=a._Store.eventQueue;a._Store.eventQueue=[],this.appendUserInfoToEvents(d,e),e.forEach(function(a){c.sendEventToServer(a);});}},this.appendUserInfoToEvents=function(b,c){c.forEach(function(c){c.MPID||a._ServerModel.appendUserInfo(b,c);});},this.sendEventToServer=function(c,d){var e=a._Helpers.extend({shouldUploadEvent:!0},d);if(a._Store.webviewBridgeEnabled)return void a._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.LogEvent,JSON.stringify(c));var f,g=a.Identity.getCurrentUser();// We queue events if there is no MPID (MPID is null, or === 0), or there are integrations that that require this to stall because integration attributes
|
|
467
450
|
// need to be set, or if we are still fetching the config (self hosted only), and so require delaying events
|
|
468
|
-
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.
|
|
451
|
+
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.convertEventToV2DTO(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));};}
|
|
469
452
|
|
|
470
453
|
var Validators={// From ./utils
|
|
471
454
|
// Utility Functions for backwards compatability
|
|
@@ -509,10 +492,37 @@ return !!(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHan
|
|
|
509
492
|
},this.isWebviewEnabled=function(c,d){return a._Store.bridgeV2Available=b.isBridgeV2Available(c),a._Store.bridgeV1Available=b.isBridgeV1Available(),2===d?a._Store.bridgeV2Available:!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName!==iosBridgeNameBase+"_"+c+"_v2")&&!!(2>d)&&(a._Store.bridgeV2Available||a._Store.bridgeV1Available);// iOS BridgeV1 can be available via mParticle.isIOS, but return false if uiwebviewBridgeName doesn't match requiredWebviewBridgeName
|
|
510
493
|
},this.isBridgeV1Available=function(){return !!(a._Store.SDKConfig.useNativeSdk||window.mParticleAndroid||a._Store.SDKConfig.isIOS)},this.sendToNative=function(c,d){return a._Store.bridgeV2Available&&2===a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV2Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV1Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV1(c,d):void 0},this.sendViaBridgeV1=function(c,d){window.mParticleAndroid&&window.mParticleAndroid.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),window.mParticleAndroid[c](d)):a._Store.SDKConfig.isIOS&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d));},this.sendViaIframeToIOS=function(a,b){var c=document.createElement("IFRAME");c.setAttribute("src","mp-sdk://"+a+"/"+encodeURIComponent(b)),document.documentElement.appendChild(c),c.parentNode.removeChild(c);},this.sendViaBridgeV2=function(c,d,e){if(e){var f,g,h=window[androidBridgeNameBase+"_"+e+"_v2"],i=iosBridgeNameBase+"_"+e+"_v2";return window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers[i]&&(f=window.webkit.messageHandlers[i]),a.uiwebviewBridgeName===i&&(g=a[i]),h&&h.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),void h[c](d)):void(f?(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),f.postMessage(JSON.stringify({path:c,value:d?JSON.parse(d):null}))):g&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d)))}};}
|
|
511
494
|
|
|
512
|
-
var Messages$7=Constants.Messages;function cookieSyncManager(a){var b=this
|
|
495
|
+
var Messages$7=Constants.Messages;function cookieSyncManager(a){var b=this;// Public
|
|
496
|
+
// Private
|
|
497
|
+
// Private
|
|
498
|
+
// TODO: Rename function to replaceAmpWithAmpersand
|
|
499
|
+
// Private
|
|
500
|
+
this.attemptCookieSync=function(c,d,e){// TODO: These should move inside the for loop
|
|
501
|
+
var f,g,h,i,j,k;// TODO: Make this exit quicker instead of nested
|
|
502
|
+
d&&!a._Store.webviewBridgeEnabled&&a._Store.pixelConfigurations.forEach(function(l){k=!1,l.filteringConsentRuleValues&&l.filteringConsentRuleValues.values&&l.filteringConsentRuleValues.values.length&&(k=!0),f={// Kit Module ID
|
|
503
|
+
moduleId:l.moduleId,// Tells you how often we should do a cookie sync (in days)
|
|
504
|
+
frequencyCap:l.frequencyCap,// Url for cookie sync pixel
|
|
505
|
+
pixelUrl:b.replaceAmp(l.pixelUrl),// TODO: Document requirements for redirectUrl
|
|
506
|
+
redirectUrl:l.redirectUrl?b.replaceAmp(l.redirectUrl):null,// Filtering rules as defined in UI
|
|
507
|
+
filteringConsentRuleValues:l.filteringConsentRuleValues},h=b.replaceMPID(f.pixelUrl,d),i=f.redirectUrl?b.replaceMPID(f.redirectUrl,d):"",j=h+encodeURIComponent(i);// TODO: Refactor so that Persistence is only called once
|
|
508
|
+
// outside of the loop
|
|
509
|
+
var m=a._Persistence.getPersistence();// TODO: Is there a historic reason for checking for previousMPID?
|
|
510
|
+
// it does not appear to be passed in anywhere
|
|
511
|
+
return c&&c!==d?void(m&&m[d]&&(!m[d].csd&&(m[d].csd={}),b.performCookieSync(j,f.moduleId,d,m[d].csd,f.filteringConsentRuleValues,e,k))):void(m[d]&&(!m[d].csd&&(m[d].csd={}),g=m[d].csd[f.moduleId.toString()]?m[d].csd[f.moduleId.toString()]:null,g?// TODO: Turn this into a convenience method for readability?
|
|
512
|
+
// We use similar comparisons elsewhere in the SDK,
|
|
513
|
+
// so perhaps we can make a time comparison convenience method
|
|
514
|
+
new Date().getTime()>new Date(g).getTime()+24*(60*(1e3*(// TODO: Turn these numbers into a constant so
|
|
515
|
+
// we can remember what this number is for
|
|
516
|
+
60*f.frequencyCap)))&&b.performCookieSync(j,f.moduleId,d,m[d].csd,f.filteringConsentRuleValues,e,k):b.performCookieSync(j,f.moduleId,d,m[d].csd,f.filteringConsentRuleValues,e,k)))});},this.replaceMPID=function(a,b){return a.replace("%%mpid%%",b)},this.replaceAmp=function(a){return a.replace(/&/g,"&")},this.performCookieSync=function(b,c,d,e,f,g,h){// if MPID is new to cookies, we should not try to perform the cookie sync
|
|
513
517
|
// because a cookie sync can only occur once a user either consents or doesn't
|
|
514
518
|
// we should not check if its enabled if the user has a blank consent
|
|
515
|
-
|
|
519
|
+
// TODO: We should do this check outside of this function
|
|
520
|
+
if(!(h&&g)&&a._Consent.isEnabledForUserConsent(f,a.Identity.getCurrentUser()))// TODO: Refactor so that check is made outside of the function.
|
|
521
|
+
// Cache or store the boolean so that it only gets called once per
|
|
522
|
+
// cookie sync attempt per module.
|
|
523
|
+
// Currently, attemptCookieSync is called as a loop and therefore this
|
|
524
|
+
// function polls the user object and consent multiple times.
|
|
525
|
+
{var i=document.createElement("img");a.Logger.verbose(Messages$7.InformationMessages.CookieSync),i.onload=function(){e[c.toString()]=new Date().getTime(),a._Persistence.saveUserCookieSyncDatesToPersistence(d,e);},i.src=b;}};}
|
|
516
526
|
|
|
517
527
|
var Messages$6=Constants.Messages;function SessionManager(a){var b=this;this.initialize=function(){if(a._Store.sessionId){var c=6e4*a._Store.SDKConfig.sessionTimeout;if(new Date>new Date(a._Store.dateLastEventSent.getTime()+c))b.endSession(),b.startNewSession();else {var d=a._Persistence.getPersistence();d&&!d.cu&&(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null);}}else b.startNewSession();},this.getSession=function(){return a._Store.sessionId},this.startNewSession=function(){if(a.Logger.verbose(Messages$6.InformationMessages.StartingNewSession),a._Helpers.canLog()){a._Store.sessionId=a._Helpers.generateUniqueId().toUpperCase();var c=a.Identity.getCurrentUser(),d=c?c.getMPID():null;if(d&&(a._Store.currentSessionMPIDs=[d]),!a._Store.sessionStartDate){var e=new Date;a._Store.sessionStartDate=e,a._Store.dateLastEventSent=e;}b.setSessionTimer(),a._Store.identifyCalled||(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null),a._Events.logEvent({messageType:Types.MessageType.SessionStart});}else a.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);},this.endSession=function(c){if(a.Logger.verbose(Messages$6.InformationMessages.StartingEndSession),c)a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.sessionId=null,a._Store.dateLastEventSent=null,a._Store.sessionAttributes={},a._Persistence.update();else if(a._Helpers.canLog()){var d,e,f;if(e=a._Persistence.getPersistence(),!e)return;if(e.gs&&!e.gs.sid)return void a.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd);// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
|
|
518
528
|
if(e.gs.sid&&a._Store.sessionId!==e.gs.sid&&(a._Store.sessionId=e.gs.sid),e.gs&&e.gs.les){d=6e4*a._Store.SDKConfig.sessionTimeout;var g=new Date().getTime();f=g-e.gs.les,f<d?b.setSessionTimer():(a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.sessionId=null,a._Store.dateLastEventSent=null,a._Store.sessionStartDate=null,a._Store.sessionAttributes={},a._Persistence.update());}}else a.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession);},this.setSessionTimer=function(){var c=6e4*a._Store.SDKConfig.sessionTimeout;a._Store.globalTimer=window.setTimeout(function(){b.endSession();},c);},this.resetSessionTimer=function(){a._Store.webviewBridgeEnabled||(!a._Store.sessionId&&b.startNewSession(),b.clearSessionTimeout(),b.setSessionTimer()),b.startNewSessionIfNeeded();},this.clearSessionTimeout=function(){clearTimeout(a._Store.globalTimer);},this.startNewSessionIfNeeded=function(){if(!a._Store.webviewBridgeEnabled){var c=a._Persistence.getPersistence();!a._Store.sessionId&&c&&(c.sid?a._Store.sessionId=c.sid:b.startNewSession());}};}
|
|
@@ -606,13 +616,13 @@ for(var f in a._Helpers.isObject(a._Store.SDKConfig.kits)&&0<Object.keys(a._Stor
|
|
|
606
616
|
// TODO: This file is no longer the server model because the web SDK payload
|
|
607
617
|
var MessageType=Types.MessageType,ApplicationTransitionType=Types.ApplicationTransitionType;// TODO: Make this a pure function that returns a new object
|
|
608
618
|
function convertCustomFlags(a,b){var c=[];for(var d in b.flags={},a.CustomFlags)c=[],a.CustomFlags.hasOwnProperty(d)&&(Array.isArray(a.CustomFlags[d])?a.CustomFlags[d].forEach(function(a){("number"==typeof a||"string"==typeof a||"boolean"==typeof a)&&c.push(a.toString());}):(// TODO: Can we use our utility functions here?
|
|
609
|
-
"number"==typeof a.CustomFlags[d]||"string"==typeof a.CustomFlags[d]||"boolean"==typeof a.CustomFlags[d])&&c.push(a.CustomFlags[d].toString()),c.length&&(b.flags[d]=c));}function
|
|
610
|
-
this.appendUserInfo=function(b,c){if(c){if(!b)return c.MPID=null,c.ConsentState=null,c.UserAttributes=null,void(c.UserIdentities=null);if(!(c.MPID&&c.MPID===b.getMPID())){c.MPID=b.getMPID(),c.ConsentState=b.getConsentState(),c.UserAttributes=b.getAllUserAttributes();var d=b.getUserIdentities().userIdentities,e={};for(var f in d){var g=Types.IdentityType.getIdentityType(f);!1!==g&&(e[g]=d[f]);}var h=[];if(a._Helpers.isObject(e)&&Object.keys(e).length)for(var i in e){var j={};j.Identity=e[i],j.Type=a._Helpers.parseNumber(i),h.push(j);}c.UserIdentities=h;}}},this.
|
|
619
|
+
"number"==typeof a.CustomFlags[d]||"string"==typeof a.CustomFlags[d]||"boolean"==typeof a.CustomFlags[d])&&c.push(a.CustomFlags[d].toString()),c.length&&(b.flags[d]=c));}function convertProductToV2DTO(a){return {id:parseStringOrNumber(a.Sku),nm:parseStringOrNumber(a.Name),pr:parseNumber(a.Price),qt:parseNumber(a.Quantity),br:parseStringOrNumber(a.Brand),va:parseStringOrNumber(a.Variant),ca:parseStringOrNumber(a.Category),ps:parseNumber(a.Position),cc:parseStringOrNumber(a.CouponCode),tpa:parseNumber(a.TotalAmount),attrs:a.Attributes}}function convertProductListToV2DTO(a){return a?a.map(function(a){return convertProductToV2DTO(a)}):[]}function ServerModel(a){var b=this;// TODO: Can we refactor this to not mutate the event?
|
|
620
|
+
this.appendUserInfo=function(b,c){if(c){if(!b)return c.MPID=null,c.ConsentState=null,c.UserAttributes=null,void(c.UserIdentities=null);if(!(c.MPID&&c.MPID===b.getMPID())){c.MPID=b.getMPID(),c.ConsentState=b.getConsentState(),c.UserAttributes=b.getAllUserAttributes();var d=b.getUserIdentities().userIdentities,e={};for(var f in d){var g=Types.IdentityType.getIdentityType(f);!1!==g&&(e[g]=d[f]);}var h=[];if(a._Helpers.isObject(e)&&Object.keys(e).length)for(var i in e){var j={};j.Identity=e[i],j.Type=a._Helpers.parseNumber(i),h.push(j);}c.UserIdentities=h;}}},this.convertToConsentStateV2DTO=function(a){if(!a)return null;var b={},c=a.getGDPRConsentState();if(c){var d={};for(var e in b.gdpr=d,c)if(c.hasOwnProperty(e)){var f=c[e];b.gdpr[e]={},"boolean"==typeof f.Consented&&(d[e].c=f.Consented),"number"==typeof f.Timestamp&&(d[e].ts=f.Timestamp),"string"==typeof f.ConsentDocument&&(d[e].d=f.ConsentDocument),"string"==typeof f.Location&&(d[e].l=f.Location),"string"==typeof f.HardwareId&&(d[e].h=f.HardwareId);}}var g=a.getCCPAConsentState();return g&&(b.ccpa={data_sale_opt_out:{c:g.Consented,ts:g.Timestamp,d:g.ConsentDocument,l:g.Location,h:g.HardwareId}}),b},this.createEventObject=function(c,d){var e={},f={},g=c.messageType===Types.MessageType.OptOut?!a._Store.isEnabled:null;// TODO: Why is Webview Bridge Enabled or Opt Out necessary here?
|
|
611
621
|
if(a._Store.sessionId||c.messageType===Types.MessageType.OptOut||a._Store.webviewBridgeEnabled){f=c.hasOwnProperty("toEventAPIObject")?c.toEventAPIObject():{// This is an artifact from v2 events where SessionStart/End and AST event
|
|
612
622
|
// names are numbers (1, 2, or 10), but going forward with v3, these lifecycle
|
|
613
623
|
// events do not have names, but are denoted by their `event_type`
|
|
614
624
|
EventName:c.name||c.messageType,EventCategory:c.eventType,EventAttributes:a._Helpers.sanitizeAttributes(c.data,c.name),SourceMessageId:c.sourceMessageId||a._Helpers.generateUniqueId(),EventDataType:c.messageType,CustomFlags:c.customFlags||{},UserAttributeChanges:c.userAttributeChanges,UserIdentityChanges:c.userIdentityChanges},c.messageType!==Types.MessageType.SessionEnd&&(a._Store.dateLastEventSent=new Date),e={// FIXME: Deprecate when we get rid of V2
|
|
615
|
-
Store:a._Store.serverSettings,SDKVersion:Constants.sdkVersion,SessionId:a._Store.sessionId,SessionStartDate:a._Store.sessionStartDate?a._Store.sessionStartDate.getTime():0,Debug:a._Store.SDKConfig.isDevelopmentMode,Location:a._Store.currentPosition,OptOut:g,ExpandedEventCount:0,AppVersion:a.getAppVersion(),AppName:a.getAppName(),Package:a._Store.SDKConfig["package"],ClientGeneratedId:a._Store.clientId,DeviceId:a._Store.deviceId,IntegrationAttributes:a._Store.integrationAttributes,CurrencyCode:a._Store.currencyCode,DataPlan:a._Store.SDKConfig.dataPlan?a._Store.SDKConfig.dataPlan:{}},f.EventDataType===MessageType.AppStateTransition&&(f.IsFirstRun=a._Store.isFirstRun,f.LaunchReferral=window.location.href||null),f.CurrencyCode=a._Store.currencyCode;var h=d||a.Identity.getCurrentUser();return b.appendUserInfo(h,f),c.messageType===Types.MessageType.SessionEnd&&(f.SessionLength=a._Store.dateLastEventSent.getTime()-a._Store.sessionStartDate.getTime(),f.currentSessionMPIDs=a._Store.currentSessionMPIDs,f.EventAttributes=a._Store.sessionAttributes,a._Store.currentSessionMPIDs=[],a._Store.sessionStartDate=null),e.Timestamp=a._Store.dateLastEventSent.getTime(),a._Helpers.extend({},f,e)}return null},this.
|
|
625
|
+
Store:a._Store.serverSettings,SDKVersion:Constants.sdkVersion,SessionId:a._Store.sessionId,SessionStartDate:a._Store.sessionStartDate?a._Store.sessionStartDate.getTime():0,Debug:a._Store.SDKConfig.isDevelopmentMode,Location:a._Store.currentPosition,OptOut:g,ExpandedEventCount:0,AppVersion:a.getAppVersion(),AppName:a.getAppName(),Package:a._Store.SDKConfig["package"],ClientGeneratedId:a._Store.clientId,DeviceId:a._Store.deviceId,IntegrationAttributes:a._Store.integrationAttributes,CurrencyCode:a._Store.currencyCode,DataPlan:a._Store.SDKConfig.dataPlan?a._Store.SDKConfig.dataPlan:{}},f.EventDataType===MessageType.AppStateTransition&&(f.IsFirstRun=a._Store.isFirstRun,f.LaunchReferral=window.location.href||null),f.CurrencyCode=a._Store.currencyCode;var h=d||a.Identity.getCurrentUser();return b.appendUserInfo(h,f),c.messageType===Types.MessageType.SessionEnd&&(f.SessionLength=a._Store.dateLastEventSent.getTime()-a._Store.sessionStartDate.getTime(),f.currentSessionMPIDs=a._Store.currentSessionMPIDs,f.EventAttributes=a._Store.sessionAttributes,a._Store.currentSessionMPIDs=[],a._Store.sessionStartDate=null),e.Timestamp=a._Store.dateLastEventSent.getTime(),a._Helpers.extend({},f,e)}return null},this.convertEventToV2DTO=function(c){var d={n:c.EventName,et:c.EventCategory,ua:c.UserAttributes,ui:c.UserIdentities,ia:c.IntegrationAttributes,str:c.Store,attrs:c.EventAttributes,sdk:c.SDKVersion,sid:c.SessionId,sl:c.SessionLength,ssd:c.SessionStartDate,dt:c.EventDataType,dbg:c.Debug,ct:c.Timestamp,lc:c.Location,o:c.OptOut,eec:c.ExpandedEventCount,av:c.AppVersion,cgid:c.ClientGeneratedId,das:c.DeviceId,mpid:c.MPID,smpids:c.currentSessionMPIDs};c.DataPlan&&c.DataPlan.PlanId&&(d.dp_id=c.DataPlan.PlanId,c.DataPlan.PlanVersion&&(d.dp_v=c.DataPlan.PlanVersion));var e=b.convertToConsentStateV2DTO(c.ConsentState);return e&&(d.con=e),c.EventDataType===MessageType.AppStateTransition&&(d.fr=c.IsFirstRun,d.iu=!1,d.at=ApplicationTransitionType.AppInit,d.lr=c.LaunchReferral,d.attrs=null),c.CustomFlags&&convertCustomFlags(c,d),c.EventDataType===MessageType.Commerce?(d.cu=c.CurrencyCode,c.ShoppingCart&&(d.sc={pl:convertProductListToV2DTO(c.ShoppingCart.ProductList)}),c.ProductAction?d.pd={an:c.ProductAction.ProductActionType,cs:a._Helpers.parseNumber(c.ProductAction.CheckoutStep),co:c.ProductAction.CheckoutOptions,pl:convertProductListToV2DTO(c.ProductAction.ProductList),ti:c.ProductAction.TransactionId,ta:c.ProductAction.Affiliation,tcc:c.ProductAction.CouponCode,tr:a._Helpers.parseNumber(c.ProductAction.TotalAmount),ts:a._Helpers.parseNumber(c.ProductAction.ShippingAmount),tt:a._Helpers.parseNumber(c.ProductAction.TaxAmount)}:c.PromotionAction?d.pm={an:c.PromotionAction.PromotionActionType,pl:c.PromotionAction.PromotionList.map(function(a){return {id:a.Id,nm:a.Name,cr:a.Creative,ps:a.Position?a.Position:0}})}:c.ProductImpressions&&(d.pi=c.ProductImpressions.map(function(a){return {pil:a.ProductImpressionList,pl:convertProductListToV2DTO(a.ProductList)}}))):c.EventDataType===MessageType.Profile&&(d.pet=c.ProfileMessageType),d};}
|
|
616
626
|
|
|
617
627
|
function forwardingStatsUploader(a){function b(){var b=a._Forwarders.getForwarderStatsQueue(),c=a._Persistence.forwardingStatsBatches.uploadsTable,d=Date.now();for(var e in b.length&&(c[d]={uploading:!1,data:b},a._Forwarders.setForwarderStatsQueue([])),c)(function(b){if(c.hasOwnProperty(b)&&!1===c[b].uploading){var d=function(){4===e.readyState&&(200===e.status||202===e.status?(a.Logger.verbose("Successfully sent "+e.statusText+" from server"),delete c[b]):"4"===e.status.toString()[0]?429!==e.status&&delete c[b]:c[b].uploading=!1);},e=a._Helpers.createXHR(d),f=c[b].data;c[b].uploading=!0,a._APIClient.sendBatchForwardingStatsToServer(f,e);}})(e);}this.startForwardingStatsTimer=function(){mParticle._forwardingStatsTimer=setInterval(function(){b();},a._Store.SDKConfig.forwarderStatsTimeout);};}
|
|
618
628
|
|
|
@@ -771,14 +781,17 @@ if(!d||!Array.isArray(d))l=!0;else if(n.length!==d.length)l=!0;else for(var c=0;
|
|
|
771
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={},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
|
|
772
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 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};}
|
|
773
783
|
|
|
774
|
-
function Consent(a){var b=this
|
|
784
|
+
var CCPAPurpose="data_sale_opt_out";function Consent(a){var b=this;// this function is called when consent is required to
|
|
785
|
+
// determine if a cookie sync should happen, or a
|
|
786
|
+
// forwarder should be initialized
|
|
787
|
+
// TODO: Refactor this method into a constructor
|
|
775
788
|
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:
|
|
776
789
|
// GDPR - '1' + purpose name
|
|
777
790
|
// CCPA - '2data_sale_opt_out' (there is only 1 purpose of data_sale_opt_out for CCPA)
|
|
778
|
-
var g=f.getGDPRConsentState();if(g)for(var h in g)g.hasOwnProperty(h)&&(d=a._Helpers.generateHash("1"+h).toString(),e[d]=g[h].Consented);var i=f.getCCPAConsentState();i&&(d=a._Helpers.generateHash("
|
|
791
|
+
var g=f.getGDPRConsentState();if(g)for(var h in g)g.hasOwnProperty(h)&&(d=a._Helpers.generateHash("1"+h).toString(),e[d]=g[h].Consented);var i=f.getCCPAConsentState();i&&(d=a._Helpers.generateHash("2data_sale_opt_out").toString(),e[d]=i.Consented);}var j=b.values.some(function(a){var b=a.consentPurpose,c=a.hasConsented;return !!e.hasOwnProperty(b)&&e[b]===c});return b.includeOnMatch===j},this.createPrivacyConsent=function(b,c,d,e,f){return "boolean"==typeof b?c&&isNaN(c)?(a.Logger.error("Timestamp must be a valid number when constructing a Consent object."),null):d&&"string"!=typeof d?(a.Logger.error("Document must be a valid string when constructing a Consent object."),null):e&&"string"!=typeof e?(a.Logger.error("Location must be a valid string when constructing a Consent object."),null):f&&"string"!=typeof f?(a.Logger.error("Hardware ID must be a valid string when constructing a Consent object."),null):{Consented:b,Timestamp:c||Date.now(),ConsentDocument:d,Location:e,HardwareId:f}:(a.Logger.error("Consented boolean is required when constructing a Consent object."),null)},this.ConsentSerialization={toMinifiedJsonObject:function toMinifiedJsonObject(a){var b,c={};if(a){var d=a.getGDPRConsentState();if(d)for(var e in c.gdpr={},d)if(d.hasOwnProperty(e)){var f=d[e];c.gdpr[e]={},"boolean"==typeof f.Consented&&(c.gdpr[e].c=f.Consented),"number"==typeof f.Timestamp&&(c.gdpr[e].ts=f.Timestamp),"string"==typeof f.ConsentDocument&&(c.gdpr[e].d=f.ConsentDocument),"string"==typeof f.Location&&(c.gdpr[e].l=f.Location),"string"==typeof f.HardwareId&&(c.gdpr[e].h=f.HardwareId);}var g=a.getCCPAConsentState();g&&(c.ccpa=(b={},b[CCPAPurpose]={},b),"boolean"==typeof g.Consented&&(c.ccpa[CCPAPurpose].c=g.Consented),"number"==typeof g.Timestamp&&(c.ccpa[CCPAPurpose].ts=g.Timestamp),"string"==typeof g.ConsentDocument&&(c.ccpa[CCPAPurpose].d=g.ConsentDocument),"string"==typeof g.Location&&(c.ccpa[CCPAPurpose].l=g.Location),"string"==typeof g.HardwareId&&(c.ccpa[CCPAPurpose].h=g.HardwareId));}return c},fromMinifiedJsonObject:function fromMinifiedJsonObject(a){var c=b.createConsentState();if(a.gdpr)for(var d in a.gdpr)if(a.gdpr.hasOwnProperty(d)){var e=b.createPrivacyConsent(a.gdpr[d].c,a.gdpr[d].ts,a.gdpr[d].d,a.gdpr[d].l,a.gdpr[d].h);c.addGDPRConsentState(d,e);}if(a.ccpa&&a.ccpa.hasOwnProperty(CCPAPurpose)){var f=b.createPrivacyConsent(a.ccpa[CCPAPurpose].c,a.ccpa[CCPAPurpose].ts,a.ccpa[CCPAPurpose].d,a.ccpa[CCPAPurpose].l,a.ccpa[CCPAPurpose].h);c.setCCPAConsentState(f);}return c}},this.createConsentState=function(c){function d(a){if("string"!=typeof a)return null;var b=a.trim();return b.length?b.toLowerCase():null}/**
|
|
779
792
|
* Invoke these methods on a consent state object.
|
|
780
793
|
* <p>
|
|
781
|
-
* Usage:
|
|
794
|
+
* Usage: const consent = mParticle.Consent.createConsentState()
|
|
782
795
|
* <br>
|
|
783
796
|
* consent.setGDPRCoonsentState()
|
|
784
797
|
*
|
|
@@ -789,22 +802,22 @@ var g=f.getGDPRConsentState();if(g)for(var h in g)g.hasOwnProperty(h)&&(d=a._Hel
|
|
|
789
802
|
* @method addGDPRConsentState
|
|
790
803
|
* @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data
|
|
791
804
|
* @param gdprConsent [Object] A GDPR consent object created via mParticle.Consent.createGDPRConsent(...)
|
|
792
|
-
*/function
|
|
805
|
+
*/function e(c,e){var f=d(c);if(!f)return a.Logger.error("Purpose must be a string."),this;if(!isObject(e))return a.Logger.error("Invoked with a bad or empty consent object."),this;var g=b.createPrivacyConsent(e.Consented,e.Timestamp,e.ConsentDocument,e.Location,e.HardwareId);return g&&(k[f]=g),this}function f(a){if(!a)k={};else if(isObject(a))for(var b in k={},a)a.hasOwnProperty(b)&&this.addGDPRConsentState(b,a[b]);return this}/**
|
|
793
806
|
* Remove a GDPR Consent State to the consent state object
|
|
794
807
|
*
|
|
795
808
|
* @method removeGDPRConsentState
|
|
796
809
|
* @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data
|
|
797
|
-
*/function
|
|
810
|
+
*/function g(a){var b=d(a);return b?(delete k[b],this):this}/**
|
|
798
811
|
* Gets the GDPR Consent State
|
|
799
812
|
*
|
|
800
813
|
* @method getGDPRConsentState
|
|
801
814
|
* @return {Object} A GDPR Consent State
|
|
802
|
-
*/function
|
|
815
|
+
*/function h(){return Object.assign({},k)}/**
|
|
803
816
|
* Sets a CCPA Consent state (has a single purpose of 'data_sale_opt_out')
|
|
804
817
|
*
|
|
805
818
|
* @method setCCPAConsentState
|
|
806
819
|
* @param {Object} ccpaConsent CCPA Consent State
|
|
807
|
-
*/function
|
|
820
|
+
*/function i(c){if(!isObject(c))return a.Logger.error("Invoked with a bad or empty CCPA consent object."),this;var d=b.createPrivacyConsent(c.Consented,c.Timestamp,c.ConsentDocument,c.Location,c.HardwareId);return d&&(l[CCPAPurpose]=d),this}/**
|
|
808
821
|
* Gets the CCPA Consent State
|
|
809
822
|
*
|
|
810
823
|
* @method getCCPAConsentStatensent
|
|
@@ -813,7 +826,10 @@ var g=f.getGDPRConsentState();if(g)for(var h in g)g.hasOwnProperty(h)&&(d=a._Hel
|
|
|
813
826
|
* Removes CCPA from the consent state object
|
|
814
827
|
*
|
|
815
828
|
* @method removeCCPAConsentState
|
|
816
|
-
*/function
|
|
829
|
+
*/function j(){return delete l[CCPAPurpose],this}// TODO: Can we remove this? It is deprecated.
|
|
830
|
+
var k={},l={};if(c){var m=b.createConsentState();// TODO: Remove casting once `removeCCPAState` is removed;
|
|
831
|
+
return m.setGDPRConsentState(c.getGDPRConsentState()),m.setCCPAConsentState(c.getCCPAConsentState()),m}return {setGDPRConsentState:f,addGDPRConsentState:e,setCCPAConsentState:i,getCCPAConsentState:function a(){return l[CCPAPurpose]},getGDPRConsentState:h,removeGDPRConsentState:g,removeCCPAState:function b(){// @ts-ignore
|
|
832
|
+
return a.Logger.warning("removeCCPAState is deprecated and will be removed in a future release; use removeCCPAConsentState instead"),j()},removeCCPAConsentState:j}};}
|
|
817
833
|
|
|
818
834
|
/*
|
|
819
835
|
TODO: Including this as a workaround because attempting to import it from
|
|
@@ -1192,7 +1208,7 @@ if(mParticle[c[0]])mParticle[d].apply(this,c);else {var e=d.split(".");try{for(v
|
|
|
1192
1208
|
|
|
1193
1209
|
// This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise!
|
|
1194
1210
|
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
|
|
1195
|
-
_Helpers:{sanitizeAttributes:window.mParticle.getInstance()._Helpers.sanitizeAttributes,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}();
|
|
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}();
|
|
1196
1212
|
|
|
1197
1213
|
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
|
|
1198
1214
|
/**
|