@mparticle/web-sdk 2.25.3 → 2.26.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 +50 -37
- package/dist/mparticle.esm.js +50 -37
- package/dist/mparticle.js +223 -75
- package/package.json +1 -1
- package/src/apiClient.ts +2 -1
- package/src/audience.ts +9 -0
- package/src/audienceManager.ts +88 -0
- package/src/batchUploader.ts +11 -66
- package/src/constants.ts +4 -0
- package/src/identity.js +32 -2
- package/src/sdkRuntimeModels.ts +16 -3
- package/src/store.ts +85 -8
- package/src/uploaders.ts +59 -0
package/dist/mparticle.esm.js
CHANGED
|
@@ -61,11 +61,11 @@ var _TriggerUploadType,MessageType$2={SessionStart:1,SessionEnd:2,PageView:3,Pag
|
|
|
61
61
|
// Continuation of enum above, but in seperate object since we don't expose these to end user
|
|
62
62
|
IdentityType$1.isValid=function(a){if("number"==typeof a)for(var b in IdentityType$1)if(IdentityType$1.hasOwnProperty(b)&&IdentityType$1[b]===a)return !0;return !1},IdentityType$1.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$1.getIdentityType=function(a){return "other"===a?IdentityType$1.Other:"customerid"===a?IdentityType$1.CustomerId:"facebook"===a?IdentityType$1.Facebook:"twitter"===a?IdentityType$1.Twitter:"google"===a?IdentityType$1.Google:"microsoft"===a?IdentityType$1.Microsoft:"yahoo"===a?IdentityType$1.Yahoo:"email"===a?IdentityType$1.Email:"facebookcustomaudienceid"===a?IdentityType$1.FacebookCustomAudienceId:"other2"===a?IdentityType$1.Other2:"other3"===a?IdentityType$1.Other3:"other4"===a?IdentityType$1.Other4:"other5"===a?IdentityType$1.Other5:"other6"===a?IdentityType$1.Other6:"other7"===a?IdentityType$1.Other7:"other8"===a?IdentityType$1.Other8:"other9"===a?IdentityType$1.Other9:"other10"===a?IdentityType$1.Other10:"mobile_number"===a?IdentityType$1.MobileNumber:"phone_number_2"===a?IdentityType$1.PhoneNumber2:!("phone_number_3"!=a)&&IdentityType$1.PhoneNumber3},IdentityType$1.getIdentityName=function(a){return a===IdentityType$1.Other?"other":a===IdentityType$1.CustomerId?"customerid":a===IdentityType$1.Facebook?"facebook":a===IdentityType$1.Twitter?"twitter":a===IdentityType$1.Google?"google":a===IdentityType$1.Microsoft?"microsoft":a===IdentityType$1.Yahoo?"yahoo":a===IdentityType$1.Email?"email":a===IdentityType$1.FacebookCustomAudienceId?"facebookcustomaudienceid":a===IdentityType$1.Other2?"other2":a===IdentityType$1.Other3?"other3":a===IdentityType$1.Other4?"other4":a===IdentityType$1.Other5?"other5":a===IdentityType$1.Other6?"other6":a===IdentityType$1.Other7?"other7":a===IdentityType$1.Other8?"other8":a===IdentityType$1.Other9?"other9":a===IdentityType$1.Other10?"other10":a===IdentityType$1.MobileNumber?"mobile_number":a===IdentityType$1.PhoneNumber2?"phone_number_2":a===IdentityType$1.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$2,EventType:EventType,CommerceEventType:CommerceEventType,IdentityType:IdentityType$1,ProfileMessageType:ProfileMessageType,ApplicationTransitionType:ApplicationTransitionType$1,ProductActionType:ProductActionType,PromotionActionType:PromotionActionType,TriggerUploadType:TriggerUploadType,Environment:Environment};
|
|
63
63
|
|
|
64
|
-
var version = "2.
|
|
64
|
+
var version = "2.26.0";
|
|
65
65
|
|
|
66
|
-
var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions"},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
|
|
67
|
-
},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
|
|
68
|
-
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",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage",DirectUrlRouting:"directURLRouting",CacheIdentity:"cacheIdentity"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out",IdentityMethods:{Modify:"modify",Logout:"logout",Login:"login",Identify:"identify"}};var ONE_DAY_IN_SECONDS=86400;var MILLIS_IN_ONE_SEC=1e3;
|
|
66
|
+
var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
|
|
67
|
+
},DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
|
|
68
|
+
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",EventBatchingIntervalMillis:"eventBatchingIntervalMillis",OfflineStorage:"offlineStorage",DirectUrlRouting:"directURLRouting",CacheIdentity:"cacheIdentity",AudienceAPI:"audienceAPI"},DefaultInstance:"default_instance",CCPAPurpose:"data_sale_opt_out",IdentityMethods:{Modify:"modify",Logout:"logout",Login:"login",Identify:"identify"}};var ONE_DAY_IN_SECONDS=86400;var MILLIS_IN_ONE_SEC=1e3;
|
|
69
69
|
|
|
70
70
|
/******************************************************************************
|
|
71
71
|
Copyright (c) Microsoft Corporation.
|
|
@@ -429,6 +429,8 @@ var BaseVault=/** @class */function(){/**
|
|
|
429
429
|
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
430
430
|
var a=this.storageObject.getItem(this._storageKey);return this.contents=a?JSON.parse(a):null,this.logger.verbose("Retrieving item from Storage: ".concat(a)),this.contents},a.prototype.purge=function(){this.logger.verbose("Purging Storage"),this.contents=null,this.storageObject.removeItem(this._storageKey);},a}();var LocalStorageVault=/** @class */function(a){function b(b,c){return a.call(this,b,window.localStorage,c)||this}return __extends(b,a),b}(BaseVault);var SessionStorageVault=/** @class */function(a){function b(b,c){return a.call(this,b,window.sessionStorage,c)||this}return __extends(b,a),b}(BaseVault);
|
|
431
431
|
|
|
432
|
+
var AsyncUploader=/** @class */function(){function a(a){this.url=a;}return a}();var FetchUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a,b){return __awaiter(this,void 0,void 0,function(){var c;return __generator(this,function(d){switch(d.label){case 0:return c=b||this.url,[4/*yield*/,fetch(c,a)];case 1:return [2/*return*/,d.sent()]}})})},b}(AsyncUploader);var XHRUploader=/** @class */function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return __extends(b,a),b.prototype.upload=function(a){return __awaiter(this,void 0,void 0,function(){var b;return __generator(this,function(c){switch(c.label){case 0:return [4/*yield*/,this.makeRequest(this.url,a.body)];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);
|
|
433
|
+
|
|
432
434
|
/**
|
|
433
435
|
* BatchUploader contains all the logic to store/retrieve events and batches
|
|
434
436
|
* to/from persistence, and upload batches to mParticle.
|
|
@@ -447,7 +449,8 @@ var a=this.storageObject.getItem(this._storageKey);return this.contents=a?JSON.p
|
|
|
447
449
|
* Creates an instance of a BatchUploader
|
|
448
450
|
* @param {MParticleWebSDK} mpInstance - the mParticle SDK instance
|
|
449
451
|
* @param {number} uploadInterval - the desired upload interval in milliseconds
|
|
450
|
-
*/function a(b,c){var d;this.offlineStorageEnabled=!1,this.mpInstance=b,this.uploadIntervalMillis=c,this.batchingEnabled=c>=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis<a.MINIMUM_INTERVAL_MILLIS&&(this.uploadIntervalMillis=a.MINIMUM_INTERVAL_MILLIS),this.eventsQueuedForProcessing=[],this.batchesQueuedForProcessing=[],this.offlineStorageEnabled=this.isOfflineStorageAvailable(),this.offlineStorageEnabled&&(this.eventVault=new SessionStorageVault("".concat(b._Store.storageName,"-events"),{logger:b.Logger}),this.batchVault=new LocalStorageVault("".concat(b._Store.storageName,"-batches"),{logger:b.Logger}),(d=this.eventsQueuedForProcessing).push.apply(d,this.eventVault.retrieve()));var e=this.mpInstance._Store,f=e.SDKConfig,g=e.devToken,h=this.mpInstance._Helpers.createServiceUrl(f.v3SecureServiceUrl,g);this.uploadUrl="".concat(h,"/events"),this.uploader=window.fetch?new FetchUploader(this.uploadUrl):new XHRUploader(this.uploadUrl),this.triggerUploadInterval(!0,!1),this.addEventListeners();}return a.prototype.isOfflineStorageAvailable=function(){var a=this.mpInstance,b=a._Helpers.getFeatureFlag,c=a._Store.deviceId,d=b(Constants.FeatureFlags.OfflineStorage),e=parseInt(d,10),f=getRampNumber(c);//
|
|
452
|
+
*/function a(b,c){var d;this.offlineStorageEnabled=!1,this.mpInstance=b,this.uploadIntervalMillis=c,this.batchingEnabled=c>=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis<a.MINIMUM_INTERVAL_MILLIS&&(this.uploadIntervalMillis=a.MINIMUM_INTERVAL_MILLIS),this.eventsQueuedForProcessing=[],this.batchesQueuedForProcessing=[],this.offlineStorageEnabled=this.isOfflineStorageAvailable(),this.offlineStorageEnabled&&(this.eventVault=new SessionStorageVault("".concat(b._Store.storageName,"-events"),{logger:b.Logger}),this.batchVault=new LocalStorageVault("".concat(b._Store.storageName,"-batches"),{logger:b.Logger}),(d=this.eventsQueuedForProcessing).push.apply(d,this.eventVault.retrieve()));var e=this.mpInstance._Store,f=e.SDKConfig,g=e.devToken,h=this.mpInstance._Helpers.createServiceUrl(f.v3SecureServiceUrl,g);this.uploadUrl="".concat(h,"/events"),this.uploader=window.fetch?new FetchUploader(this.uploadUrl):new XHRUploader(this.uploadUrl),this.triggerUploadInterval(!0,!1),this.addEventListeners();}return a.prototype.isOfflineStorageAvailable=function(){var a=this.mpInstance,b=a._Helpers.getFeatureFlag,c=a._Store.deviceId,d=b(Constants.FeatureFlags.OfflineStorage),e=parseInt(d,10),f=getRampNumber(c);// https://go.mparticle.com/work/SQDSDKS-6317
|
|
453
|
+
// TODO: Handle cases where Local Storage is unavailable
|
|
451
454
|
// Potentially shared between Vault and Persistence as well
|
|
452
455
|
// https://go.mparticle.com/work/SQDSDKS-5022
|
|
453
456
|
return e>=f},a.prototype.addEventListeners=function(){var a=this;// visibility change is a document property, not window
|
|
@@ -455,9 +458,10 @@ document.addEventListener("visibilitychange",function(){a.prepareAndUpload(!1,a.
|
|
|
455
458
|
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.
|
|
456
459
|
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;return __generator(this,function(l){switch(l.label){case 0:return d=this.mpInstance.Identity.getCurrentUser(),e=this.eventsQueuedForProcessing,this.eventsQueuedForProcessing=[],this.offlineStorageEnabled&&this.eventVault&&this.eventVault.store([]),f=[],isEmpty(e)||(f=a.createNewBatches(e,d,this.mpInstance)),this.offlineStorageEnabled&&this.batchVault&&((i=this.batchesQueuedForProcessing).unshift.apply(i,this.batchVault.retrieve()),this.batchVault.purge()),isEmpty(f)||(j=this.batchesQueuedForProcessing).push.apply(j,f),g=this.batchesQueuedForProcessing,this.batchesQueuedForProcessing=[],[4/*yield*/,this.uploadBatches(this.mpInstance.Logger,g,c)];case 1:return h=l.sent(),isEmpty(h)||(k=this.batchesQueuedForProcessing).unshift.apply(k,h),!c&&this.offlineStorageEnabled&&this.batchVault&&(this.batchVault.store(this.batchesQueuedForProcessing),this.batchesQueuedForProcessing=[]),b&&this.triggerUploadInterval(b,!1),[2/*return*/]}})})},a.prototype.uploadBatches=function(b,c,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
|
|
457
460
|
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.
|
|
458
|
-
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}();
|
|
461
|
+
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}();
|
|
459
462
|
|
|
460
|
-
function APIClient(a,b){this.uploader=null;var c=this;this.queueEventForBatchUpload=function(b){if(!this.uploader){
|
|
463
|
+
function APIClient(a,b){this.uploader=null;var c=this;this.queueEventForBatchUpload=function(b){if(!this.uploader){// https://go.mparticle.com/work/SQDSDKS-6317
|
|
464
|
+
var c=parseNumber(a._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis));this.uploader=new BatchUploader(a,c);}// https://go.mparticle.com/work/SQDSDKS-6038
|
|
461
465
|
this.uploader.queueEvent(b),a._Persistence.update();},this.processQueuedEvents=function(){var b,d=a.Identity.getCurrentUser();if(d&&(b=d.getMPID()),a._Store.eventQueue.length&&b){var e=a._Store.eventQueue;a._Store.eventQueue=[],this.appendUserInfoToEvents(d,e),e.forEach(function(a){c.sendEventToServer(a);});}},this.appendUserInfoToEvents=function(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
|
|
462
466
|
// need to be set, or if we are still fetching the config (self hosted only), and so require delaying events
|
|
463
467
|
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)?(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)):void(this.processQueuedEvents(),isEmpty(c)||(e.shouldUploadEvent&&this.queueEventForBatchUpload(c),c.EventName!==Types.MessageType.AppStateTransition&&(b&&b.kitBlockingEnabled&&(c=b.createBlockedEvent(c)),c&&a._Forwarders.sendEventToForwarders(c))))},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(){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));};}
|
|
@@ -541,7 +545,8 @@ return a._Helpers.parseNumber(b)};}
|
|
|
541
545
|
function createSDKConfig(a){// TODO: Refactor to create a default config object
|
|
542
546
|
var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultBaseUrls)b[c]=Constants.DefaultBaseUrls[c];return b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels
|
|
543
547
|
function Store(a,b,c){var d=this,e={isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},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},// Placeholder for in-memory persistence model
|
|
544
|
-
persistenceData:{cu:null,gs:{sid:null,ie:null,sa:null,ss:null,dt:null,av:null,cgid:null,das:null,ia:null,c:null,csm:null,les:null,ssd:null},l:null}};for(var f in e)this[f]=e[f];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a,this.SDKConfig),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&b._Helpers.returnConvertedBoolean(a.isDevelopmentMode);var g=processBaseUrls(a,this.SDKConfig.flags,c);for(var h in g)this.SDKConfig[h]=g[h];if(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 i=a.identityCallback;b._Helpers.Validators.isFunction(i)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(i)+" . 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 j=a.dataPlan;j.planId&&(isDataPlanSlug(j.planId)?this.SDKConfig.dataPlan.PlanId=j.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),j.planVersion&&(isNumber(j.planVersion)?this.SDKConfig.dataPlan.PlanVersion=j.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 k=a.dataPlanOptions;k.hasOwnProperty("dataPlanVersion")&&k.hasOwnProperty("blockUserAttributes")&&k.hasOwnProperty("blockEventAttributes")&&k.hasOwnProperty("blockEvents")&&k.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionAttributes={},b._Persistence.update();}
|
|
548
|
+
persistenceData:{cu:null,gs:{sid:null,ie:null,sa:null,ss:null,dt:null,av:null,cgid:null,das:null,ia:null,c:null,csm:null,les:null,ssd:null},l:null}};for(var f in e)this[f]=e[f];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a,this.SDKConfig),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&b._Helpers.returnConvertedBoolean(a.isDevelopmentMode);var g=processBaseUrls(a,this.SDKConfig.flags,c);for(var h in g)this.SDKConfig[h]=g[h];if(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 i=a.identityCallback;b._Helpers.Validators.isFunction(i)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof(i)+" . 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 j=a.dataPlan;j.planId&&(isDataPlanSlug(j.planId)?this.SDKConfig.dataPlan.PlanId=j.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),j.planVersion&&(isNumber(j.planVersion)?this.SDKConfig.dataPlan.PlanVersion=j.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 k=a.dataPlanOptions;k.hasOwnProperty("dataPlanVersion")&&k.hasOwnProperty("blockUserAttributes")&&k.hasOwnProperty("blockEventAttributes")&&k.hasOwnProperty("blockEvents")&&k.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionAttributes={},b._Persistence.update();},this.getFirstSeenTime=function(a){return a?d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a].fst?d.persistenceData[a].fst:null:null},this.setFirstSeenTime=function(a,c){if(a){var e=c||new Date().getTime();d.persistenceData&&(!d.persistenceData[a]&&(d.persistenceData[a]={}),!d.persistenceData[a].fst&&(d.persistenceData[a].fst=e,b._Persistence.savePersistence(d.persistenceData)));}},this.getLastSeenTime=function(a){if(!a)return null;// // https://go.mparticle.com/work/SQDSDKS-6315
|
|
549
|
+
var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a].lst?d.persistenceData[a].lst:null},this.setLastSeenTime=function(a,c){if(a){var e=c||new Date().getTime();d.persistenceData&&(!d.persistenceData[a]&&(d.persistenceData[a]={}),!d.persistenceData[a].lst&&(d.persistenceData[a].lst=e,b._Persistence.savePersistence(d.persistenceData)));}};}function processFlags(a){var b={},c=Constants.FeatureFlags,d=c.ReportBatching,e=c.EventBatchingIntervalMillis,f=c.OfflineStorage,g=c.DirectUrlRouting,h=c.CacheIdentity,i=c.AudienceAPI;return a.flags?(b[d]=a.flags[d]||!1,b[e]=parseNumber(a.flags[e])||Constants.DefaultConfig.uploadInterval,b[f]=a.flags[f]||"0",b[g]="True"===a.flags[g],b[h]="True"===a.flags[h],b[i]="True"===a.flags[i],b):{};// Passed in config flags take priority over defaults
|
|
545
550
|
}function processBaseUrls(a,b,c){// an API key is not present in a webview only mode. In this case, no baseUrls are needed
|
|
546
551
|
if(!c)return {};// Set default baseUrls
|
|
547
552
|
// When direct URL routing is false, update baseUrls based custom urls
|
|
@@ -710,7 +715,10 @@ for(var d in b)b[d].expireTimestamp<c&&delete b[d];a.store(b);};var tryCacheIden
|
|
|
710
715
|
var h=hasValidCachedIdentity(g,a,b);// If Identity is cached, then immediately parse the identity response
|
|
711
716
|
if(h){var i=getCachedIdentity(g,a,b);return c(i,d,e,f,g,a,!0),!0}return !1};
|
|
712
717
|
|
|
713
|
-
var
|
|
718
|
+
var AudienceManager=/** @class */function(){function a(a,b,c){this.url="",this.logger=c,this.url="https://".concat(a).concat(b,"/audience"),this.userAudienceAPI=window.fetch?new FetchUploader(this.url):new XHRUploader(this.url);}return a.prototype.sendGetUserAudienceRequest=function(a,b){return __awaiter(this,void 0,void 0,function(){var c,d,e,f,g,h;return __generator(this,function(i){switch(i.label){case 0:this.logger.verbose("Fetching user audiences from server"),c={method:"GET",headers:{Accept:"*/*"}},d="".concat(this.url,"?mpid=").concat(a),i.label=1;case 1:return i.trys.push([1,6,,7]),[4/*yield*/,this.userAudienceAPI.upload(c,d)];case 2:return (e=i.sent(),!(200<=e.status&&300>e.status))?[3/*break*/,4]:(this.logger.verbose("User Audiences successfully received"),[4/*yield*/,e.json()]);case 3:f=i.sent(),g={currentAudienceMemberships:null===f||void 0===f?void 0:f.audience_memberships};try{b(g);}catch(a){throw new Error("Error invoking callback on user audience response.")}return [3/*break*/,5];case 4:if(401===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`");else if(403===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`");else// In case there is an HTTP error we did not anticipate.
|
|
719
|
+
throw new Error("Uncaught HTTP Error ".concat(e.status,"."));case 5:return [3/*break*/,7];case 6:return h=i.sent(),this.logger.error("Error retrieving audiences. ".concat(h)),[3/*break*/,7];case 7:return [2/*return*/]}})})},a}();
|
|
720
|
+
|
|
721
|
+
var Messages$2=Constants.Messages,HTTPCodes$2=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,ErrorMessages=Messages$2.ErrorMessages,_Constants$IdentityMe=Constants.IdentityMethods,Identify=_Constants$IdentityMe.Identify,Modify$1=_Constants$IdentityMe.Modify,Login=_Constants$IdentityMe.Login,Logout=_Constants$IdentityMe.Logout;function Identity(t){var r=this;/**
|
|
714
722
|
* Invoke these methods on the mParticle.Identity object.
|
|
715
723
|
* Example: mParticle.Identity.getCurrentUser().
|
|
716
724
|
* @class mParticle.Identity
|
|
@@ -726,48 +734,48 @@ var Messages$2=Constants.Messages,HTTPCodes$2=Constants.HTTPCodes,_Constants$Ide
|
|
|
726
734
|
*/ // send a user identity change request on identify, login, logout, modify when any values change.
|
|
727
735
|
// compare what identities exist vs what is previously was for the specific user if they were in memory before.
|
|
728
736
|
// if it's the first time the user is logging in, send a user identity change request with
|
|
729
|
-
this.idCache=null,this.checkIdentitySwap=function(e,s
|
|
730
|
-
combineUserIdentities:function combineUserIdentities(e,
|
|
731
|
-
!1!==
|
|
737
|
+
this.idCache=null,this.audienceManager=null,this.checkIdentitySwap=function(e,r,s){if(e&&r&&e!==r){var i=t._Persistence.getPersistence();i&&(i.cu=r,i.gs.csm=s,t._Persistence.savePersistence(i));}},this.IdentityRequest={preProcessIdentityRequest:function preProcessIdentityRequest(e,r,s){t.Logger.verbose(Messages$2.InformationMessages.StartingLogEvent+": "+s);var i=t._Helpers.Validators.validateIdentities(e,s);if(!i.valid)return t.Logger.error("ERROR: "+i.error),{valid:!1,error:i.error};if(r&&!t._Helpers.Validators.isFunction(r)){var n="The optional callback must be a function. You tried entering a(n) "+_typeof(r);return t.Logger.error(n),{valid:!1,error:n}}return {valid:!0}},createIdentityRequest:function createIdentityRequest(e,r,s,i,n,a,o){var d={client_sdk:{platform:r,sdk_vendor:s,sdk_version:i},context:a,environment:t._Store.SDKConfig.isDevelopmentMode?"development":"production",request_id:t._Helpers.generateUniqueId(),request_timestamp_ms:new Date().getTime(),previous_mpid:o||null,known_identities:createKnownIdentities(e,n)};return d},createModifyIdentityRequest:function createModifyIdentityRequest(e,r,s,i,n,a){return {client_sdk:{platform:s,sdk_vendor:i,sdk_version:n},context:a,environment:t._Store.SDKConfig.isDevelopmentMode?"development":"production",request_id:t._Helpers.generateUniqueId(),request_timestamp_ms:new Date().getTime(),identity_changes:this.createIdentityChanges(e,r)}},createIdentityChanges:function createIdentityChanges(e,r){var s,i=[];if(r&&t._Helpers.isObject(r)&&e&&t._Helpers.isObject(e))for(s in r)i.push({old_value:e[s]||null,new_value:r[s],identity_type:s});return i},// takes 2 UI objects keyed by name, combines them, returns them keyed by type
|
|
738
|
+
combineUserIdentities:function combineUserIdentities(e,r){var s={},i=t._Helpers.extend(e,r);for(var n in i){var a=Types.IdentityType.getIdentityType(n);// this check removes anything that is not whitelisted as an identity type
|
|
739
|
+
!1!==a&&0<=a&&(s[Types.IdentityType.getIdentityType(n)]=i[n]);}return s},createAliasNetworkRequest:function createAliasNetworkRequest(e){return {request_id:t._Helpers.generateUniqueId(),request_type:"alias",environment:t._Store.SDKConfig.isDevelopmentMode?"development":"production",api_key:t._Store.devToken,data:{destination_mpid:e.destinationMpid,source_mpid:e.sourceMpid,start_unixtime_ms:e.startTime,end_unixtime_ms:e.endTime,scope:e.scope,device_application_stamp:t._Store.deviceId}}},convertAliasToNative:function convertAliasToNative(e){return {DestinationMpid:e.destinationMpid,SourceMpid:e.sourceMpid,StartUnixtimeMs:e.startTime,EndUnixtimeMs:e.endTime}},convertToNative:function convertToNative(e){var t=[];if(e&&e.userIdentities){for(var r in e.userIdentities)e.userIdentities.hasOwnProperty(r)&&t.push({Type:Types.IdentityType.getIdentityType(r),Identity:e.userIdentities[r]});return {UserIdentities:t}}}},this.IdentityAPI={HTTPCodes:HTTPCodes$2,/**
|
|
732
740
|
* Initiate a logout request to the mParticle server
|
|
733
741
|
* @method identify
|
|
734
742
|
* @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
|
|
735
743
|
* @param {Function} [callback] A callback function that is called when the identify request completes
|
|
736
|
-
*/identify:function identify(e,
|
|
744
|
+
*/identify:function identify(e,s){var i,n=t.Identity.getCurrentUser(),a=t._Identity.IdentityRequest.preProcessIdentityRequest(e,s,Identify);if(n&&(i=n.getMPID()),a.valid){var o=t._Identity.IdentityRequest.createIdentityRequest(e,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,t._Store.deviceId,t._Store.context,i);if(t._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)){var d=tryCacheIdentity(o.known_identities,r.idCache,r.parseIdentityResponse,i,s,e,Identify);if(d)return}t._Helpers.canLog()?t._Store.webviewBridgeEnabled?(t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Identify,JSON.stringify(t._Identity.IdentityRequest.convertToNative(e))),t._Helpers.invokeCallback(s,HTTPCodes$2.nativeIdentityRequest,"Identify request sent to native sdk")):t._IdentityAPIClient.sendIdentityRequest(o,Identify,s,e,r.parseIdentityResponse,i,o.known_identities):(t._Helpers.invokeCallback(s,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),t.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else t._Helpers.invokeCallback(s,HTTPCodes$2.validationIssue,a.error),t.Logger.verbose(a);},/**
|
|
737
745
|
* Initiate a logout request to the mParticle server
|
|
738
746
|
* @method logout
|
|
739
747
|
* @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
|
|
740
748
|
* @param {Function} [callback] A callback function that is called when the logout request completes
|
|
741
|
-
*/logout:function logout(e,
|
|
749
|
+
*/logout:function logout(e,s){var i,n=t.Identity.getCurrentUser(),a=t._Identity.IdentityRequest.preProcessIdentityRequest(e,s,Logout);if(n&&(i=n.getMPID()),a.valid){var o,d=t._Identity.IdentityRequest.createIdentityRequest(e,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,t._Store.deviceId,t._Store.context,i);t._Helpers.canLog()?t._Store.webviewBridgeEnabled?(t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Logout,JSON.stringify(t._Identity.IdentityRequest.convertToNative(e))),t._Helpers.invokeCallback(s,HTTPCodes$2.nativeIdentityRequest,"Logout request sent to native sdk")):(t._IdentityAPIClient.sendIdentityRequest(d,Logout,s,e,r.parseIdentityResponse,i),o=t._ServerModel.createEventObject({messageType:Types.MessageType.Profile}),o.ProfileMessageType=Types.ProfileMessageType.Logout,t._Store.activeForwarders.length&&t._Store.activeForwarders.forEach(function(e){e.logOut&&e.logOut(o);})):(t._Helpers.invokeCallback(s,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),t.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else t._Helpers.invokeCallback(s,HTTPCodes$2.validationIssue,a.error),t.Logger.verbose(a);},/**
|
|
742
750
|
* Initiate a login request to the mParticle server
|
|
743
751
|
* @method login
|
|
744
752
|
* @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
|
|
745
753
|
* @param {Function} [callback] A callback function that is called when the login request completes
|
|
746
|
-
*/login:function login(e,
|
|
754
|
+
*/login:function login(e,s){var i,n=t.Identity.getCurrentUser(),a=t._Identity.IdentityRequest.preProcessIdentityRequest(e,s,Login);if(n&&(i=n.getMPID()),a.valid){var o=t._Identity.IdentityRequest.createIdentityRequest(e,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,t._Store.deviceId,t._Store.context,i);if(t._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)){var d=tryCacheIdentity(o.known_identities,r.idCache,r.parseIdentityResponse,i,s,e,Login);if(d)return}t._Helpers.canLog()?t._Store.webviewBridgeEnabled?(t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Login,JSON.stringify(t._Identity.IdentityRequest.convertToNative(e))),t._Helpers.invokeCallback(s,HTTPCodes$2.nativeIdentityRequest,"Login request sent to native sdk")):t._IdentityAPIClient.sendIdentityRequest(o,Login,s,e,r.parseIdentityResponse,i,o.known_identities):(t._Helpers.invokeCallback(s,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),t.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else t._Helpers.invokeCallback(s,HTTPCodes$2.validationIssue,a.error),t.Logger.verbose(a);},/**
|
|
747
755
|
* Initiate a modify request to the mParticle server
|
|
748
756
|
* @method modify
|
|
749
757
|
* @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
|
|
750
758
|
* @param {Function} [callback] A callback function that is called when the modify request completes
|
|
751
|
-
*/modify:function modify(e,
|
|
759
|
+
*/modify:function modify(e,s){var i,n=t.Identity.getCurrentUser(),a=t._Identity.IdentityRequest.preProcessIdentityRequest(e,s,Modify$1);n&&(i=n.getMPID());var o=e&&e.userIdentities?e.userIdentities:{};if(a.valid){var d=t._Identity.IdentityRequest.createModifyIdentityRequest(n?n.getUserIdentities().userIdentities:{},o,Constants.platform,Constants.sdkVendor,Constants.sdkVersion,t._Store.context);t._Helpers.canLog()?t._Store.webviewBridgeEnabled?(t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Modify,JSON.stringify(t._Identity.IdentityRequest.convertToNative(e))),t._Helpers.invokeCallback(s,HTTPCodes$2.nativeIdentityRequest,"Modify request sent to native sdk")):t._IdentityAPIClient.sendIdentityRequest(d,Modify$1,s,e,r.parseIdentityResponse,i,d.known_identities):(t._Helpers.invokeCallback(s,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonLogEvent),t.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent));}else t._Helpers.invokeCallback(s,HTTPCodes$2.validationIssue,a.error),t.Logger.verbose(a);},/**
|
|
752
760
|
* Returns a user object with methods to interact with the current user
|
|
753
761
|
* @method getCurrentUser
|
|
754
762
|
* @return {Object} the current user object
|
|
755
|
-
*/getCurrentUser:function getCurrentUser(){var e;return t._Store?(e=t._Store.mpid,e?(e=t._Store.mpid.slice(),
|
|
763
|
+
*/getCurrentUser:function getCurrentUser(){var e;return t._Store?(e=t._Store.mpid,e?(e=t._Store.mpid.slice(),r.mParticleUser(e,t._Store.isLoggedIn)):t._Store.webviewBridgeEnabled?r.mParticleUser():null):null},/**
|
|
756
764
|
* Returns a the user object associated with the mpid parameter or 'null' if no such
|
|
757
765
|
* user exists
|
|
758
766
|
* @method getUser
|
|
759
767
|
* @param {String} mpid of the desired user
|
|
760
768
|
* @return {Object} the user for mpid
|
|
761
|
-
*/getUser:function getUser(e){var
|
|
769
|
+
*/getUser:function getUser(e){var s=t._Persistence.getPersistence();return s?s[e]&&!Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(e)?r.mParticleUser(e):null:null},/**
|
|
762
770
|
* Returns all users, including the current user and all previous users that are stored on the device.
|
|
763
771
|
* @method getUsers
|
|
764
772
|
* @return {Array} array of users
|
|
765
|
-
*/getUsers:function getUsers(){var e=t._Persistence.getPersistence(),
|
|
773
|
+
*/getUsers:function getUsers(){var e=t._Persistence.getPersistence(),s=[];if(e)for(var i in e)Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(i)||s.push(r.mParticleUser(i));return s.sort(function(e,t){var r=e.getLastSeenTime()||0,s=t.getLastSeenTime()||0;return r>s?-1:1}),s},/**
|
|
766
774
|
* Initiate an alias request to the mParticle server
|
|
767
775
|
* @method aliasUsers
|
|
768
776
|
* @param {Object} aliasRequest object representing an AliasRequest
|
|
769
777
|
* @param {Function} [callback] A callback function that is called when the aliasUsers request completes
|
|
770
|
-
*/aliasUsers:function aliasUsers(e,
|
|
778
|
+
*/aliasUsers:function aliasUsers(e,r){var s;if(e.destinationMpid&&e.sourceMpid||(s=Messages$2.ValidationMessages.AliasMissingMpid),e.destinationMpid===e.sourceMpid&&(s=Messages$2.ValidationMessages.AliasNonUniqueMpid),e.startTime&&e.endTime||(s=Messages$2.ValidationMessages.AliasMissingTime),e.startTime>e.endTime&&(s=Messages$2.ValidationMessages.AliasStartBeforeEndTime),s)return t.Logger.warning(s),void t._Helpers.invokeAliasCallback(r,HTTPCodes$2.validationIssue,s);if(!t._Helpers.canLog())t._Helpers.invokeAliasCallback(r,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonAliasUsers),t.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers);else if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias,JSON.stringify(t._Identity.IdentityRequest.convertAliasToNative(e))),t._Helpers.invokeAliasCallback(r,HTTPCodes$2.nativeIdentityRequest,"Alias request sent to native sdk");else {t.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest+": "+e.sourceMpid+" -> "+e.destinationMpid);var i=t._Identity.IdentityRequest.createAliasNetworkRequest(e);t._IdentityAPIClient.sendAliasRequest(i,r);}},/**
|
|
771
779
|
Create a default AliasRequest for 2 MParticleUsers. This will construct the request
|
|
772
780
|
using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime.
|
|
773
781
|
|
|
@@ -781,12 +789,12 @@ combineUserIdentities:function combineUserIdentities(e,s){var r={},i=t._Helpers.
|
|
|
781
789
|
In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit,
|
|
782
790
|
after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers()
|
|
783
791
|
validation that the startTime must be less than the endTime
|
|
784
|
-
*/createAliasRequest:function createAliasRequest(e,
|
|
785
|
-
return
|
|
792
|
+
*/createAliasRequest:function createAliasRequest(e,r){try{if(!r||!e)return t.Logger.error("'destinationUser' and 'sourceUser' must both be present"),null;var s=e.getFirstSeenTime();s||t.Identity.getUsers().forEach(function(e){e.getFirstSeenTime()&&(!s||e.getFirstSeenTime()<s)&&(s=e.getFirstSeenTime());});var i=new Date().getTime()-1e3*(60*(60*(24*t._Store.SDKConfig.aliasMaxWindow))),n=e.getLastSeenTime()||new Date().getTime();//if the startTime is greater than $maxAliasWindow ago, adjust the startTime to the earliest allowed
|
|
793
|
+
return s<i&&(s=i,n<s&&t.Logger.warning("Source User has not been seen in the last "+t._Store.SDKConfig.maxAliasWindow+" days, Alias Request will likely fail")),{destinationMpid:r.getMPID(),sourceMpid:e.getMPID(),startTime:s,endTime:n}}catch(r){return t.Logger.error("There was a problem with creating an alias request: "+r),null}}},this.mParticleUser=function(e,r){var s=this;return {/**
|
|
786
794
|
* Get user identities for current user
|
|
787
795
|
* @method getUserIdentities
|
|
788
796
|
* @return {Object} an object with userIdentities as its key
|
|
789
|
-
*/getUserIdentities:function getUserIdentities(){var
|
|
797
|
+
*/getUserIdentities:function getUserIdentities(){var r={},s=t._Persistence.getUserIdentities(e);for(var i in s)s.hasOwnProperty(i)&&(r[Types.IdentityType.getIdentityName(t._Helpers.parseNumber(i))]=s[i]);return {userIdentities:r}},/**
|
|
790
798
|
* Get the MPID of the current user
|
|
791
799
|
* @method getMPID
|
|
792
800
|
* @return {String} the current user MPID as a string
|
|
@@ -803,38 +811,38 @@ return r<i&&(r=i,n<r&&t.Logger.warning("Source User has not been seen in the las
|
|
|
803
811
|
* @method setUserAttribute
|
|
804
812
|
* @param {String} key
|
|
805
813
|
* @param {String} value
|
|
806
|
-
*/setUserAttribute:function setUserAttribute(
|
|
814
|
+
*/setUserAttribute:function setUserAttribute(r,i){var n,a,o,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(r))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttribute,JSON.stringify({key:r,value:i}));else {n=t._Persistence.getPersistence(),a=this.getAllUserAttributes();var g=t._Helpers.findKeyInObject(a,r);g?(d=!1,o=a[g],delete a[g]):d=!0,a[r]=i,n&&n[e]&&(n[e].ua=a,t._Persistence.savePersistence(n,e)),s.sendUserAttributeChangeEvent(r,i,o,d,!1,this),t._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.handleForwarderUserAttributes("setUserAttribute",r,i);}}},/**
|
|
807
815
|
* Set multiple user attributes
|
|
808
816
|
* @method setUserAttributes
|
|
809
817
|
* @param {Object} user attribute object with keys of the attribute type, and value of the attribute value
|
|
810
|
-
*/setUserAttributes:function setUserAttributes(e){if(t._SessionManager.resetSessionTimer(),!t._Helpers.isObject(e))t.Logger.error("Must pass an object into setUserAttributes. You passed a "+_typeof(e));else if(t._Helpers.canLog())for(var
|
|
818
|
+
*/setUserAttributes:function setUserAttributes(e){if(t._SessionManager.resetSessionTimer(),!t._Helpers.isObject(e))t.Logger.error("Must pass an object into setUserAttributes. You passed a "+_typeof(e));else if(t._Helpers.canLog())for(var r in e)e.hasOwnProperty(r)&&this.setUserAttribute(r,e[r]);},/**
|
|
811
819
|
* Removes a specific user attribute
|
|
812
820
|
* @method removeUserAttribute
|
|
813
821
|
* @param {String} key
|
|
814
|
-
*/removeUserAttribute:function removeUserAttribute(
|
|
822
|
+
*/removeUserAttribute:function removeUserAttribute(r){var i,n;if(t._SessionManager.resetSessionTimer(),!t._Helpers.Validators.isValidKeyValue(r))return void t.Logger.error(Messages$2.ErrorMessages.BadKey);if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveUserAttribute,JSON.stringify({key:r,value:null}));else {i=t._Persistence.getPersistence(),n=this.getAllUserAttributes();var a=t._Helpers.findKeyInObject(n,r);a&&(r=a);var o=n[r]?n[r].toString():null;delete n[r],i&&i[e]&&(i[e].ua=n,t._Persistence.savePersistence(i,e)),s.sendUserAttributeChangeEvent(r,null,o,!1,!0,this),t._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.handleForwarderUserAttributes("removeUserAttribute",r,null);}},/**
|
|
815
823
|
* Sets a list of user attributes
|
|
816
824
|
* @method setUserAttributeList
|
|
817
825
|
* @param {String} key
|
|
818
826
|
* @param {Array} value an array of values
|
|
819
|
-
*/setUserAttributeList:function setUserAttributeList(
|
|
827
|
+
*/setUserAttributeList:function setUserAttributeList(r,n){var a,o,d,g,l;if(t._SessionManager.resetSessionTimer(),!t._Helpers.Validators.isValidKeyValue(r))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:r,value:u}));else {a=t._Persistence.getPersistence(),o=this.getAllUserAttributes();var c=t._Helpers.findKeyInObject(o,r);// If the new attributeList length is different previous, then there is a change event.
|
|
820
828
|
// Loop through new attributes list, see if they are all in the same index as previous user attributes list
|
|
821
829
|
// If there are any changes, break, and immediately send a userAttributeChangeEvent with full array as a value
|
|
822
|
-
if(
|
|
830
|
+
if(c?(g=!1,d=o[c],delete o[c]):g=!0,o[r]=u,a&&a[e]&&(a[e].ua=o,t._Persistence.savePersistence(a,e)),!d||!Array.isArray(d))l=!0;else if(n.length!==d.length)l=!0;else for(var p=0;p<n.length;p++)if(d[p]!==n[p]){l=!0;break}l&&s.sendUserAttributeChangeEvent(r,n,d,g,!1,this),t._Forwarders.initForwarders(s.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),t._Forwarders.handleForwarderUserAttributes("setUserAttribute",r,u);}},/**
|
|
823
831
|
* Removes all user attributes
|
|
824
832
|
* @method removeAllUserAttributes
|
|
825
|
-
*/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(
|
|
833
|
+
*/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(s.IdentityAPI.getCurrentUser().getUserIdentities(),t._APIClient.prepareForwardingStats),e)for(var r in e)e.hasOwnProperty(r)&&t._Forwarders.handleForwarderUserAttributes("removeUserAttribute",r,null),this.removeUserAttribute(r);},/**
|
|
826
834
|
* Returns all user attribute keys that have values that are arrays
|
|
827
835
|
* @method getUserAttributesLists
|
|
828
836
|
* @return {Object} an object of only keys with array values. Example: { attr1: [1, 2, 3], attr2: ['a', 'b', 'c'] }
|
|
829
|
-
*/getUserAttributesLists:function getUserAttributesLists(){var e,t={};for(var
|
|
837
|
+
*/getUserAttributesLists:function getUserAttributesLists(){var e,t={};for(var r in e=this.getAllUserAttributes(),e)e.hasOwnProperty(r)&&Array.isArray(e[r])&&(t[r]=e[r].slice());return t},/**
|
|
830
838
|
* Returns all user attributes
|
|
831
839
|
* @method getAllUserAttributes
|
|
832
840
|
* @return {Object} an object of all user attributes. Example: { attr1: 'value1', attr2: ['a', 'b', 'c'] }
|
|
833
|
-
*/getAllUserAttributes:function getAllUserAttributes(){var
|
|
841
|
+
*/getAllUserAttributes:function getAllUserAttributes(){var r={},s=t._Persistence.getAllUserAttributes(e);if(s)for(var i in s)s.hasOwnProperty(i)&&(r[i]=Array.isArray(s[i])?s[i].slice():s[i]);return r},/**
|
|
834
842
|
* Returns the cart object for the current user
|
|
835
843
|
* @method getCart
|
|
836
844
|
* @return a cart object
|
|
837
|
-
*/getCart:function getCart(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart() will be removed in future releases"),
|
|
845
|
+
*/getCart:function getCart(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart() will be removed in future releases"),s.mParticleUserCart(e)},/**
|
|
838
846
|
* Returns the Consent State stored locally for this user.
|
|
839
847
|
* @method getConsentState
|
|
840
848
|
* @return a ConsentState object
|
|
@@ -842,28 +850,33 @@ if(p?(g=!1,d=a[p],delete a[p]):g=!0,a[s]=u,o&&o[e]&&(o[e].ua=a,t._Persistence.sa
|
|
|
842
850
|
* Sets the Consent State stored locally for this user.
|
|
843
851
|
* @method setConsentState
|
|
844
852
|
* @param {Object} consent state
|
|
845
|
-
*/setConsentState:function setConsentState(
|
|
853
|
+
*/setConsentState:function setConsentState(r){t._Persistence.saveUserConsentStateToCookies(e,r),t._Forwarders.initForwarders(this.getUserIdentities().userIdentities,t._APIClient.prepareForwardingStats),t._CookieSyncManager.attemptCookieSync(null,this.getMPID());},isLoggedIn:function isLoggedIn(){return r},getLastSeenTime:function getLastSeenTime(){return t._Persistence.getLastSeenTime(e)},getFirstSeenTime:function getFirstSeenTime(){return t._Persistence.getFirstSeenTime(e)},/**
|
|
854
|
+
* Get user audiences
|
|
855
|
+
* @method getuserAudiences
|
|
856
|
+
* @param {Function} [callback] A callback function that is invoked when the user audience request completes
|
|
857
|
+
*/getUserAudiences:function getUserAudiences(r){// user audience API is feature flagged
|
|
858
|
+
return t._Helpers.getFeatureFlag(FeatureFlags.AudienceAPI)?void(null===s.audienceManager&&(s.audienceManager=new AudienceManager(t._Store.SDKConfig.userAudienceUrl,t._Store.devToken,t.Logger,e)),s.audienceManager.sendGetUserAudienceRequest(e,r)):void t.Logger.error(ErrorMessages.AudienceAPINotEnabled)}}},this.mParticleUserCart=function(e){return {/**
|
|
846
859
|
* Adds a cart product to the user cart
|
|
847
860
|
* @method add
|
|
848
861
|
* @param {Object} product the product
|
|
849
862
|
* @param {Boolean} [logEvent] a boolean to log adding of the cart object. If blank, no logging occurs.
|
|
850
863
|
* @deprecated
|
|
851
|
-
*/add:function add(s
|
|
864
|
+
*/add:function add(r,s){t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().add() will be removed in future releases");var i,n,a;if(a=Array.isArray(r)?r.slice():[r],a.forEach(function(e){e.Attributes=t._Helpers.sanitizeAttributes(e.Attributes);}),t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.AddToCart,JSON.stringify(a));else {t._SessionManager.resetSessionTimer(),n=t._Persistence.getUserProductsFromLS(e),n=n.concat(a),!0===s&&t._Events.logProductActionEvent(Types.ProductActionType.AddToCart,a);n.length>t._Store.SDKConfig.maxProducts&&(t.Logger.verbose("The cart contains "+n.length+" items. Only "+t._Store.SDKConfig.maxProducts+" can currently be saved in cookies."),n=n.slice(-t._Store.SDKConfig.maxProducts)),i=t._Persistence.getAllUserProductsFromLS(),i[e].cp=n,t._Persistence.setCartProducts(i);}},/**
|
|
852
865
|
* Removes a cart product from the current user cart
|
|
853
866
|
* @method remove
|
|
854
867
|
* @param {Object} product the product
|
|
855
868
|
* @param {Boolean} [logEvent] a boolean to log adding of the cart object. If blank, no logging occurs.
|
|
856
869
|
* @deprecated
|
|
857
|
-
*/remove:function remove(s
|
|
870
|
+
*/remove:function remove(r,s){t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().remove() will be removed in future releases");var i,n,a=-1,o=null;if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveFromCart,JSON.stringify(r));else {t._SessionManager.resetSessionTimer(),n=t._Persistence.getUserProductsFromLS(e),n&&(n.forEach(function(e,t){e.Sku===r.Sku&&(a=t,o=e);}),-1<a&&(n.splice(a,1),!0===s&&t._Events.logProductActionEvent(Types.ProductActionType.RemoveFromCart,o)));i=t._Persistence.getAllUserProductsFromLS(),i[e].cp=n,t._Persistence.setCartProducts(i);}},/**
|
|
858
871
|
* Clears the user's cart
|
|
859
872
|
* @method clear
|
|
860
873
|
* @deprecated
|
|
861
|
-
*/clear:function clear(){t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().clear() will be removed in future releases");var
|
|
874
|
+
*/clear:function clear(){t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().clear() will be removed in future releases");var r;t._Store.webviewBridgeEnabled?t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.ClearCart):(t._SessionManager.resetSessionTimer(),r=t._Persistence.getAllUserProductsFromLS(),r&&r[e]&&r[e].cp&&(r[e].cp=[],r[e].cp=[],t._Persistence.setCartProducts(r)));},/**
|
|
862
875
|
* Returns all cart products
|
|
863
876
|
* @method getCartProducts
|
|
864
877
|
* @return {Array} array of cart products
|
|
865
878
|
* @deprecated
|
|
866
|
-
*/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(
|
|
879
|
+
*/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(s,i,n,a,o,d,g){var l,u,c,p,_=t.Identity.getUser(i),I={},y=_?_.getUserIdentities().userIdentities:{},v=t._Helpers.extend({},y);t._Store.identityCallInFlight=!1;try{if(t.Logger.verbose("Parsing \""+o+"\" identity response from server"),s.responseText&&(c=JSON.parse(s.responseText),c.hasOwnProperty("is_logged_in")&&(t._Store.isLoggedIn=c.is_logged_in)),(!_||_.getMPID()&&c.mpid&&c.mpid!==_.getMPID())&&(t._Store.mpid=c.mpid,_&&t._Persistence.setLastSeenTime(i),!t._Persistence.getFirstSeenTime(c.mpid)&&(u=!0),t._Persistence.setFirstSeenTime(c.mpid)),200===s.status){if(t._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)&&cacheOrClearIdCache(o,d,r.idCache,s,g),o===Modify$1)I=t._Identity.IdentityRequest.combineUserIdentities(y,a.userIdentities),t._Persistence.saveUserIdentitiesToPersistence(i,I);else {var m=r.IdentityAPI.getUser(c.mpid),S=m?m.getUserIdentities().userIdentities:{},P=t._Helpers.extend({},S);t.Logger.verbose("Successfully parsed Identity Response"),o===Identify&&_&&c.mpid===_.getMPID()&&t._Persistence.setFirstSeenTime(c.mpid),p=t._Store.currentSessionMPIDs.indexOf(c.mpid),t._Store.sessionId&&c.mpid&&i!==c.mpid&&0>p&&t._Store.currentSessionMPIDs.push(c.mpid),-1<p&&(t._Store.currentSessionMPIDs=t._Store.currentSessionMPIDs.slice(0,p).concat(t._Store.currentSessionMPIDs.slice(p+1,t._Store.currentSessionMPIDs.length)),t._Store.currentSessionMPIDs.push(c.mpid)),t._CookieSyncManager.attemptCookieSync(i,c.mpid,u),r.checkIdentitySwap(i,c.mpid,t._Store.currentSessionMPIDs),a&&a.userIdentities&&Object.keys(a.userIdentities).length&&(I=r.IdentityRequest.combineUserIdentities(S,a.userIdentities)),t._Persistence.saveUserIdentitiesToPersistence(c.mpid,I),t._Persistence.update(),t._Persistence.findPrevCookiesBasedOnUI(a),t._Store.context=c.context||t._Store.context;}if(l=t.Identity.getCurrentUser(),a&&a.onUserAlias&&t._Helpers.Validators.isFunction(a.onUserAlias))try{t.Logger.warning("Deprecated function onUserAlias will be removed in future releases"),a.onUserAlias(_,l);}catch(r){t.Logger.error("There was an error with your onUserAlias function - "+r);}var b=t._Persistence.getPersistence();l&&(t._Persistence.storeDataInMemory(b,l.getMPID()),(!_||l.getMPID()!==_.getMPID()||_.isLoggedIn()!==l.isLoggedIn())&&t._Forwarders.initForwarders(l.getUserIdentities().userIdentities,t._APIClient.prepareForwardingStats),t._Forwarders.setForwarderUserIdentities(l.getUserIdentities().userIdentities),t._Forwarders.setForwarderOnIdentityComplete(l,o),t._Forwarders.setForwarderOnUserIdentified(l));var A={};for(var k in I)A[Types.IdentityType.getIdentityName(t._Helpers.parseNumber(k))]=I[k];r.sendUserIdentityChangeEvent(A,o,c.mpid,o===Modify$1?v:P);}n?0===s.status?t._Helpers.invokeCallback(n,HTTPCodes$2.noHttpCoverage,c||null,l):t._Helpers.invokeCallback(n,s.status,c||null,l):c&&c.errors&&c.errors.length&&t.Logger.error("Received HTTP response code of "+s.status+" - "+c.errors[0].message),t._APIClient.processQueuedEvents();}catch(r){n&&t._Helpers.invokeCallback(n,s.status,c||null),t.Logger.error("Error parsing JSON response from Identity server: "+r);}},this.sendUserIdentityChangeEvent=function(e,s,i,n){var a,o;if(i||s===Modify$1)for(var d in a=this.IdentityAPI.getUser(i),e)if(n[d]!==e[d]){var g=!n[d];o=r.createUserIdentityChange(d,e[d],n[d],g,a),t._APIClient.sendEventToServer(o);}},this.createUserIdentityChange=function(e,r,s,i,n){var a;return a=t._ServerModel.createEventObject({messageType:Types.MessageType.UserIdentityChange,userIdentityChanges:{New:{IdentityType:e,Identity:r,CreatedThisBatch:i},Old:{IdentityType:e,Identity:s,CreatedThisBatch:!1}},userInMemory:n}),a},this.sendUserAttributeChangeEvent=function(e,s,i,n,a,o){var d=r.createUserAttributeChange(e,s,i,n,a,o);d&&t._APIClient.sendEventToServer(d);},this.createUserAttributeChange=function(e,r,s,i,n,a){"undefined"==typeof s&&(s=null);var o;return r!==s&&(o=t._ServerModel.createEventObject({messageType:Types.MessageType.UserAttributeChange,userAttributeChanges:{UserAttributeName:e,New:r,Old:s,Deleted:n,IsNewAttribute:i}},a)),o};}
|
|
867
880
|
|
|
868
881
|
var CCPAPurpose=Constants.CCPAPurpose;function Consent(a){var b=this;// this function is called when consent is required to
|
|
869
882
|
// determine if a cookie sync should happen, or a
|