@mparticle/web-sdk 2.54.0 → 2.55.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.
@@ -15,7 +15,7 @@ map:function map(a,b){var c,d,e;if(null===this)throw new TypeError(" this is nul
15
15
  filter:function filter(a/*, thisArg*/){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g);}return d},// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
16
16
  isArray:function isArray(a){return "[object Array]"===Object.prototype.toString.call(a)},Base64:Base64$1};
17
17
 
18
- var version = "2.54.0";
18
+ var version = "2.55.0";
19
19
 
20
20
  var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
21
21
  },DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},// These are the paths that are used to construct the CNAME urls
@@ -580,7 +580,7 @@ document.addEventListener("visibilitychange",function(){return a.handleVisibilit
580
580
 
581
581
  function createSDKConfig(a){// TODO: Refactor to create a default config object
582
582
  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
583
- function Store(a,b,c){var d=this,e=b._Helpers.createMainStorageName,f=b._NativeSdkHelpers.isWebviewEnabled,g={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},// Placeholder for in-memory persistence model
583
+ function Store(a,b,c){var d=this,e=b._Helpers.createMainStorageName,f=b._NativeSdkHelpers.isWebviewEnabled,g={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,identifyRequestCount:0,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},// Placeholder for in-memory persistence model
584
584
  persistenceData:{gs:{}}};for(var h in g)this[h]=g[h];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&returnConvertedBoolean(a.isDevelopmentMode);var i=processBaseUrls(a,this.SDKConfig.flags,c);for(var j in i)this.SDKConfig[j]=i[j];if(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 k=a.identityCallback;b._Helpers.Validators.isFunction(k)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof$1(k)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var l=a.dataPlan;l.planId&&(isDataPlanSlug(l.planId)?this.SDKConfig.dataPlan.PlanId=l.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),l.planVersion&&(isNumber(l.planVersion)?this.SDKConfig.dataPlan.PlanVersion=l.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var m=a.dataPlanOptions;m.hasOwnProperty("dataPlanVersion")&&m.hasOwnProperty("blockUserAttributes")&&m.hasOwnProperty("blockEventAttributes")&&m.hasOwnProperty("blockEvents")&&m.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this._getFromPersistence=function(a,b){return a?(d.syncPersistenceData(),d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a][b]?d.persistenceData[a][b]:null):null},this._setPersistence=function(a,c,e){var f;a&&(d.syncPersistenceData(),d.persistenceData&&(d.persistenceData[a]?d.persistenceData[a][c]=e:d.persistenceData[a]=(f={},f[c]=e,f),isObject(d.persistenceData[a][c])&&isEmpty(d.persistenceData[a][c])&&delete d.persistenceData[a][c],b._Persistence.savePersistence(d.persistenceData)));},this.hasInvalidIdentifyRequest=function(){var a=d.SDKConfig.identifyRequest;return isObject(a)&&isObject(a.userIdentities)&&isEmpty(a.userIdentities)||!a},this.getConsentState=function(a){var c=b._Consent.ConsentSerialization.fromMinifiedJsonObject,e=d._getFromPersistence(a,"con");return isEmpty(e)?null:c(e)},this.setConsentState=function(a,c){var e=b._Consent.ConsentSerialization.toMinifiedJsonObject;// If ConsentState is null, we assume the intent is to clear out the consent state
585
585
  (c||null===c)&&d._setPersistence(a,"con",e(c));},this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.getFirstSeenTime=function(a){return d._getFromPersistence(a,"fst")},this.setFirstSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"fst",c);}},this.getLastSeenTime=function(a){if(!a)return null;// https://go.mparticle.com/work/SQDSDKS-6315
586
586
  var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d._getFromPersistence(a,"lst")},this.setLastSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"lst",c);}},this.getLocalSessionAttributes=function(){return d.localSessionAttributes||{}},this.setLocalSessionAttribute=function(a,c){var e;d.localSessionAttributes[a]=c,d.persistenceData.gs.lsa=__assign(__assign({},d.persistenceData.gs.lsa||{}),(e={},e[a]=c,e)),b._Persistence.savePersistence(d.persistenceData);},this.syncPersistenceData=function(){var a=b._Persistence.getPersistence();d.persistenceData=b._Helpers.extend({},d.persistenceData,a);},this.getUserAttributes=function(a){return d._getFromPersistence(a,"ua")||{}},this.setUserAttributes=function(a,b){return d._setPersistence(a,"ua",b)},this.getUserIdentities=function(a){return d._getFromPersistence(a,"ui")||{}},this.setUserIdentities=function(a,b){d._setPersistence(a,"ui",b);},this.addMpidToSessionHistory=function(a,b){var c=d.currentSessionMPIDs.indexOf(a);return a&&b!==a&&0>c?void d.currentSessionMPIDs.push(a):void(0<=c&&(d.currentSessionMPIDs=moveElementToEnd(d.currentSessionMPIDs,c)))},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionStartDate=null,d.sessionAttributes={},d.localSessionAttributes={},b._Persistence.update();},this.processConfig=function(a){var g=a.workspaceToken,h=a.requiredWebviewBridgeName;// We should reprocess the flags and baseUrls in case they have changed when we request an updated config
@@ -1296,7 +1296,7 @@ return a._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===d.audie
1296
1296
  * @deprecated
1297
1297
  */getCartProducts:function getCartProducts(){return a.Logger.warning(generateDeprecationMessage("Identity.getCurrentUser().getCart().getCartProducts()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")),[]}}},this.parseIdentityResponse=function(b,d,f,g,h,i,j){var k,l,m,n=a.Identity.getUser(d),o=n?n.getMPID():null,p=n?n.getUserIdentities().userIdentities:{},q={};a._Store.identityCallInFlight=!1;try{var r,s,t;if(a.Logger.verbose("Parsing \""+h+"\" identity response from server"),l=null!==(r=b.responseText)&&void 0!==r?r:null,a._Store.isLoggedIn=(null===(s=l)||void 0===s?void 0:s.is_logged_in)||!1,hasMPIDChanged(n,l)&&(a._Store.mpid=l.mpid,n&&a._Persistence.setLastSeenTime(d),k=!a._Persistence.getFirstSeenTime(l.mpid),a._Persistence.setFirstSeenTime(l.mpid)),b.status===HTTP_OK){c(CacheIdentity)&&cacheOrClearIdCache(h,i,e.idCache,b,j);var u=e.IdentityAPI.getUser(l.mpid),v=u?u.getUserIdentities().userIdentities:{};h===Modify$1?(q=a._Identity.IdentityRequest.combineUserIdentities(p,g.userIdentities),a._Store.setUserIdentities(d,q)):(h===Identify&&n&&l.mpid===o&&a._Persistence.setFirstSeenTime(l.mpid),a._Store.addMpidToSessionHistory(l.mpid,d),a._CookieSyncManager.attemptCookieSync(l.mpid,k),a._Persistence.swapCurrentUser(d,l.mpid,a._Store.currentSessionMPIDs),g&&!isEmpty(g.userIdentities)&&(q=e.IdentityRequest.combineUserIdentities(v,g.userIdentities)),a._Store.setUserIdentities(l.mpid,q),a._Persistence.update(),a._Store.syncPersistenceData(),a._Persistence.findPrevCookiesBasedOnUI(g),a._Store.context=l.context||a._Store.context),m=a.Identity.getCurrentUser(),tryOnUserAlias(n,m,g,a.Logger);var w=a._Persistence.getPersistence();m&&(a._Persistence.storeDataInMemory(w,m.getMPID()),e.reinitForwardersOnUserChange(n,m),e.setForwarderCallbacks(m,h));var x=IdentityType.getNewIdentitiesByName(q),y=h===Modify$1?p:v;// https://go.mparticle.com/work/SQDSDKS-6501
1298
1298
  e.sendUserIdentityChangeEvent(x,h,l.mpid,y);}if(f){var z=0===b.status?HTTPCodes$2.noHttpCoverage:b.status;a._Helpers.invokeCallback(f,z,l||null,m);}else l&&!isEmpty(l.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
1299
- a.Logger.error("Received HTTP response code of "+b.status+" - "+l.errors[0].message);a.Logger.verbose("Successfully parsed Identity Response"),null===(t=a._APIClient)||void 0===t||t.processQueuedEvents();}catch(c){f&&a._Helpers.invokeCallback(f,b.status,l||null),a.Logger.error("Error parsing JSON response from Identity server: "+c);}a._Store.isInitialized=!0,a._RoktManager.isReady()&&(a._RoktManager.currentUser=a.Identity.getCurrentUser()),a._preInit.readyQueue=processReadyQueue(a._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(b,c,d,f){if(d||c===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1299
+ a.Logger.error("Received HTTP response code of "+b.status+" - "+l.errors[0].message);a.Logger.verbose("Successfully parsed Identity Response"),null===(t=a._APIClient)||void 0===t||t.processQueuedEvents();}catch(c){f&&a._Helpers.invokeCallback(f,b.status,l||null),a.Logger.error("Error parsing JSON response from Identity server: "+c);}a._Store.isInitialized=!0,a._RoktManager.onIdentityComplete(),a._preInit.readyQueue=processReadyQueue(a._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(b,c,d,f){if(d||c===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1300
1300
  {// https://go.mparticle.com/work/SQDSDKS-6354
1301
1301
  var g=this.IdentityAPI.getUser(d);for(var h in b)// Verifies a change actually happened
1302
1302
  if(f[h]!==b[h]){var i,j=!f[h],k=e.createUserIdentityChange(h,b[h],f[h],j,g);// If a new identity type was introduced when the identity changes
@@ -1400,7 +1400,7 @@ return !("boolean"==typeof b&&b)&&"object"===_typeof$1(b)&&!0!==b[a];// When "Bl
1400
1400
  var buildUrl=function(a,b,c,d){var e=d?"1":"0",f=["env=".concat(e)],g=c||{},h=g.planId,i=g.planVersion;return h&&f.push("plan_id=".concat(h)),i&&f.push("plan_version=".concat(i)),"".concat(a+b+"/config","?").concat(f.join("&"))};function ConfigAPIClient(a,b,c){var d=this,e="https://"+c._Store.SDKConfig.configUrl,f=b.isDevelopmentMode,g=b.dataPlan,h=buildUrl(e,a,g,f),i=window.fetch?new FetchUploader(h):new XHRUploader(h);this.getSDKConfiguration=function(){return __awaiter(d,void 0,void 0,function(){var a,d,e,f,h,j,k;return __generator(this,function(l){switch(l.label){case 0:d={method:"get",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"text/plain;charset=UTF-8"},body:null},l.label=1;case 1:return l.trys.push([1,6,,7]),[4/*yield*/,i.upload(d)];case 2:return (e=l.sent(),200!==e.status)?[3/*break*/,5]:(null===(h=null===c||void 0===c?void 0:c.Logger)||void 0===h?void 0:h.verbose("Successfully received configuration from server"),e.json?[4/*yield*/,e.json()]:[3/*break*/,4]);case 3:return a=l.sent(),[2/*return*/,a];case 4:return f=e,a=JSON.parse(f.responseText),[2/*return*/,a];case 5:return null===(j=null===c||void 0===c?void 0:c.Logger)||void 0===j?void 0:j.verbose("Issue with receiving configuration from server, received HTTP Code of "+e.statusText),[3/*break*/,7];case 6:return l.sent(),null===(k=null===c||void 0===c?void 0:c.Logger)||void 0===k?void 0:k.error("Error getting forwarder configuration from mParticle servers."),[3/*break*/,7];case 7:// Returns the original config object if we cannot retrieve the remote config
1401
1401
  return [2/*return*/,b]}})})};}
1402
1402
 
1403
- var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){return __awaiter(this,void 0,void 0,function(){var i,j,k,l,m,n,o,p,q,r,s,t,u,v,u;return __generator(this,function(w){switch(w.label){case 0:if(i=a._Helpers.invokeCallback,j=a.Logger,j.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return j.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(j.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return i(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];k=g||null,l=this.getUploadUrl(c,g),m=window.fetch?new FetchUploader(l):new XHRUploader(l),n={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,w.label=1;case 1:return w.trys.push([1,9,,10]),[4/*yield*/,m.upload(n)];case 2:return o=w.sent(),p=void 0,q=void 0,r=o.status,r===HTTP_ACCEPTED?[3/*break*/,3]:r===HTTP_OK?[3/*break*/,3]:r===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return o.json?[4/*yield*/,o.json()]:[3/*break*/,5];case 4:return s=w.sent(),p=this.getIdentityResponseFromFetch(o,s),[3/*break*/,6];case 5:p=this.getIdentityResponseFromXHR(o),w.label=6;case 6:return p.status===HTTP_BAD_REQUEST?(t=p.responseText,q="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+p.status,(null===t||void 0===t?void 0:t.Errors)&&(u=t.Errors.map(function(a){return a.message}).join(", "),q+=" - "+u)):(q="Received Identity Response from server: ",q+=JSON.stringify(p.responseText)),[3/*break*/,8];case 7:throw new Error("Received HTTP Code of "+o.status);case 8:return a._Store.identityCallInFlight=!1,j.verbose(q),f(p,k,d,e,c,h,!1),[3/*break*/,10];case 9:return v=w.sent(),a._Store.identityCallInFlight=!1,u=v.message||v.toString(),j.error("Error sending identity request to servers - "+u),i(d,HTTPCodes$1.noHttpCoverage,u),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};}
1403
+ var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k;return __awaiter(this,void 0,void 0,function(){var l,m,n,o,p,q,r,s,t,u,v,w,x,y,l,z,l,y;return __generator(this,function(A){switch(A.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,l=a._Store.identifyRequestCount,a.captureTiming("".concat(l,"-identityRequestStart"))),m=a._Helpers.invokeCallback,n=a.Logger,n.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return n.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(n.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return m(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];o=g||null,p=this.getUploadUrl(c,g),q=window.fetch?new FetchUploader(p):new XHRUploader(p),r={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,A.label=1;case 1:return A.trys.push([1,9,,10]),[4/*yield*/,q.upload(r)];case 2:return s=A.sent(),t=void 0,u=void 0,v=s.status,v===HTTP_ACCEPTED?[3/*break*/,3]:v===HTTP_OK?[3/*break*/,3]:v===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return s.json?[4/*yield*/,s.json()]:[3/*break*/,5];case 4:return w=A.sent(),t=this.getIdentityResponseFromFetch(s,w),[3/*break*/,6];case 5:t=this.getIdentityResponseFromXHR(s),A.label=6;case 6:return t.status===HTTP_BAD_REQUEST?(x=t.responseText,u="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+t.status,(null===x||void 0===x?void 0:x.Errors)&&(y=x.Errors.map(function(a){return a.message}).join(", "),u+=" - "+y)):(u="Received Identity Response from server: ",u+=JSON.stringify(t.responseText)),[3/*break*/,8];case 7:throw new Error("Received HTTP Code of "+s.status);case 8:return a._Store.identityCallInFlight=!1,n.verbose(u),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(l=a._Store.identifyRequestCount,a.captureTiming("".concat(l,"-identityRequestEnd"))),f(t,o,d,e,c,h,!1),[3/*break*/,10];case 9:return z=A.sent(),a._Store.identityCallInFlight=!1,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(l=a._Store.identifyRequestCount,a.captureTiming("".concat(l,"-identityRequestEnd"))),y=z.message||z.toString(),n.error("Error sending identity request to servers - "+y),m(d,HTTPCodes$1.noHttpCoverage,y),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};}
1404
1404
 
1405
1405
  // The formatted ClickID value must be of the form version.subdomainIndex.creationTime.<fbclid>, where:
1406
1406
  // - version is always this prefix: fb
@@ -1450,7 +1450,7 @@ for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickI
1450
1450
  // Rokt Manager in a "ready" state and it can begin sending data to the kit.
1451
1451
  //
1452
1452
  // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
1453
- var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[];}/**
1453
+ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[],this.initialized=!1;}/**
1454
1454
  * Initializes the RoktManager with configuration settings and user data.
1455
1455
  *
1456
1456
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
@@ -1467,9 +1467,12 @@ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters=
1467
1467
  // as that is independent of this setting, though they share the same name.
1468
1468
  var o=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through
1469
1469
  // to the Rokt Launcher.
1470
- this.launcherOptions=__assign({sandbox:o},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain);},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b,c;return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s=this;return __generator(this,function(t){switch(t.label){case 0:if(this.captureTiming&&this.captureTiming(PerformanceMarkType.JointSdkSelectPlacements),!this.isReady())return [2/*return*/,this.deferredCall("selectPlacements",a)];t.label=1;case 1:if(t.trys.push([1,6,,7]),d=a.attributes,e=(null===d||void 0===d?void 0:d.sandbox)||null,f=this.mapPlacementAttributes(d,this.placementAttributesMapping),this.currentUser=this.identityService.getCurrentUser(),g=(null===(c=null===(b=this.currentUser)||void 0===b?void 0:b.getUserIdentities())||void 0===c?void 0:c.userIdentities)||{},h=g.email,i=f.email,j=void 0,k=void 0,this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType)&&(j=g[this.mappedEmailShaIdentityType],k=f.emailsha256||f[this.mappedEmailShaIdentityType]||void 0),l=this.hasIdentityChanged(h,i),m=this.hasIdentityChanged(j,k),n={},l&&(n.email=i,i&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),m&&(n[this.mappedEmailShaIdentityType]=k,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(n))return [3/*break*/,5];t.label=2;case 2:return t.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){s.identityService.identify({userIdentities:__assign(__assign({},g),n)},function(){a();});})];case 3:return t.sent(),[3/*break*/,5];case 4:return o=t.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(o)),[3/*break*/,5];case 5:return this.setUserAttributes(f),p=__assign(__assign({},f),null===e?{}:{sandbox:e}),q=__assign(__assign({},a),{attributes:p}),[2/*return*/,this.kit.selectPlacements(q)];case 6:return r=t.sent(),[2/*return*/,Promise.reject(r instanceof Error?r:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);f<g.length;f++)h=g[f],i=h.key,j=h.attributeValue,k=h.hashedValue,e[i]=j,k&&(e["".concat(i,"sha256")]=k);return [2/*return*/,e];case 2:return l=o.sent(),m=l instanceof Error?l.message:l+"",this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(m)),[2/*return*/,{}];case 3:return [2/*return*/]}})})},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.deferredCall("setExtensionData",a);try{this.kit.setExtensionData(a);}catch(a){var b=a instanceof Error?a.message:a+"";throw new Error("Error setting extension data: "+b)}},a.prototype.use=function(a){if(!this.isReady())return this.deferredCall("use",a);try{return this.kit.use(a)}catch(b){return Promise.reject(b instanceof Error?b:new Error("Error using extension: "+a))}},a.prototype.hashSha256=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];e.label=1;case 1:return e.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,e.sent()];case 3:return c=e.sent(),d=c instanceof Error?c.message:c+"",this.logger.error("Failed to hashSha256, returning undefined: ".concat(d)),[2/*return*/,void 0];case 4:return [2/*return*/]}})})},a.prototype.getLocalSessionAttributes=function(){return this.store.getLocalSessionAttributes()},a.prototype.setLocalSessionAttribute=function(a,b){this.store.setLocalSessionAttribute(a,b);},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1471
- return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)if(a.hasOwnProperty(d)&&-1===b.indexOf(d)){var e=a[d];c[d]=Array.isArray(e)?JSON.stringify(e):e;}try{this.currentUser.setUserAttributes(c);}catch(a){this.logger.error("Error setting user attributes: "+a);}},a.prototype.mapPlacementAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.processMessageQueue=function(){var a,b=this;this.isReady()&&0!==this.messageQueue.size&&(// Clear the queue after processing all messages
1472
- null===(a=this.logger)||void 0===a?void 0:a.verbose("RoktManager: Processing ".concat(this.messageQueue.size," queued messages")),this.messageQueue.forEach(function(a){var c,d,e;if(!(a.methodName in b)||!isFunction(b[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found")));null===(d=b.logger)||void 0===d?void 0:d.verbose("RoktManager: Processing queued message: ".concat(a.methodName," with payload: ").concat(JSON.stringify(a.payload)));try{var f=b[a.methodName](a.payload);b.completePendingPromise(a.messageId,f);}catch(c){var g=c instanceof Error?c.message:c+"";null===(e=b.logger)||void 0===e?void 0:e.error("RoktManager: Error processing message '".concat(a.methodName,"': ").concat(g)),b.completePendingPromise(a.messageId,Promise.reject(c));}}),this.messageQueue.clear());},a.prototype.queueMessage=function(a){this.messageQueue.set(a.messageId,a);},a.prototype.deferredCall=function(a,b){var c=this;return new Promise(function(d,e){var f="".concat(a,"_").concat(generateUniqueId());c.queueMessage({messageId:f,methodName:a,payload:b,resolve:d,reject:e});})},a.prototype.completePendingPromise=function(a,b){if(a&&this.messageQueue.has(a)){var c=this.messageQueue.get(a);c.resolve&&Promise.resolve(b).then(function(a){return c.resolve(a)})["catch"](function(a){return c.reject(a)}),this.messageQueue["delete"](a);}},a.prototype.sha256Hex=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:return b=new TextEncoder,c=b.encode(a),[4/*yield*/,crypto.subtle.digest("SHA-256",c)];case 1:return d=e.sent(),[2/*return*/,this.arrayBufferToHex(d)]}})})},a.prototype.arrayBufferToHex=function(a){for(var b,c=new Uint8Array(a),d="",e=0;e<c.length;e++)b=c[e].toString(16).padStart(2,"0"),d+=b;return d},a.prototype.hasIdentityChanged=function(a,b){return !!b&&(!a||a!==b);// Values are the same
1470
+ this.launcherOptions=__assign({sandbox:o},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain),this.initialized=!0;},Object.defineProperty(a.prototype,"isInitialized",{get:function get(){return this.initialized},enumerable:!1,configurable:!0}),a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b,c,d,e,f;return __awaiter(this,void 0,void 0,function(){var g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y=this;return __generator(this,function(z){switch(z.label){case 0:// Queue if kit isn't ready OR if identity is in flight
1471
+ if(this.captureTiming&&this.captureTiming(PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(b=this.store)||void 0===b?void 0:b.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];z.label=1;case 1:if(z.trys.push([1,6,,7]),g=a.attributes,h=(null===g||void 0===g?void 0:g.sandbox)||null,i=this.mapPlacementAttributes(g,this.placementAttributesMapping),this.currentUser=this.identityService.getCurrentUser(),j=(null===(d=null===(c=this.currentUser)||void 0===c?void 0:c.getUserIdentities())||void 0===d?void 0:d.userIdentities)||{},k=j.email,l=i.email,m=void 0,n=void 0,o=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),o&&(m=j[this.mappedEmailShaIdentityType],n=i.emailsha256||i[this.mappedEmailShaIdentityType]||void 0),p=this.hasIdentityChanged(k,l),q=this.hasIdentityChanged(m,n),r={},p&&(r.email=l,l&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),q&&(r[this.mappedEmailShaIdentityType]=n,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(r))return [3/*break*/,5];z.label=2;case 2:return z.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){y.identityService.identify({userIdentities:__assign(__assign({},j),r)},function(){a();});})];case 3:return z.sent(),[3/*break*/,5];case 4:return s=z.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(s)),[3/*break*/,5];case 5:return this.currentUser=this.identityService.getCurrentUser(),t=(null===(f=null===(e=this.currentUser)||void 0===e?void 0:e.getUserIdentities())||void 0===f?void 0:f.userIdentities)||{},this.setUserAttributes(i),u=__assign(__assign({},i),null===h?{}:{sandbox:h}),t.email&&!u.email&&(u.email=t.email),o&&(v=t[this.mappedEmailShaIdentityType],v&&!u.emailsha256&&!u[this.mappedEmailShaIdentityType]&&(u.emailsha256=v)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,w=__assign(__assign({},a),{attributes:u}),[2/*return*/,this.kit.selectPlacements(w)];case 6:return x=z.sent(),[2/*return*/,Promise.reject(x instanceof Error?x:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);f<g.length;f++)h=g[f],i=h.key,j=h.attributeValue,k=h.hashedValue,e[i]=j,k&&(e["".concat(i,"sha256")]=k);return [2/*return*/,e];case 2:return l=o.sent(),m=l instanceof Error?l.message:l+"",this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(m)),[2/*return*/,{}];case 3:return [2/*return*/]}})})},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.deferredCall("setExtensionData",a);try{this.kit.setExtensionData(a);}catch(a){var b=a instanceof Error?a.message:a+"";throw new Error("Error setting extension data: "+b)}},a.prototype.use=function(a){if(!this.isReady())return this.deferredCall("use",a);try{return this.kit.use(a)}catch(b){return Promise.reject(b instanceof Error?b:new Error("Error using extension: "+a))}},a.prototype.hashSha256=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];e.label=1;case 1:return e.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,e.sent()];case 3:return c=e.sent(),d=c instanceof Error?c.message:c+"",this.logger.error("Failed to hashSha256, returning undefined: ".concat(d)),[2/*return*/,void 0];case 4:return [2/*return*/]}})})},a.prototype.getLocalSessionAttributes=function(){return this.store.getLocalSessionAttributes()},a.prototype.setLocalSessionAttribute=function(a,b){this.store.setLocalSessionAttribute(a,b);},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1472
+ return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)if(a.hasOwnProperty(d)&&-1===b.indexOf(d)){var e=a[d];c[d]=Array.isArray(e)?JSON.stringify(e):e;}try{this.currentUser.setUserAttributes(c);}catch(a){this.logger.error("Error setting user attributes: "+a);}},a.prototype.mapPlacementAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.onIdentityComplete=function(){this.isReady()&&(this.currentUser=this.identityService.getCurrentUser(),this.processMessageQueue());},a.prototype.processMessageQueue=function(){var a,b=this;if(this.isReady()&&0!==this.messageQueue.size){null===(a=this.logger)||void 0===a?void 0:a.verbose("RoktManager: Processing ".concat(this.messageQueue.size," queued messages"));var c=Array.from(this.messageQueue.values());// Clear the queue immediately to prevent re-processing
1473
+ this.messageQueue.clear(),c.forEach(function(a){var c,d;if(!(a.methodName in b)||!isFunction(b[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found")));null===(d=b.logger)||void 0===d?void 0:d.verbose("RoktManager: Processing queued message: ".concat(a.methodName," with payload: ").concat(JSON.stringify(a.payload)));// Capture resolve/reject functions before async processing
1474
+ var e=a.resolve,f=a.reject,g=function(c){var d,e=c instanceof Error?c.message:c+"";null===(d=b.logger)||void 0===d?void 0:d.error("RoktManager: Error processing message '".concat(a.methodName,"': ").concat(e)),f&&f(c);};try{var h=b[a.methodName](a.payload);// Handle both sync and async methods
1475
+ Promise.resolve(h).then(function(a){e&&e(a);})["catch"](g);}catch(a){g(a);}});}},a.prototype.queueMessage=function(a){this.messageQueue.set(a.messageId,a);},a.prototype.deferredCall=function(a,b){var c=this;return new Promise(function(d,e){var f="".concat(a,"_").concat(generateUniqueId());c.queueMessage({messageId:f,methodName:a,payload:b,resolve:d,reject:e});})},a.prototype.sha256Hex=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:return b=new TextEncoder,c=b.encode(a),[4/*yield*/,crypto.subtle.digest("SHA-256",c)];case 1:return d=e.sent(),[2/*return*/,this.arrayBufferToHex(d)]}})})},a.prototype.arrayBufferToHex=function(a){for(var b,c=new Uint8Array(a),d="",e=0;e<c.length;e++)b=c[e].toString(16).padStart(2,"0"),d+=b;return d},a.prototype.hasIdentityChanged=function(a,b){return !!b&&(!a||a!==b);// Values are the same
1473
1476
  },a}();
1474
1477
 
1475
1478
  /**
@@ -15,7 +15,7 @@ map:function map(a,b){var c,d,e;if(null===this)throw new TypeError(" this is nul
15
15
  filter:function filter(a/*, thisArg*/){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f<c;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g);}return d},// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
16
16
  isArray:function isArray(a){return "[object Array]"===Object.prototype.toString.call(a)},Base64:Base64$1};
17
17
 
18
- var version = "2.54.0";
18
+ var version = "2.55.0";
19
19
 
20
20
  var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodHasBeenDeprecated:"has been deprecated.",MethodMarkedForDeprecationPostfix:"is a deprecated method and will be removed in future releases.",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
21
21
  },DefaultBaseUrls:{v1SecureServiceUrl:"jssdks.mparticle.com/v1/JS/",v2SecureServiceUrl:"jssdks.mparticle.com/v2/JS/",v3SecureServiceUrl:"jssdks.mparticle.com/v3/JS/",configUrl:"jssdkcdns.mparticle.com/JS/v2/",identityUrl:"identity.mparticle.com/v1/",aliasUrl:"jssdks.mparticle.com/v1/identity/",userAudienceUrl:"nativesdks.mparticle.com/v1/"},// These are the paths that are used to construct the CNAME urls
@@ -580,7 +580,7 @@ document.addEventListener("visibilitychange",function(){return a.handleVisibilit
580
580
 
581
581
  function createSDKConfig(a){// TODO: Refactor to create a default config object
582
582
  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
583
- function Store(a,b,c){var d=this,e=b._Helpers.createMainStorageName,f=b._NativeSdkHelpers.isWebviewEnabled,g={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},// Placeholder for in-memory persistence model
583
+ function Store(a,b,c){var d=this,e=b._Helpers.createMainStorageName,f=b._NativeSdkHelpers.isWebviewEnabled,g={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,identifyRequestCount:0,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},// Placeholder for in-memory persistence model
584
584
  persistenceData:{gs:{}}};for(var h in g)this[h]=g[h];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&returnConvertedBoolean(a.isDevelopmentMode);var i=processBaseUrls(a,this.SDKConfig.flags,c);for(var j in i)this.SDKConfig[j]=i[j];if(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 k=a.identityCallback;b._Helpers.Validators.isFunction(k)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof$1(k)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var l=a.dataPlan;l.planId&&(isDataPlanSlug(l.planId)?this.SDKConfig.dataPlan.PlanId=l.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),l.planVersion&&(isNumber(l.planVersion)?this.SDKConfig.dataPlan.PlanVersion=l.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var m=a.dataPlanOptions;m.hasOwnProperty("dataPlanVersion")&&m.hasOwnProperty("blockUserAttributes")&&m.hasOwnProperty("blockEventAttributes")&&m.hasOwnProperty("blockEvents")&&m.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this._getFromPersistence=function(a,b){return a?(d.syncPersistenceData(),d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a][b]?d.persistenceData[a][b]:null):null},this._setPersistence=function(a,c,e){var f;a&&(d.syncPersistenceData(),d.persistenceData&&(d.persistenceData[a]?d.persistenceData[a][c]=e:d.persistenceData[a]=(f={},f[c]=e,f),isObject(d.persistenceData[a][c])&&isEmpty(d.persistenceData[a][c])&&delete d.persistenceData[a][c],b._Persistence.savePersistence(d.persistenceData)));},this.hasInvalidIdentifyRequest=function(){var a=d.SDKConfig.identifyRequest;return isObject(a)&&isObject(a.userIdentities)&&isEmpty(a.userIdentities)||!a},this.getConsentState=function(a){var c=b._Consent.ConsentSerialization.fromMinifiedJsonObject,e=d._getFromPersistence(a,"con");return isEmpty(e)?null:c(e)},this.setConsentState=function(a,c){var e=b._Consent.ConsentSerialization.toMinifiedJsonObject;// If ConsentState is null, we assume the intent is to clear out the consent state
585
585
  (c||null===c)&&d._setPersistence(a,"con",e(c));},this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.getFirstSeenTime=function(a){return d._getFromPersistence(a,"fst")},this.setFirstSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"fst",c);}},this.getLastSeenTime=function(a){if(!a)return null;// https://go.mparticle.com/work/SQDSDKS-6315
586
586
  var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d._getFromPersistence(a,"lst")},this.setLastSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"lst",c);}},this.getLocalSessionAttributes=function(){return d.localSessionAttributes||{}},this.setLocalSessionAttribute=function(a,c){var e;d.localSessionAttributes[a]=c,d.persistenceData.gs.lsa=__assign(__assign({},d.persistenceData.gs.lsa||{}),(e={},e[a]=c,e)),b._Persistence.savePersistence(d.persistenceData);},this.syncPersistenceData=function(){var a=b._Persistence.getPersistence();d.persistenceData=b._Helpers.extend({},d.persistenceData,a);},this.getUserAttributes=function(a){return d._getFromPersistence(a,"ua")||{}},this.setUserAttributes=function(a,b){return d._setPersistence(a,"ua",b)},this.getUserIdentities=function(a){return d._getFromPersistence(a,"ui")||{}},this.setUserIdentities=function(a,b){d._setPersistence(a,"ui",b);},this.addMpidToSessionHistory=function(a,b){var c=d.currentSessionMPIDs.indexOf(a);return a&&b!==a&&0>c?void d.currentSessionMPIDs.push(a):void(0<=c&&(d.currentSessionMPIDs=moveElementToEnd(d.currentSessionMPIDs,c)))},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionStartDate=null,d.sessionAttributes={},d.localSessionAttributes={},b._Persistence.update();},this.processConfig=function(a){var g=a.workspaceToken,h=a.requiredWebviewBridgeName;// We should reprocess the flags and baseUrls in case they have changed when we request an updated config
@@ -1296,7 +1296,7 @@ return a._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===d.audie
1296
1296
  * @deprecated
1297
1297
  */getCartProducts:function getCartProducts(){return a.Logger.warning(generateDeprecationMessage("Identity.getCurrentUser().getCart().getCartProducts()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking")),[]}}},this.parseIdentityResponse=function(b,d,f,g,h,i,j){var k,l,m,n=a.Identity.getUser(d),o=n?n.getMPID():null,p=n?n.getUserIdentities().userIdentities:{},q={};a._Store.identityCallInFlight=!1;try{var r,s,t;if(a.Logger.verbose("Parsing \""+h+"\" identity response from server"),l=null!==(r=b.responseText)&&void 0!==r?r:null,a._Store.isLoggedIn=(null===(s=l)||void 0===s?void 0:s.is_logged_in)||!1,hasMPIDChanged(n,l)&&(a._Store.mpid=l.mpid,n&&a._Persistence.setLastSeenTime(d),k=!a._Persistence.getFirstSeenTime(l.mpid),a._Persistence.setFirstSeenTime(l.mpid)),b.status===HTTP_OK){c(CacheIdentity)&&cacheOrClearIdCache(h,i,e.idCache,b,j);var u=e.IdentityAPI.getUser(l.mpid),v=u?u.getUserIdentities().userIdentities:{};h===Modify$1?(q=a._Identity.IdentityRequest.combineUserIdentities(p,g.userIdentities),a._Store.setUserIdentities(d,q)):(h===Identify&&n&&l.mpid===o&&a._Persistence.setFirstSeenTime(l.mpid),a._Store.addMpidToSessionHistory(l.mpid,d),a._CookieSyncManager.attemptCookieSync(l.mpid,k),a._Persistence.swapCurrentUser(d,l.mpid,a._Store.currentSessionMPIDs),g&&!isEmpty(g.userIdentities)&&(q=e.IdentityRequest.combineUserIdentities(v,g.userIdentities)),a._Store.setUserIdentities(l.mpid,q),a._Persistence.update(),a._Store.syncPersistenceData(),a._Persistence.findPrevCookiesBasedOnUI(g),a._Store.context=l.context||a._Store.context),m=a.Identity.getCurrentUser(),tryOnUserAlias(n,m,g,a.Logger);var w=a._Persistence.getPersistence();m&&(a._Persistence.storeDataInMemory(w,m.getMPID()),e.reinitForwardersOnUserChange(n,m),e.setForwarderCallbacks(m,h));var x=IdentityType.getNewIdentitiesByName(q),y=h===Modify$1?p:v;// https://go.mparticle.com/work/SQDSDKS-6501
1298
1298
  e.sendUserIdentityChangeEvent(x,h,l.mpid,y);}if(f){var z=0===b.status?HTTPCodes$2.noHttpCoverage:b.status;a._Helpers.invokeCallback(f,z,l||null,m);}else l&&!isEmpty(l.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
1299
- a.Logger.error("Received HTTP response code of "+b.status+" - "+l.errors[0].message);a.Logger.verbose("Successfully parsed Identity Response"),null===(t=a._APIClient)||void 0===t||t.processQueuedEvents();}catch(c){f&&a._Helpers.invokeCallback(f,b.status,l||null),a.Logger.error("Error parsing JSON response from Identity server: "+c);}a._Store.isInitialized=!0,a._RoktManager.isReady()&&(a._RoktManager.currentUser=a.Identity.getCurrentUser()),a._preInit.readyQueue=processReadyQueue(a._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(b,c,d,f){if(d||c===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1299
+ a.Logger.error("Received HTTP response code of "+b.status+" - "+l.errors[0].message);a.Logger.verbose("Successfully parsed Identity Response"),null===(t=a._APIClient)||void 0===t||t.processQueuedEvents();}catch(c){f&&a._Helpers.invokeCallback(f,b.status,l||null),a.Logger.error("Error parsing JSON response from Identity server: "+c);}a._Store.isInitialized=!0,a._RoktManager.onIdentityComplete(),a._preInit.readyQueue=processReadyQueue(a._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(b,c,d,f){if(d||c===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1300
1300
  {// https://go.mparticle.com/work/SQDSDKS-6354
1301
1301
  var g=this.IdentityAPI.getUser(d);for(var h in b)// Verifies a change actually happened
1302
1302
  if(f[h]!==b[h]){var i,j=!f[h],k=e.createUserIdentityChange(h,b[h],f[h],j,g);// If a new identity type was introduced when the identity changes
@@ -1400,7 +1400,7 @@ return !("boolean"==typeof b&&b)&&"object"===_typeof$1(b)&&!0!==b[a];// When "Bl
1400
1400
  var buildUrl=function(a,b,c,d){var e=d?"1":"0",f=["env=".concat(e)],g=c||{},h=g.planId,i=g.planVersion;return h&&f.push("plan_id=".concat(h)),i&&f.push("plan_version=".concat(i)),"".concat(a+b+"/config","?").concat(f.join("&"))};function ConfigAPIClient(a,b,c){var d=this,e="https://"+c._Store.SDKConfig.configUrl,f=b.isDevelopmentMode,g=b.dataPlan,h=buildUrl(e,a,g,f),i=window.fetch?new FetchUploader(h):new XHRUploader(h);this.getSDKConfiguration=function(){return __awaiter(d,void 0,void 0,function(){var a,d,e,f,h,j,k;return __generator(this,function(l){switch(l.label){case 0:d={method:"get",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"text/plain;charset=UTF-8"},body:null},l.label=1;case 1:return l.trys.push([1,6,,7]),[4/*yield*/,i.upload(d)];case 2:return (e=l.sent(),200!==e.status)?[3/*break*/,5]:(null===(h=null===c||void 0===c?void 0:c.Logger)||void 0===h?void 0:h.verbose("Successfully received configuration from server"),e.json?[4/*yield*/,e.json()]:[3/*break*/,4]);case 3:return a=l.sent(),[2/*return*/,a];case 4:return f=e,a=JSON.parse(f.responseText),[2/*return*/,a];case 5:return null===(j=null===c||void 0===c?void 0:c.Logger)||void 0===j?void 0:j.verbose("Issue with receiving configuration from server, received HTTP Code of "+e.statusText),[3/*break*/,7];case 6:return l.sent(),null===(k=null===c||void 0===c?void 0:c.Logger)||void 0===k?void 0:k.error("Error getting forwarder configuration from mParticle servers."),[3/*break*/,7];case 7:// Returns the original config object if we cannot retrieve the remote config
1401
1401
  return [2/*return*/,b]}})})};}
1402
1402
 
1403
- var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){return __awaiter(this,void 0,void 0,function(){var i,j,k,l,m,n,o,p,q,r,s,t,u,v,u;return __generator(this,function(w){switch(w.label){case 0:if(i=a._Helpers.invokeCallback,j=a.Logger,j.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return j.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(j.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return i(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];k=g||null,l=this.getUploadUrl(c,g),m=window.fetch?new FetchUploader(l):new XHRUploader(l),n={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,w.label=1;case 1:return w.trys.push([1,9,,10]),[4/*yield*/,m.upload(n)];case 2:return o=w.sent(),p=void 0,q=void 0,r=o.status,r===HTTP_ACCEPTED?[3/*break*/,3]:r===HTTP_OK?[3/*break*/,3]:r===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return o.json?[4/*yield*/,o.json()]:[3/*break*/,5];case 4:return s=w.sent(),p=this.getIdentityResponseFromFetch(o,s),[3/*break*/,6];case 5:p=this.getIdentityResponseFromXHR(o),w.label=6;case 6:return p.status===HTTP_BAD_REQUEST?(t=p.responseText,q="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+p.status,(null===t||void 0===t?void 0:t.Errors)&&(u=t.Errors.map(function(a){return a.message}).join(", "),q+=" - "+u)):(q="Received Identity Response from server: ",q+=JSON.stringify(p.responseText)),[3/*break*/,8];case 7:throw new Error("Received HTTP Code of "+o.status);case 8:return a._Store.identityCallInFlight=!1,j.verbose(q),f(p,k,d,e,c,h,!1),[3/*break*/,10];case 9:return v=w.sent(),a._Store.identityCallInFlight=!1,u=v.message||v.toString(),j.error("Error sending identity request to servers - "+u),i(d,HTTPCodes$1.noHttpCoverage,u),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};}
1403
+ var HTTPCodes$1=Constants.HTTPCodes,Messages$1=Constants.Messages,IdentityMethods=Constants.IdentityMethods,Modify=IdentityMethods.Modify;function IdentityAPIClient(a){this.sendAliasRequest=function(b,c){return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,q,r,s,n;return __generator(this,function(t){switch(t.label){case 0:d=a.Logger,e=a._Helpers.invokeAliasCallback,f=a._Store.SDKConfig.aliasUrl,g=a._Store.devToken,d.verbose(Messages$1.InformationMessages.SendAliasHttp),h="https://".concat(f).concat(g,"/Alias"),i=window.fetch?new FetchUploader(h):new XHRUploader(h),j={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json"},body:JSON.stringify(b)},t.label=1;case 1:return t.trys.push([1,13,,14]),[4/*yield*/,i.upload(j)];case 2:return k=t.sent(),l=void 0,m=void 0,n=void 0,o=k.status,o===HTTP_ACCEPTED?[3/*break*/,3]:o===HTTP_OK?[3/*break*/,3]:o===HTTP_BAD_REQUEST?[3/*break*/,4]:[3/*break*/,11];case 3:return m="Received Alias Response from server: "+JSON.stringify(k.status),[3/*break*/,12];case 4:if(!k.json)return [3/*break*/,9];t.label=5;case 5:return t.trys.push([5,7,,8]),[4/*yield*/,k.json()];case 6:return l=t.sent(),[3/*break*/,8];case 7:return t.sent(),d.verbose("The request has no response body"),[3/*break*/,8];case 8:return [3/*break*/,10];case 9:q=k,l=q.responseText?JSON.parse(q.responseText):"",t.label=10;case 10:return r=l,(null===r||void 0===r?void 0:r.message)&&(n=r.message),m="Issue with sending Alias Request to mParticle Servers, received HTTP Code of "+k.status,(null===r||void 0===r?void 0:r.code)&&(m+=" - "+r.code),[3/*break*/,12];case 11:throw new Error("Received HTTP Code of "+k.status);case 12:return d.verbose(m),e(c,k.status,n),[3/*break*/,14];case 13:return s=t.sent(),n=s.message||s.toString(),d.error("Error sending alias request to mParticle servers. "+n),e(c,HTTPCodes$1.noHttpCoverage,n),[3/*break*/,14];case 14:return [2/*return*/]}})})},this.sendIdentityRequest=function(b,c,d,e,f,g,h){var i,j,k;return __awaiter(this,void 0,void 0,function(){var l,m,n,o,p,q,r,s,t,u,v,w,x,y,l,z,l,y;return __generator(this,function(A){switch(A.label){case 0:if((null===(i=a._RoktManager)||void 0===i?void 0:i.isInitialized)&&(a._Store.identifyRequestCount=(a._Store.identifyRequestCount||0)+1,l=a._Store.identifyRequestCount,a.captureTiming("".concat(l,"-identityRequestStart"))),m=a._Helpers.invokeCallback,n=a.Logger,n.verbose(Messages$1.InformationMessages.SendIdentityBegin),!b)return n.error(Messages$1.ErrorMessages.APIRequestEmpty),[2/*return*/];if(n.verbose(Messages$1.InformationMessages.SendIdentityHttp),a._Store.identityCallInFlight)return m(d,HTTPCodes$1.activeIdentityRequest,"There is currently an Identity request processing. Please wait for this to return before requesting again"),[2/*return*/];o=g||null,p=this.getUploadUrl(c,g),q=window.fetch?new FetchUploader(p):new XHRUploader(p),r={method:"post",headers:{Accept:"text/plain;charset=UTF-8","Content-Type":"application/json","x-mp-key":a._Store.devToken},body:JSON.stringify(b)},a._Store.identityCallInFlight=!0,A.label=1;case 1:return A.trys.push([1,9,,10]),[4/*yield*/,q.upload(r)];case 2:return s=A.sent(),t=void 0,u=void 0,v=s.status,v===HTTP_ACCEPTED?[3/*break*/,3]:v===HTTP_OK?[3/*break*/,3]:v===HTTP_BAD_REQUEST?[3/*break*/,3]:[3/*break*/,7];case 3:return s.json?[4/*yield*/,s.json()]:[3/*break*/,5];case 4:return w=A.sent(),t=this.getIdentityResponseFromFetch(s,w),[3/*break*/,6];case 5:t=this.getIdentityResponseFromXHR(s),A.label=6;case 6:return t.status===HTTP_BAD_REQUEST?(x=t.responseText,u="Issue with sending Identity Request to mParticle Servers, received HTTP Code of "+t.status,(null===x||void 0===x?void 0:x.Errors)&&(y=x.Errors.map(function(a){return a.message}).join(", "),u+=" - "+y)):(u="Received Identity Response from server: ",u+=JSON.stringify(t.responseText)),[3/*break*/,8];case 7:throw new Error("Received HTTP Code of "+s.status);case 8:return a._Store.identityCallInFlight=!1,n.verbose(u),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(l=a._Store.identifyRequestCount,a.captureTiming("".concat(l,"-identityRequestEnd"))),f(t,o,d,e,c,h,!1),[3/*break*/,10];case 9:return z=A.sent(),a._Store.identityCallInFlight=!1,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(l=a._Store.identifyRequestCount,a.captureTiming("".concat(l,"-identityRequestEnd"))),y=z.message||z.toString(),n.error("Error sending identity request to servers - "+y),m(d,HTTPCodes$1.noHttpCoverage,y),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};}
1404
1404
 
1405
1405
  // The formatted ClickID value must be of the form version.subdomainIndex.creationTime.<fbclid>, where:
1406
1406
  // - version is always this prefix: fb
@@ -1450,7 +1450,7 @@ for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickI
1450
1450
  // Rokt Manager in a "ready" state and it can begin sending data to the kit.
1451
1451
  //
1452
1452
  // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
1453
- var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[];}/**
1453
+ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[],this.initialized=!1;}/**
1454
1454
  * Initializes the RoktManager with configuration settings and user data.
1455
1455
  *
1456
1456
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
@@ -1467,9 +1467,12 @@ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters=
1467
1467
  // as that is independent of this setting, though they share the same name.
1468
1468
  var o=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through
1469
1469
  // to the Rokt Launcher.
1470
- this.launcherOptions=__assign({sandbox:o},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain);},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b,c;return __awaiter(this,void 0,void 0,function(){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s=this;return __generator(this,function(t){switch(t.label){case 0:if(this.captureTiming&&this.captureTiming(PerformanceMarkType.JointSdkSelectPlacements),!this.isReady())return [2/*return*/,this.deferredCall("selectPlacements",a)];t.label=1;case 1:if(t.trys.push([1,6,,7]),d=a.attributes,e=(null===d||void 0===d?void 0:d.sandbox)||null,f=this.mapPlacementAttributes(d,this.placementAttributesMapping),this.currentUser=this.identityService.getCurrentUser(),g=(null===(c=null===(b=this.currentUser)||void 0===b?void 0:b.getUserIdentities())||void 0===c?void 0:c.userIdentities)||{},h=g.email,i=f.email,j=void 0,k=void 0,this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType)&&(j=g[this.mappedEmailShaIdentityType],k=f.emailsha256||f[this.mappedEmailShaIdentityType]||void 0),l=this.hasIdentityChanged(h,i),m=this.hasIdentityChanged(j,k),n={},l&&(n.email=i,i&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),m&&(n[this.mappedEmailShaIdentityType]=k,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(n))return [3/*break*/,5];t.label=2;case 2:return t.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){s.identityService.identify({userIdentities:__assign(__assign({},g),n)},function(){a();});})];case 3:return t.sent(),[3/*break*/,5];case 4:return o=t.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(o)),[3/*break*/,5];case 5:return this.setUserAttributes(f),p=__assign(__assign({},f),null===e?{}:{sandbox:e}),q=__assign(__assign({},a),{attributes:p}),[2/*return*/,this.kit.selectPlacements(q)];case 6:return r=t.sent(),[2/*return*/,Promise.reject(r instanceof Error?r:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);f<g.length;f++)h=g[f],i=h.key,j=h.attributeValue,k=h.hashedValue,e[i]=j,k&&(e["".concat(i,"sha256")]=k);return [2/*return*/,e];case 2:return l=o.sent(),m=l instanceof Error?l.message:l+"",this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(m)),[2/*return*/,{}];case 3:return [2/*return*/]}})})},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.deferredCall("setExtensionData",a);try{this.kit.setExtensionData(a);}catch(a){var b=a instanceof Error?a.message:a+"";throw new Error("Error setting extension data: "+b)}},a.prototype.use=function(a){if(!this.isReady())return this.deferredCall("use",a);try{return this.kit.use(a)}catch(b){return Promise.reject(b instanceof Error?b:new Error("Error using extension: "+a))}},a.prototype.hashSha256=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];e.label=1;case 1:return e.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,e.sent()];case 3:return c=e.sent(),d=c instanceof Error?c.message:c+"",this.logger.error("Failed to hashSha256, returning undefined: ".concat(d)),[2/*return*/,void 0];case 4:return [2/*return*/]}})})},a.prototype.getLocalSessionAttributes=function(){return this.store.getLocalSessionAttributes()},a.prototype.setLocalSessionAttribute=function(a,b){this.store.setLocalSessionAttribute(a,b);},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1471
- return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)if(a.hasOwnProperty(d)&&-1===b.indexOf(d)){var e=a[d];c[d]=Array.isArray(e)?JSON.stringify(e):e;}try{this.currentUser.setUserAttributes(c);}catch(a){this.logger.error("Error setting user attributes: "+a);}},a.prototype.mapPlacementAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.processMessageQueue=function(){var a,b=this;this.isReady()&&0!==this.messageQueue.size&&(// Clear the queue after processing all messages
1472
- null===(a=this.logger)||void 0===a?void 0:a.verbose("RoktManager: Processing ".concat(this.messageQueue.size," queued messages")),this.messageQueue.forEach(function(a){var c,d,e;if(!(a.methodName in b)||!isFunction(b[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found")));null===(d=b.logger)||void 0===d?void 0:d.verbose("RoktManager: Processing queued message: ".concat(a.methodName," with payload: ").concat(JSON.stringify(a.payload)));try{var f=b[a.methodName](a.payload);b.completePendingPromise(a.messageId,f);}catch(c){var g=c instanceof Error?c.message:c+"";null===(e=b.logger)||void 0===e?void 0:e.error("RoktManager: Error processing message '".concat(a.methodName,"': ").concat(g)),b.completePendingPromise(a.messageId,Promise.reject(c));}}),this.messageQueue.clear());},a.prototype.queueMessage=function(a){this.messageQueue.set(a.messageId,a);},a.prototype.deferredCall=function(a,b){var c=this;return new Promise(function(d,e){var f="".concat(a,"_").concat(generateUniqueId());c.queueMessage({messageId:f,methodName:a,payload:b,resolve:d,reject:e});})},a.prototype.completePendingPromise=function(a,b){if(a&&this.messageQueue.has(a)){var c=this.messageQueue.get(a);c.resolve&&Promise.resolve(b).then(function(a){return c.resolve(a)})["catch"](function(a){return c.reject(a)}),this.messageQueue["delete"](a);}},a.prototype.sha256Hex=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:return b=new TextEncoder,c=b.encode(a),[4/*yield*/,crypto.subtle.digest("SHA-256",c)];case 1:return d=e.sent(),[2/*return*/,this.arrayBufferToHex(d)]}})})},a.prototype.arrayBufferToHex=function(a){for(var b,c=new Uint8Array(a),d="",e=0;e<c.length;e++)b=c[e].toString(16).padStart(2,"0"),d+=b;return d},a.prototype.hasIdentityChanged=function(a,b){return !!b&&(!a||a!==b);// Values are the same
1470
+ this.launcherOptions=__assign({sandbox:o},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain),this.initialized=!0;},Object.defineProperty(a.prototype,"isInitialized",{get:function get(){return this.initialized},enumerable:!1,configurable:!0}),a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b,c,d,e,f;return __awaiter(this,void 0,void 0,function(){var g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y=this;return __generator(this,function(z){switch(z.label){case 0:// Queue if kit isn't ready OR if identity is in flight
1471
+ if(this.captureTiming&&this.captureTiming(PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(b=this.store)||void 0===b?void 0:b.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];z.label=1;case 1:if(z.trys.push([1,6,,7]),g=a.attributes,h=(null===g||void 0===g?void 0:g.sandbox)||null,i=this.mapPlacementAttributes(g,this.placementAttributesMapping),this.currentUser=this.identityService.getCurrentUser(),j=(null===(d=null===(c=this.currentUser)||void 0===c?void 0:c.getUserIdentities())||void 0===d?void 0:d.userIdentities)||{},k=j.email,l=i.email,m=void 0,n=void 0,o=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),o&&(m=j[this.mappedEmailShaIdentityType],n=i.emailsha256||i[this.mappedEmailShaIdentityType]||void 0),p=this.hasIdentityChanged(k,l),q=this.hasIdentityChanged(m,n),r={},p&&(r.email=l,l&&this.logger.warning("Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.")),q&&(r[this.mappedEmailShaIdentityType]=n,this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.")),!!isEmpty(r))return [3/*break*/,5];z.label=2;case 2:return z.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){y.identityService.identify({userIdentities:__assign(__assign({},j),r)},function(){a();});})];case 3:return z.sent(),[3/*break*/,5];case 4:return s=z.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(s)),[3/*break*/,5];case 5:return this.currentUser=this.identityService.getCurrentUser(),t=(null===(f=null===(e=this.currentUser)||void 0===e?void 0:e.getUserIdentities())||void 0===f?void 0:f.userIdentities)||{},this.setUserAttributes(i),u=__assign(__assign({},i),null===h?{}:{sandbox:h}),t.email&&!u.email&&(u.email=t.email),o&&(v=t[this.mappedEmailShaIdentityType],v&&!u.emailsha256&&!u[this.mappedEmailShaIdentityType]&&(u.emailsha256=v)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,w=__assign(__assign({},a),{attributes:u}),[2/*return*/,this.kit.selectPlacements(w)];case 6:return x=z.sent(),[2/*return*/,Promise.reject(x instanceof Error?x:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);f<g.length;f++)h=g[f],i=h.key,j=h.attributeValue,k=h.hashedValue,e[i]=j,k&&(e["".concat(i,"sha256")]=k);return [2/*return*/,e];case 2:return l=o.sent(),m=l instanceof Error?l.message:l+"",this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(m)),[2/*return*/,{}];case 3:return [2/*return*/]}})})},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.deferredCall("setExtensionData",a);try{this.kit.setExtensionData(a);}catch(a){var b=a instanceof Error?a.message:a+"";throw new Error("Error setting extension data: "+b)}},a.prototype.use=function(a){if(!this.isReady())return this.deferredCall("use",a);try{return this.kit.use(a)}catch(b){return Promise.reject(b instanceof Error?b:new Error("Error using extension: "+a))}},a.prototype.hashSha256=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:if(null===a||void 0===a)return this.logger.warning("hashSha256 received null/undefined as input"),[2/*return*/,a];e.label=1;case 1:return e.trys.push([1,3,,4]),b=(a+"").trim().toLocaleLowerCase(),[4/*yield*/,this.sha256Hex(b)];case 2:return [2/*return*/,e.sent()];case 3:return c=e.sent(),d=c instanceof Error?c.message:c+"",this.logger.error("Failed to hashSha256, returning undefined: ".concat(d)),[2/*return*/,void 0];case 4:return [2/*return*/]}})})},a.prototype.getLocalSessionAttributes=function(){return this.store.getLocalSessionAttributes()},a.prototype.setLocalSessionAttribute=function(a,b){this.store.setLocalSessionAttribute(a,b);},a.prototype.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1472
+ return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)if(a.hasOwnProperty(d)&&-1===b.indexOf(d)){var e=a[d];c[d]=Array.isArray(e)?JSON.stringify(e):e;}try{this.currentUser.setUserAttributes(c);}catch(a){this.logger.error("Error setting user attributes: "+a);}},a.prototype.mapPlacementAttributes=function(a,b){for(var c,d={},e=0,f=b;e<f.length;e++)c=f[e],d[c.map]=c.value;var g={};for(var h in a)if(a.hasOwnProperty(h)){var i=d[h]||h;g[i]=a[h];}return g},a.prototype.onIdentityComplete=function(){this.isReady()&&(this.currentUser=this.identityService.getCurrentUser(),this.processMessageQueue());},a.prototype.processMessageQueue=function(){var a,b=this;if(this.isReady()&&0!==this.messageQueue.size){null===(a=this.logger)||void 0===a?void 0:a.verbose("RoktManager: Processing ".concat(this.messageQueue.size," queued messages"));var c=Array.from(this.messageQueue.values());// Clear the queue immediately to prevent re-processing
1473
+ this.messageQueue.clear(),c.forEach(function(a){var c,d;if(!(a.methodName in b)||!isFunction(b[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found")));null===(d=b.logger)||void 0===d?void 0:d.verbose("RoktManager: Processing queued message: ".concat(a.methodName," with payload: ").concat(JSON.stringify(a.payload)));// Capture resolve/reject functions before async processing
1474
+ var e=a.resolve,f=a.reject,g=function(c){var d,e=c instanceof Error?c.message:c+"";null===(d=b.logger)||void 0===d?void 0:d.error("RoktManager: Error processing message '".concat(a.methodName,"': ").concat(e)),f&&f(c);};try{var h=b[a.methodName](a.payload);// Handle both sync and async methods
1475
+ Promise.resolve(h).then(function(a){e&&e(a);})["catch"](g);}catch(a){g(a);}});}},a.prototype.queueMessage=function(a){this.messageQueue.set(a.messageId,a);},a.prototype.deferredCall=function(a,b){var c=this;return new Promise(function(d,e){var f="".concat(a,"_").concat(generateUniqueId());c.queueMessage({messageId:f,methodName:a,payload:b,resolve:d,reject:e});})},a.prototype.sha256Hex=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d;return __generator(this,function(e){switch(e.label){case 0:return b=new TextEncoder,c=b.encode(a),[4/*yield*/,crypto.subtle.digest("SHA-256",c)];case 1:return d=e.sent(),[2/*return*/,this.arrayBufferToHex(d)]}})})},a.prototype.arrayBufferToHex=function(a){for(var b,c=new Uint8Array(a),d="",e=0;e<c.length;e++)b=c[e].toString(16).padStart(2,"0"),d+=b;return d},a.prototype.hasIdentityChanged=function(a,b){return !!b&&(!a||a!==b);// Values are the same
1473
1476
  },a}();
1474
1477
 
1475
1478
  /**
package/dist/mparticle.js CHANGED
@@ -203,7 +203,7 @@ var mParticle = (function () {
203
203
  Base64: Base64$1
204
204
  };
205
205
 
206
- var version = "2.54.0";
206
+ var version = "2.55.0";
207
207
 
208
208
  var Constants = {
209
209
  sdkVersion: version,
@@ -4461,6 +4461,7 @@ var mParticle = (function () {
4461
4461
  context: null,
4462
4462
  configurationLoaded: false,
4463
4463
  identityCallInFlight: false,
4464
+ identifyRequestCount: 0,
4464
4465
  SDKConfig: {},
4465
4466
  nonCurrentUserMPIDs: {},
4466
4467
  identifyCalled: false,
@@ -8224,9 +8225,7 @@ var mParticle = (function () {
8224
8225
  mpInstance.Logger.error('Error parsing JSON response from Identity server: ' + e);
8225
8226
  }
8226
8227
  mpInstance._Store.isInitialized = true;
8227
- if (mpInstance._RoktManager.isReady()) {
8228
- mpInstance._RoktManager.currentUser = mpInstance.Identity.getCurrentUser();
8229
- }
8228
+ mpInstance._RoktManager.onIdentityComplete();
8230
8229
  mpInstance._preInit.readyQueue = processReadyQueue(mpInstance._preInit.readyQueue);
8231
8230
  };
8232
8231
 
@@ -9259,11 +9258,17 @@ var mParticle = (function () {
9259
9258
  };
9260
9259
 
9261
9260
  this.sendIdentityRequest = function (identityApiRequest, method, callback, originalIdentityApiData, parseIdentityResponse, mpid, knownIdentities) {
9261
+ var _a, _b, _c;
9262
9262
  return __awaiter(this, void 0, void 0, function () {
9263
- var invokeCallback, Logger, previousMPID, uploadUrl, uploader, fetchPayload, response, identityResponse, message, _a, responseBody, errorResponse, errorMessage, err_1, errorMessage;
9264
- return __generator(this, function (_b) {
9265
- switch (_b.label) {
9263
+ var requestCount, invokeCallback, Logger, previousMPID, uploadUrl, uploader, fetchPayload, response, identityResponse, message, _d, responseBody, errorResponse, errorMessage, requestCount, err_1, requestCount, errorMessage;
9264
+ return __generator(this, function (_e) {
9265
+ switch (_e.label) {
9266
9266
  case 0:
9267
+ if ((_a = mpInstance._RoktManager) === null || _a === void 0 ? void 0 : _a.isInitialized) {
9268
+ mpInstance._Store.identifyRequestCount = (mpInstance._Store.identifyRequestCount || 0) + 1;
9269
+ requestCount = mpInstance._Store.identifyRequestCount;
9270
+ mpInstance.captureTiming("".concat(requestCount, "-identityRequestStart"));
9271
+ }
9267
9272
  invokeCallback = mpInstance._Helpers.invokeCallback;
9268
9273
  Logger = mpInstance.Logger;
9269
9274
  Logger.verbose(Messages$1.InformationMessages.SendIdentityBegin);
@@ -9291,16 +9296,16 @@ var mParticle = (function () {
9291
9296
  body: JSON.stringify(identityApiRequest)
9292
9297
  };
9293
9298
  mpInstance._Store.identityCallInFlight = true;
9294
- _b.label = 1;
9299
+ _e.label = 1;
9295
9300
  case 1:
9296
- _b.trys.push([1, 9,, 10]);
9301
+ _e.trys.push([1, 9,, 10]);
9297
9302
  return [4 /*yield*/, uploader.upload(fetchPayload)];
9298
9303
  case 2:
9299
- response = _b.sent();
9304
+ response = _e.sent();
9300
9305
  identityResponse = void 0;
9301
9306
  message = void 0;
9302
- _a = response.status;
9303
- switch (_a) {
9307
+ _d = response.status;
9308
+ switch (_d) {
9304
9309
  case HTTP_ACCEPTED:
9305
9310
  return [3 /*break*/, 3];
9306
9311
  case HTTP_OK:
@@ -9313,12 +9318,12 @@ var mParticle = (function () {
9313
9318
  if (!response.json) return [3 /*break*/, 5];
9314
9319
  return [4 /*yield*/, response.json()];
9315
9320
  case 4:
9316
- responseBody = _b.sent();
9321
+ responseBody = _e.sent();
9317
9322
  identityResponse = this.getIdentityResponseFromFetch(response, responseBody);
9318
9323
  return [3 /*break*/, 6];
9319
9324
  case 5:
9320
9325
  identityResponse = this.getIdentityResponseFromXHR(response);
9321
- _b.label = 6;
9326
+ _e.label = 6;
9322
9327
  case 6:
9323
9328
  if (identityResponse.status === HTTP_BAD_REQUEST) {
9324
9329
  errorResponse = identityResponse.responseText;
@@ -9341,11 +9346,19 @@ var mParticle = (function () {
9341
9346
  case 8:
9342
9347
  mpInstance._Store.identityCallInFlight = false;
9343
9348
  Logger.verbose(message);
9349
+ if ((_b = mpInstance._RoktManager) === null || _b === void 0 ? void 0 : _b.isInitialized) {
9350
+ requestCount = mpInstance._Store.identifyRequestCount;
9351
+ mpInstance.captureTiming("".concat(requestCount, "-identityRequestEnd"));
9352
+ }
9344
9353
  parseIdentityResponse(identityResponse, previousMPID, callback, originalIdentityApiData, method, knownIdentities, false);
9345
9354
  return [3 /*break*/, 10];
9346
9355
  case 9:
9347
- err_1 = _b.sent();
9356
+ err_1 = _e.sent();
9348
9357
  mpInstance._Store.identityCallInFlight = false;
9358
+ if ((_c = mpInstance._RoktManager) === null || _c === void 0 ? void 0 : _c.isInitialized) {
9359
+ requestCount = mpInstance._Store.identifyRequestCount;
9360
+ mpInstance.captureTiming("".concat(requestCount, "-identityRequestEnd"));
9361
+ }
9349
9362
  errorMessage = err_1.message || err_1.toString();
9350
9363
  Logger.error('Error sending identity request to servers' + ' - ' + errorMessage);
9351
9364
  invokeCallback(callback, HTTPCodes$1.noHttpCoverage, errorMessage);
@@ -9695,6 +9708,7 @@ var mParticle = (function () {
9695
9708
  this.messageQueue = new Map();
9696
9709
  this.sandbox = null;
9697
9710
  this.placementAttributesMapping = [];
9711
+ this.initialized = false;
9698
9712
  }
9699
9713
  /**
9700
9714
  * Initializes the RoktManager with configuration settings and user data.
@@ -9744,7 +9758,18 @@ var mParticle = (function () {
9744
9758
  if (options === null || options === void 0 ? void 0 : options.domain) {
9745
9759
  this.domain = options.domain;
9746
9760
  }
9761
+ // initialized indicates that init() has been called and the RoktManager has been initialized.
9762
+ // This is different from isReady(), which only returns true once the kit has been attached
9763
+ // (which is asynchronous), and has a launcher.
9764
+ this.initialized = true;
9747
9765
  };
9766
+ Object.defineProperty(RoktManager.prototype, "isInitialized", {
9767
+ get: function get() {
9768
+ return this.initialized;
9769
+ },
9770
+ enumerable: false,
9771
+ configurable: true
9772
+ });
9748
9773
  RoktManager.prototype.attachKit = function (kit) {
9749
9774
  this.kit = kit;
9750
9775
  this.processMessageQueue();
@@ -9765,34 +9790,34 @@ var mParticle = (function () {
9765
9790
  * });
9766
9791
  */
9767
9792
  RoktManager.prototype.selectPlacements = function (options) {
9768
- var _a, _b;
9793
+ var _a, _b, _c, _d, _e;
9769
9794
  return __awaiter(this, void 0, void 0, function () {
9770
- var attributes, sandboxValue, mappedAttributes, currentUserIdentities_1, currentEmail, newEmail, currentHashedEmail, newHashedEmail, emailChanged, hashedEmailChanged, newIdentities_1, error_1, enrichedAttributes, enrichedOptions, error_2;
9795
+ var attributes, sandboxValue, mappedAttributes, currentUserIdentities_1, currentEmail, newEmail, currentHashedEmail, newHashedEmail, isValidHashedEmailIdentityType, emailChanged, hashedEmailChanged, newIdentities_1, error_1, finalUserIdentities, enrichedAttributes, hashedEmail, enrichedOptions, error_2;
9771
9796
  var _this = this;
9772
- return __generator(this, function (_c) {
9773
- switch (_c.label) {
9797
+ return __generator(this, function (_f) {
9798
+ switch (_f.label) {
9774
9799
  case 0:
9775
9800
  if (this.captureTiming) {
9776
9801
  this.captureTiming(PerformanceMarkType.JointSdkSelectPlacements);
9777
9802
  }
9778
- if (!this.isReady()) {
9803
+ // Queue if kit isn't ready OR if identity is in flight
9804
+ if (!this.isReady() || ((_a = this.store) === null || _a === void 0 ? void 0 : _a.identityCallInFlight)) {
9779
9805
  return [2 /*return*/, this.deferredCall('selectPlacements', options)];
9780
9806
  }
9781
- _c.label = 1;
9807
+ _f.label = 1;
9782
9808
  case 1:
9783
- _c.trys.push([1, 6,, 7]);
9809
+ _f.trys.push([1, 6,, 7]);
9784
9810
  attributes = options.attributes;
9785
9811
  sandboxValue = (attributes === null || attributes === void 0 ? void 0 : attributes.sandbox) || null;
9786
9812
  mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
9787
- // Get current user identities
9788
9813
  this.currentUser = this.identityService.getCurrentUser();
9789
- currentUserIdentities_1 = ((_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.getUserIdentities()) === null || _b === void 0 ? void 0 : _b.userIdentities) || {};
9814
+ currentUserIdentities_1 = ((_c = (_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.getUserIdentities()) === null || _c === void 0 ? void 0 : _c.userIdentities) || {};
9790
9815
  currentEmail = currentUserIdentities_1.email;
9791
9816
  newEmail = mappedAttributes.email;
9792
9817
  currentHashedEmail = void 0;
9793
9818
  newHashedEmail = void 0;
9794
- // Hashed email identity is valid if it is set to Other-Other10
9795
- if (this.mappedEmailShaIdentityType && IdentityType.getIdentityType(this.mappedEmailShaIdentityType) !== false) {
9819
+ isValidHashedEmailIdentityType = this.mappedEmailShaIdentityType && IdentityType.getIdentityType(this.mappedEmailShaIdentityType) !== false;
9820
+ if (isValidHashedEmailIdentityType) {
9796
9821
  currentHashedEmail = currentUserIdentities_1[this.mappedEmailShaIdentityType];
9797
9822
  newHashedEmail = mappedAttributes['emailsha256'] || mappedAttributes[this.mappedEmailShaIdentityType] || undefined;
9798
9823
  }
@@ -9810,9 +9835,9 @@ var mParticle = (function () {
9810
9835
  this.logger.warning("emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.");
9811
9836
  }
9812
9837
  if (!!isEmpty(newIdentities_1)) return [3 /*break*/, 5];
9813
- _c.label = 2;
9838
+ _f.label = 2;
9814
9839
  case 2:
9815
- _c.trys.push([2, 4,, 5]);
9840
+ _f.trys.push([2, 4,, 5]);
9816
9841
  return [4 /*yield*/, new Promise(function (resolve, reject) {
9817
9842
  _this.identityService.identify({
9818
9843
  userIdentities: __assign(__assign({}, currentUserIdentities_1), newIdentities_1)
@@ -9821,23 +9846,38 @@ var mParticle = (function () {
9821
9846
  });
9822
9847
  })];
9823
9848
  case 3:
9824
- _c.sent();
9849
+ _f.sent();
9825
9850
  return [3 /*break*/, 5];
9826
9851
  case 4:
9827
- error_1 = _c.sent();
9852
+ error_1 = _f.sent();
9828
9853
  this.logger.error('Failed to identify user with new email: ' + JSON.stringify(error_1));
9829
9854
  return [3 /*break*/, 5];
9830
9855
  case 5:
9856
+ // Refresh current user identities to ensure we have the latest values before building enrichedAttributes
9857
+ this.currentUser = this.identityService.getCurrentUser();
9858
+ finalUserIdentities = ((_e = (_d = this.currentUser) === null || _d === void 0 ? void 0 : _d.getUserIdentities()) === null || _e === void 0 ? void 0 : _e.userIdentities) || {};
9831
9859
  this.setUserAttributes(mappedAttributes);
9832
9860
  enrichedAttributes = __assign(__assign({}, mappedAttributes), sandboxValue !== null ? {
9833
9861
  sandbox: sandboxValue
9834
9862
  } : {});
9863
+ // Propagate email from current user identities if not already in attributes
9864
+ if (finalUserIdentities.email && !enrichedAttributes.email) {
9865
+ enrichedAttributes.email = finalUserIdentities.email;
9866
+ }
9867
+ // Propagate emailsha256 from current user identities if not already in attributes
9868
+ if (isValidHashedEmailIdentityType) {
9869
+ hashedEmail = finalUserIdentities[this.mappedEmailShaIdentityType];
9870
+ if (hashedEmail && !enrichedAttributes.emailsha256 && !enrichedAttributes[this.mappedEmailShaIdentityType]) {
9871
+ enrichedAttributes.emailsha256 = hashedEmail;
9872
+ }
9873
+ }
9874
+ this.filters.filteredUser = this.currentUser || this.filters.filteredUser || null;
9835
9875
  enrichedOptions = __assign(__assign({}, options), {
9836
9876
  attributes: enrichedAttributes
9837
9877
  });
9838
9878
  return [2 /*return*/, this.kit.selectPlacements(enrichedOptions)];
9839
9879
  case 6:
9840
- error_2 = _c.sent();
9880
+ error_2 = _f.sent();
9841
9881
  return [2 /*return*/, Promise.reject(error_2 instanceof Error ? error_2 : new Error('Unknown error occurred'))];
9842
9882
  case 7:
9843
9883
  return [2 /*return*/];
@@ -10010,6 +10050,13 @@ var mParticle = (function () {
10010
10050
  }
10011
10051
  return mappedAttributes;
10012
10052
  };
10053
+ RoktManager.prototype.onIdentityComplete = function () {
10054
+ if (this.isReady()) {
10055
+ this.currentUser = this.identityService.getCurrentUser();
10056
+ // Process any queued selectPlacements calls that were waiting for identity
10057
+ this.processMessageQueue();
10058
+ }
10059
+ };
10013
10060
  RoktManager.prototype.processMessageQueue = function () {
10014
10061
  var _this = this;
10015
10062
  var _a;
@@ -10017,24 +10064,39 @@ var mParticle = (function () {
10017
10064
  return;
10018
10065
  }
10019
10066
  (_a = this.logger) === null || _a === void 0 ? void 0 : _a.verbose("RoktManager: Processing ".concat(this.messageQueue.size, " queued messages"));
10020
- this.messageQueue.forEach(function (message) {
10021
- var _a, _b, _c;
10067
+ var messagesToProcess = Array.from(this.messageQueue.values());
10068
+ // Clear the queue immediately to prevent re-processing
10069
+ this.messageQueue.clear();
10070
+ messagesToProcess.forEach(function (message) {
10071
+ var _a, _b;
10022
10072
  if (!(message.methodName in _this) || !isFunction(_this[message.methodName])) {
10023
10073
  (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error("RoktManager: Method ".concat(message.methodName, " not found"));
10024
10074
  return;
10025
10075
  }
10026
10076
  (_b = _this.logger) === null || _b === void 0 ? void 0 : _b.verbose("RoktManager: Processing queued message: ".concat(message.methodName, " with payload: ").concat(JSON.stringify(message.payload)));
10077
+ // Capture resolve/reject functions before async processing
10078
+ var resolve = message.resolve;
10079
+ var reject = message.reject;
10080
+ var handleError = function handleError(error) {
10081
+ var _a;
10082
+ var errorMessage = error instanceof Error ? error.message : String(error);
10083
+ (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error("RoktManager: Error processing message '".concat(message.methodName, "': ").concat(errorMessage));
10084
+ if (reject) {
10085
+ reject(error);
10086
+ }
10087
+ };
10027
10088
  try {
10028
10089
  var result = _this[message.methodName](message.payload);
10029
- _this.completePendingPromise(message.messageId, result);
10090
+ // Handle both sync and async methods
10091
+ Promise.resolve(result).then(function (resolvedResult) {
10092
+ if (resolve) {
10093
+ resolve(resolvedResult);
10094
+ }
10095
+ })["catch"](handleError);
10030
10096
  } catch (error) {
10031
- var errorMessage = error instanceof Error ? error.message : String(error);
10032
- (_c = _this.logger) === null || _c === void 0 ? void 0 : _c.error("RoktManager: Error processing message '".concat(message.methodName, "': ").concat(errorMessage));
10033
- _this.completePendingPromise(message.messageId, Promise.reject(error));
10097
+ handleError(error);
10034
10098
  }
10035
10099
  });
10036
- // Clear the queue after processing all messages
10037
- this.messageQueue.clear();
10038
10100
  };
10039
10101
  RoktManager.prototype.queueMessage = function (message) {
10040
10102
  this.messageQueue.set(message.messageId, message);
@@ -10052,20 +10114,6 @@ var mParticle = (function () {
10052
10114
  });
10053
10115
  });
10054
10116
  };
10055
- RoktManager.prototype.completePendingPromise = function (messageId, resultOrError) {
10056
- if (!messageId || !this.messageQueue.has(messageId)) {
10057
- return;
10058
- }
10059
- var message = this.messageQueue.get(messageId);
10060
- if (message.resolve) {
10061
- Promise.resolve(resultOrError).then(function (result) {
10062
- return message.resolve(result);
10063
- })["catch"](function (error) {
10064
- return message.reject(error);
10065
- });
10066
- }
10067
- this.messageQueue["delete"](messageId);
10068
- };
10069
10117
  /**
10070
10118
  * Hashes a string input using SHA-256 and returns the hex digest
10071
10119
  * Uses the Web Crypto API for secure hashing
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.54.0",
3
+ "version": "2.55.0",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
package/src/identity.js CHANGED
@@ -1372,7 +1372,6 @@ export default function Identity(mpInstance) {
1372
1372
  : {};
1373
1373
  let mpidIsNotInCookies;
1374
1374
  let identityApiResult;
1375
-
1376
1375
  let newUser;
1377
1376
  let newIdentitiesByType = {};
1378
1377
 
@@ -1577,9 +1576,7 @@ export default function Identity(mpInstance) {
1577
1576
  }
1578
1577
  mpInstance._Store.isInitialized = true;
1579
1578
 
1580
- if (mpInstance._RoktManager.isReady()) {
1581
- mpInstance._RoktManager.currentUser = mpInstance.Identity.getCurrentUser();
1582
- }
1579
+ mpInstance._RoktManager.onIdentityComplete();
1583
1580
 
1584
1581
  mpInstance._preInit.readyQueue = processReadyQueue(
1585
1582
  mpInstance._preInit.readyQueue
@@ -193,6 +193,12 @@ export default function IdentityAPIClient(
193
193
  mpid: MPID,
194
194
  knownIdentities: UserIdentities
195
195
  ) {
196
+ if (mpInstance._RoktManager?.isInitialized) {
197
+ mpInstance._Store.identifyRequestCount = (mpInstance._Store.identifyRequestCount || 0) + 1;
198
+ const requestCount = mpInstance._Store.identifyRequestCount;
199
+ mpInstance.captureTiming(`${requestCount}-identityRequestStart`);
200
+ }
201
+
196
202
  const { invokeCallback } = mpInstance._Helpers;
197
203
  const { Logger } = mpInstance;
198
204
  Logger.verbose(Messages.InformationMessages.SendIdentityBegin);
@@ -289,6 +295,10 @@ export default function IdentityAPIClient(
289
295
  mpInstance._Store.identityCallInFlight = false;
290
296
 
291
297
  Logger.verbose(message);
298
+ if (mpInstance._RoktManager?.isInitialized) {
299
+ const requestCount = mpInstance._Store.identifyRequestCount;
300
+ mpInstance.captureTiming(`${requestCount}-identityRequestEnd`);
301
+ }
292
302
  parseIdentityResponse(
293
303
  identityResponse,
294
304
  previousMPID,
@@ -300,6 +310,10 @@ export default function IdentityAPIClient(
300
310
  );
301
311
  } catch (err) {
302
312
  mpInstance._Store.identityCallInFlight = false;
313
+ if (mpInstance._RoktManager?.isInitialized) {
314
+ const requestCount = mpInstance._Store.identifyRequestCount;
315
+ mpInstance.captureTiming(`${requestCount}-identityRequestEnd`);
316
+ }
303
317
 
304
318
  const errorMessage = (err as Error).message || err.toString();
305
319
 
@@ -102,6 +102,7 @@ export default class RoktManager {
102
102
  private domain?: string;
103
103
  private mappedEmailShaIdentityType?: string | null;
104
104
  private captureTiming?: (metricsName: string) => void;
105
+ private initialized: boolean = false;
105
106
  /**
106
107
  * Initializes the RoktManager with configuration settings and user data.
107
108
  *
@@ -157,6 +158,14 @@ export default class RoktManager {
157
158
  if (options?.domain) {
158
159
  this.domain = options.domain;
159
160
  }
161
+ // initialized indicates that init() has been called and the RoktManager has been initialized.
162
+ // This is different from isReady(), which only returns true once the kit has been attached
163
+ // (which is asynchronous), and has a launcher.
164
+ this.initialized = true;
165
+ }
166
+
167
+ public get isInitialized(): boolean {
168
+ return this.initialized;
160
169
  }
161
170
 
162
171
  public attachKit(kit: IRoktKit): void {
@@ -184,7 +193,8 @@ export default class RoktManager {
184
193
  this.captureTiming(PerformanceMarkType.JointSdkSelectPlacements);
185
194
  }
186
195
 
187
- if (!this.isReady()) {
196
+ // Queue if kit isn't ready OR if identity is in flight
197
+ if (!this.isReady() || this.store?.identityCallInFlight) {
188
198
  return this.deferredCall<IRoktSelection>('selectPlacements', options);
189
199
  }
190
200
 
@@ -192,8 +202,7 @@ export default class RoktManager {
192
202
  const { attributes } = options;
193
203
  const sandboxValue = attributes?.sandbox || null;
194
204
  const mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
195
-
196
- // Get current user identities
205
+
197
206
  this.currentUser = this.identityService.getCurrentUser();
198
207
  const currentUserIdentities = this.currentUser?.getUserIdentities()?.userIdentities || {};
199
208
 
@@ -204,9 +213,16 @@ export default class RoktManager {
204
213
  let newHashedEmail: string | undefined;
205
214
 
206
215
  // Hashed email identity is valid if it is set to Other-Other10
207
- if(this.mappedEmailShaIdentityType && IdentityType.getIdentityType(this.mappedEmailShaIdentityType) !== false) {
216
+ const isValidHashedEmailIdentityType =
217
+ this.mappedEmailShaIdentityType &&
218
+ IdentityType.getIdentityType(this.mappedEmailShaIdentityType) !== false;
219
+
220
+ if (isValidHashedEmailIdentityType) {
208
221
  currentHashedEmail = currentUserIdentities[this.mappedEmailShaIdentityType];
209
- newHashedEmail = mappedAttributes['emailsha256'] as string || mappedAttributes[this.mappedEmailShaIdentityType] as string || undefined;
222
+ newHashedEmail =
223
+ (mappedAttributes['emailsha256'] as string) ||
224
+ (mappedAttributes[this.mappedEmailShaIdentityType] as string) ||
225
+ undefined;
210
226
  }
211
227
 
212
228
  const emailChanged = this.hasIdentityChanged(currentEmail, newEmail);
@@ -242,14 +258,37 @@ export default class RoktManager {
242
258
  this.logger.error('Failed to identify user with new email: ' + JSON.stringify(error));
243
259
  }
244
260
  }
261
+
262
+ // Refresh current user identities to ensure we have the latest values before building enrichedAttributes
263
+ this.currentUser = this.identityService.getCurrentUser();
264
+ const finalUserIdentities = this.currentUser?.getUserIdentities()?.userIdentities || {};
245
265
 
246
266
  this.setUserAttributes(mappedAttributes);
247
267
 
248
- const enrichedAttributes = {
268
+ const enrichedAttributes: RoktAttributes = {
249
269
  ...mappedAttributes,
250
270
  ...(sandboxValue !== null ? { sandbox: sandboxValue } : {}),
251
271
  };
252
272
 
273
+ // Propagate email from current user identities if not already in attributes
274
+ if (finalUserIdentities.email && !enrichedAttributes.email) {
275
+ enrichedAttributes.email = finalUserIdentities.email;
276
+ }
277
+
278
+ // Propagate emailsha256 from current user identities if not already in attributes
279
+ if (isValidHashedEmailIdentityType) {
280
+ const hashedEmail = finalUserIdentities[this.mappedEmailShaIdentityType];
281
+ if (
282
+ hashedEmail &&
283
+ !enrichedAttributes.emailsha256 &&
284
+ !enrichedAttributes[this.mappedEmailShaIdentityType]
285
+ ) {
286
+ enrichedAttributes.emailsha256 = hashedEmail;
287
+ }
288
+ }
289
+
290
+ this.filters.filteredUser = this.currentUser || this.filters.filteredUser || null;
291
+
253
292
  const enrichedOptions = {
254
293
  ...options,
255
294
  attributes: enrichedAttributes,
@@ -405,6 +444,14 @@ export default class RoktManager {
405
444
  return mappedAttributes;
406
445
  }
407
446
 
447
+ public onIdentityComplete(): void {
448
+ if (this.isReady()) {
449
+ this.currentUser = this.identityService.getCurrentUser();
450
+ // Process any queued selectPlacements calls that were waiting for identity
451
+ this.processMessageQueue();
452
+ }
453
+ }
454
+
408
455
  private processMessageQueue(): void {
409
456
  if (!this.isReady() || this.messageQueue.size === 0) {
410
457
  return;
@@ -412,7 +459,12 @@ export default class RoktManager {
412
459
 
413
460
  this.logger?.verbose(`RoktManager: Processing ${this.messageQueue.size} queued messages`);
414
461
 
415
- this.messageQueue.forEach((message) => {
462
+ const messagesToProcess = Array.from(this.messageQueue.values());
463
+
464
+ // Clear the queue immediately to prevent re-processing
465
+ this.messageQueue.clear();
466
+
467
+ messagesToProcess.forEach((message) => {
416
468
  if(!(message.methodName in this) || !isFunction(this[message.methodName])) {
417
469
  this.logger?.error(`RoktManager: Method ${message.methodName} not found`);
418
470
 
@@ -421,18 +473,32 @@ export default class RoktManager {
421
473
 
422
474
  this.logger?.verbose(`RoktManager: Processing queued message: ${message.methodName} with payload: ${JSON.stringify(message.payload)}`);
423
475
 
476
+ // Capture resolve/reject functions before async processing
477
+ const resolve = message.resolve;
478
+ const reject = message.reject;
479
+
480
+ const handleError = (error: unknown) => {
481
+ const errorMessage = error instanceof Error ? error.message : String(error);
482
+ this.logger?.error(`RoktManager: Error processing message '${message.methodName}': ${errorMessage}`);
483
+ if (reject) {
484
+ reject(error);
485
+ }
486
+ };
487
+
424
488
  try {
425
489
  const result = (this[message.methodName] as Function)(message.payload);
426
- this.completePendingPromise(message.messageId, result);
490
+ // Handle both sync and async methods
491
+ Promise.resolve(result)
492
+ .then((resolvedResult) => {
493
+ if (resolve) {
494
+ resolve(resolvedResult);
495
+ }
496
+ })
497
+ .catch(handleError);
427
498
  } catch (error) {
428
- const errorMessage = error instanceof Error ? error.message : String(error);
429
- this.logger?.error(`RoktManager: Error processing message '${message.methodName}': ${errorMessage}`);
430
- this.completePendingPromise(message.messageId, Promise.reject(error));
499
+ handleError(error);
431
500
  }
432
501
  });
433
-
434
- // Clear the queue after processing all messages
435
- this.messageQueue.clear();
436
502
  }
437
503
 
438
504
  private queueMessage(message: IRoktMessage): void {
@@ -453,22 +519,6 @@ export default class RoktManager {
453
519
  });
454
520
  }
455
521
 
456
- private completePendingPromise(messageId: string | undefined, resultOrError: any): void {
457
- if (!messageId || !this.messageQueue.has(messageId)) {
458
- return;
459
- }
460
-
461
- const message = this.messageQueue.get(messageId)!;
462
-
463
- if (message.resolve) {
464
- Promise.resolve(resultOrError)
465
- .then((result) => message.resolve!(result))
466
- .catch((error) => message.reject!(error));
467
- }
468
-
469
- this.messageQueue.delete(messageId);
470
- }
471
-
472
522
  /**
473
523
  * Hashes a string input using SHA-256 and returns the hex digest
474
524
  * Uses the Web Crypto API for secure hashing
package/src/store.ts CHANGED
@@ -182,6 +182,7 @@ export interface IStore {
182
182
  context: Context | null;
183
183
  configurationLoaded: boolean;
184
184
  identityCallInFlight: boolean;
185
+ identifyRequestCount: number;
185
186
  SDKConfig: Partial<SDKConfig>;
186
187
  nonCurrentUserMPIDs: Record<MPID, Dictionary>;
187
188
  identifyCalled: boolean;
@@ -266,6 +267,7 @@ export default function Store(
266
267
  context: null,
267
268
  configurationLoaded: false,
268
269
  identityCallInFlight: false,
270
+ identifyRequestCount: 0,
269
271
  SDKConfig: {},
270
272
  nonCurrentUserMPIDs: {},
271
273
  identifyCalled: false,