@mparticle/web-sdk 2.39.1 → 2.41.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.39.1";
18
+ var version = "2.41.0";
19
19
 
20
20
  var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
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/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
@@ -1265,7 +1265,7 @@ return t._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===s.audie
1265
1265
  * @deprecated
1266
1266
  */getCartProducts:function getCartProducts(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().getCartProducts() will be removed in future releases"),t._Persistence.getCartProducts(e)}}},this.parseIdentityResponse=function(r,i,a,d,o,g,l){var u,p,y,c=t.Identity.getUser(i),I=c?c.getMPID():null,_=c?c.getUserIdentities().userIdentities:{},v={};t._Store.identityCallInFlight=!1;try{var m,S,b;if(t.Logger.verbose("Parsing \""+o+"\" identity response from server"),p=null!==(m=r.responseText)&&void 0!==m?m:null,t._Store.isLoggedIn=(null===(S=p)||void 0===S?void 0:S.is_logged_in)||!1,hasMPIDChanged(c,p)&&(t._Store.mpid=p.mpid,c&&t._Persistence.setLastSeenTime(i),u=!t._Persistence.getFirstSeenTime(p.mpid),t._Persistence.setFirstSeenTime(p.mpid)),r.status===HTTP_OK){s(CacheIdentity)&&cacheOrClearIdCache(o,g,n.idCache,r,l);var A=n.IdentityAPI.getUser(p.mpid),P=A?A.getUserIdentities().userIdentities:{};o===Modify$1?(v=t._Identity.IdentityRequest.combineUserIdentities(_,d.userIdentities),t._Store.setUserIdentities(i,v)):(o===Identify&&c&&p.mpid===I&&t._Persistence.setFirstSeenTime(p.mpid),t._Store.addMpidToSessionHistory(p.mpid,i),t._CookieSyncManager.attemptCookieSync(p.mpid,u),t._Persistence.swapCurrentUser(i,p.mpid,t._Store.currentSessionMPIDs),d&&!isEmpty(d.userIdentities)&&(v=n.IdentityRequest.combineUserIdentities(P,d.userIdentities)),t._Store.setUserIdentities(p.mpid,v),t._Persistence.update(),t._Store.syncPersistenceData(),t._Persistence.findPrevCookiesBasedOnUI(d),t._Store.context=p.context||t._Store.context),y=t.Identity.getCurrentUser(),tryOnUserAlias(c,y,d,t.Logger);var U=t._Persistence.getPersistence();y&&(t._Persistence.storeDataInMemory(U,y.getMPID()),n.reinitForwardersOnUserChange(c,y),n.setForwarderCallbacks(y,o));var C=IdentityType.getNewIdentitiesByName(v),k=o===Modify$1?_:P;// https://go.mparticle.com/work/SQDSDKS-6501
1267
1267
  n.sendUserIdentityChangeEvent(C,o,p.mpid,k);}if(a){var f=0===r.status?HTTPCodes$2.noHttpCoverage:r.status;t._Helpers.invokeCallback(a,f,p||null,y);}else p&&!isEmpty(p.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
1268
- t.Logger.error("Received HTTP response code of "+r.status+" - "+p.errors[0].message);t.Logger.verbose("Successfully parsed Identity Response"),null===(b=t._APIClient)||void 0===b||b.processQueuedEvents();}catch(s){a&&t._Helpers.invokeCallback(a,r.status,p||null),t.Logger.error("Error parsing JSON response from Identity server: "+s);}t._Store.isInitialized=!0,t._preInit.readyQueue=processReadyQueue(t._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(e,r,s,i){if(s||r===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1268
+ t.Logger.error("Received HTTP response code of "+r.status+" - "+p.errors[0].message);t.Logger.verbose("Successfully parsed Identity Response"),null===(b=t._APIClient)||void 0===b||b.processQueuedEvents();}catch(s){a&&t._Helpers.invokeCallback(a,r.status,p||null),t.Logger.error("Error parsing JSON response from Identity server: "+s);}t._Store.isInitialized=!0,t._RoktManager.isReady()&&(t._RoktManager.currentUser=t.Identity.getCurrentUser()),t._preInit.readyQueue=processReadyQueue(t._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(e,r,s,i){if(s||r===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1269
1269
  {// https://go.mparticle.com/work/SQDSDKS-6354
1270
1270
  var a=this.IdentityAPI.getUser(s);for(var d in e)// Verifies a change actually happened
1271
1271
  if(i[d]!==e[d]){var o,g=!i[d],l=n.createUserIdentityChange(d,e[d],i[d],g,a);// If a new identity type was introduced when the identity changes
@@ -1417,16 +1417,17 @@ for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickI
1417
1417
  // Rokt Manager in a "ready" state and it can begin sending data to the kit.
1418
1418
  //
1419
1419
  // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
1420
- var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.filteredUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1420
+ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1421
1421
  * Initializes the RoktManager with configuration settings and user data.
1422
1422
  *
1423
1423
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
1424
1424
  * @param {IMParticleUser} filteredUser - User object with filtered attributes
1425
- * @param {IMParticleUser} currentUser - Current mParticle user object
1426
- * @param {IRoktManagerOptions} options - Options for the RoktManager
1425
+ * @param {SDKIdentityApi} identityService - The mParticle Identity instance
1426
+ * @param {SDKLoggerApi} logger - The mParticle Logger instance
1427
+ * @param {IRoktOptions} options - Options for the RoktManager
1427
1428
  *
1428
1429
  * @throws Logs error to console if placementAttributesMapping parsing fails
1429
- */return a.prototype.init=function(a,b,c,d){var e=a||{},f=e.userAttributeFilters,g=e.settings,h=(g||{}).placementAttributesMapping;try{this.placementAttributesMapping=parseSettingsString(h);}catch(a){console.error("Error parsing placement attributes mapping from config",a);}this.currentUser=c,this.filters={userAttributeFilters:f,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b},this.sandbox=null===d||void 0===d?void 0:d.sandbox;},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b;if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),Promise.resolve({});try{var c=a.attributes,d=null!==(b=null===c||void 0===c?void 0:c.sandbox)&&void 0!==b?b:this.sandbox,e=this.mapPlacementAttributes(c,this.placementAttributesMapping);this.setUserAttributes(e);var f=__assign(__assign({},e),null===d?{}:{sandbox:d}),g=__assign(__assign({},a),{attributes:f});return this.kit.selectPlacements(g)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.queueMessage({methodName:"hashAttributes",payload:a}),Promise.resolve({});try{return this.kit.hashAttributes(a)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.queueMessage({methodName:"setExtensionData",payload: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.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1430
+ */return a.prototype.init=function(a,b,c,d,e){var f,g=a||{},h=g.userAttributeFilters,i=g.settings,j=(i||{}).placementAttributesMapping;try{this.placementAttributesMapping=parseSettingsString(j);}catch(a){console.error("Error parsing placement attributes mapping from config",a);}this.identityService=c,this.logger=d,this.filters={userAttributeFilters:h,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b},this.sandbox=null===(f=null===e||void 0===e?void 0:e.managerOptions)||void 0===f?void 0:f.sandbox,this.launcherOptions=null===e||void 0===e?void 0:e.launcherOptions;},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=this;return __generator(this,function(o){switch(o.label){case 0:if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),[2/*return*/,Promise.resolve({})];o.label=1;case 1:if(o.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,!i||h&&h===i)return [3/*break*/,5];h&&h!==i&&this.logger.warning("Email mismatch detected. Current email, ".concat(h," differs from email passed to selectPlacements call, ").concat(i,". Proceeding to call identify with ").concat(i,". Please verify your implementation.")),o.label=2;case 2:return o.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){n.identityService.identify({userIdentities:__assign(__assign({},g),{email:i})},function(){a();});})];case 3:return o.sent(),[3/*break*/,5];case 4:return j=o.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(j)),[3/*break*/,5];case 5:return this.setUserAttributes(f),k=__assign(__assign({},f),null===e?{}:{sandbox:e}),l=__assign(__assign({},a),{attributes:k}),[2/*return*/,this.kit.selectPlacements(l)];case 6:return m=o.sent(),[2/*return*/,Promise.reject(m instanceof Error?m:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.queueMessage({methodName:"hashAttributes",payload:a}),Promise.resolve({});try{return this.kit.hashAttributes(a)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.queueMessage({methodName:"setExtensionData",payload: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.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1430
1431
  return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)a.hasOwnProperty(d)&&-1===b.indexOf(d)&&(c[d]=a[d]);try{this.currentUser.setUserAttributes(c);}catch(a){console.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=this;0<this.messageQueue.length&&this.isReady()&&(this.messageQueue.forEach(function(b){return __awaiter(a,void 0,void 0,function(){return __generator(this,function(a){switch(a.label){case 0:return this.kit&&b.methodName in this.kit?[4/*yield*/,this.kit[b.methodName](b.payload)]:[3/*break*/,2];case 1:a.sent(),a.label=2;case 2:return [2/*return*/]}})})}),this.messageQueue=[]);},a.prototype.queueMessage=function(a){this.messageQueue.push(a);},a}();
1431
1432
 
1432
1433
  var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
@@ -1765,7 +1766,8 @@ function completeSDKInitialization(a,b,c){var d=createKitBlocker(b,c);// Web Vie
1765
1766
  // persistence or Identity directly.
1766
1767
  if(c._APIClient=new APIClient(c,d),c._Forwarders=new Forwarders(c,d),c._Store.processConfig(b),c._Identity.idCache=createIdentityCache(c),removeExpiredIdentityCacheDates(c._Identity.idCache),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.initializeSessionAttributes(a);else {c._Persistence.initializeStorage(),c._Store.syncPersistenceData();// Set up user identitiy variables for later use
1767
1768
  var e=c.Identity.getCurrentUser(),f=e?e.getMPID():null,g=e?e.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:g}:c._Store.SDKConfig.identifyRequest,c._Helpers.getFeatureFlag(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer(),c._Helpers.getFeatureFlag(CaptureIntegrationSpecificIds)&&c._IntegrationCapture.capture();// Configure Rokt Manager with user and filtered user
1768
- var h=parseConfig(b,"Rokt",181);if(h){var i=h.userAttributeFilters,j=filteredMparticleUser(f,{userAttributeFilters:i},c),k={sandbox:b.isDevelopmentMode};c._RoktManager.init(h,j,e,k);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,e,f,g);}// We will continue to clear out the ready queue as part of the initial init flow
1769
+ var h=parseConfig(b,"Rokt",181);if(h){var i=h.userAttributeFilters,j=filteredMparticleUser(f,{userAttributeFilters:i},c),k={managerOptions:{sandbox:b.isDevelopmentMode},launcherOptions:null===b||void 0===b?void 0:b.launcherOptions};// https://go.mparticle.com/work/SQDSDKS-7339
1770
+ c._RoktManager.init(h,j,c.Identity,c.Logger,k);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,e,f,g);}// We will continue to clear out the ready queue as part of the initial init flow
1769
1771
  // if an identify request is unnecessary, such as if there is an existing session
1770
1772
  (c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue)),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061
1771
1773
  function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK:
@@ -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.39.1";
18
+ var version = "2.41.0";
19
19
 
20
20
  var Constants={sdkVersion:version,sdkVendor:"mparticle",platform:"web",Messages:{DeprecationMessages:{MethodIsDeprecatedPostfix:"is a deprecated method and will be removed in future releases",AlternativeMethodPrefix:"Please use the alternate method:"},ErrorMessages:{NoToken:"A token must be specified.",EventNameInvalidType:"Event name must be a valid string value.",EventDataInvalidType:"Event data must be a valid object hash.",LoggingDisabled:"Event logging is currently disabled.",CookieParseError:"Could not parse cookie",EventEmpty:"Event object is null or undefined, cancelling send",APIRequestEmpty:"APIRequest is null or undefined, cancelling send",NoEventType:"Event type must be specified.",TransactionIdRequired:"Transaction ID is required",TransactionRequired:"A transaction attributes object is required",PromotionIdRequired:"Promotion ID is required",BadAttribute:"Attribute value cannot be object or array",BadKey:"Key value cannot be object or array",BadLogPurchase:"Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",AudienceAPINotEnabled:"Your workspace is not enabled to retrieve user audiences."},InformationMessages:{CookieSearch:"Searching for cookie",CookieFound:"Cookie found, parsing values",CookieNotFound:"Cookies not found",CookieSet:"Setting cookie",CookieSync:"Performing cookie sync",SendBegin:"Starting to send event",SendIdentityBegin:"Starting to send event to identity server",SendWindowsPhone:"Sending event to Windows Phone container",SendIOS:"Calling iOS path: ",SendAndroid:"Calling Android JS interface method: ",SendHttp:"Sending event to mParticle HTTP service",SendAliasHttp:"Sending alias request to mParticle HTTP service",SendIdentityHttp:"Sending event to mParticle HTTP service",StartingNewSession:"Starting new Session",StartingLogEvent:"Starting to log event",StartingLogOptOut:"Starting to log user opt in/out",StartingEndSession:"Starting to end session",StartingInitialization:"Starting to initialize",StartingLogCommerceEvent:"Starting to log commerce event",StartingAliasRequest:"Starting to Alias MPIDs",LoadingConfig:"Loading configuration options",AbandonLogEvent:"Cannot log event, logging disabled or developer token not set",AbandonAliasUsers:"Cannot Alias Users, logging disabled or developer token not set",AbandonStartSession:"Cannot start session, logging disabled or developer token not set",AbandonEndSession:"Cannot end session, logging disabled or developer token not set",NoSessionToEnd:"Cannot end session, no active session found"},ValidationMessages:{ModifyIdentityRequestUserIdentitiesPresent:"identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",IdentityRequesetInvalidKey:"There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",OnUserAliasType:"The onUserAlias value must be a function.",UserIdentities:"The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidKey:"There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",UserIdentitiesInvalidValues:"All user identity values must be strings or null. Request not sent to server. Please fix and try again.",AliasMissingMpid:"Alias Request must contain both a destinationMpid and a sourceMpid",AliasNonUniqueMpid:"Alias Request's destinationMpid and sourceMpid must be unique",AliasMissingTime:"Alias Request must have both a startTime and an endTime",AliasStartBeforeEndTime:"Alias Request's endTime must be later than its startTime"}},NativeSdkPaths:{LogEvent:"logEvent",SetUserTag:"setUserTag",RemoveUserTag:"removeUserTag",SetUserAttribute:"setUserAttribute",RemoveUserAttribute:"removeUserAttribute",SetSessionAttribute:"setSessionAttribute",AddToCart:"addToCart",RemoveFromCart:"removeFromCart",ClearCart:"clearCart",LogOut:"logOut",SetUserAttributeList:"setUserAttributeList",RemoveAllUserAttributes:"removeAllUserAttributes",GetUserAttributesLists:"getUserAttributesLists",GetAllUserAttributes:"getAllUserAttributes",Identify:"identify",Logout:"logout",Login:"login",Modify:"modify",Alias:"aliasUsers",Upload:"upload"},StorageNames:{localStorageName:"mprtcl-api",localStorageNameV3:"mprtcl-v3",cookieName:"mprtcl-api",cookieNameV2:"mprtcl-v2",cookieNameV3:"mprtcl-v3",localStorageNameV4:"mprtcl-v4",localStorageProductsV4:"mprtcl-prodv4",cookieNameV4:"mprtcl-v4",currentStorageName:"mprtcl-v4",currentStorageProductsName:"mprtcl-prodv4"},DefaultConfig:{cookieDomain:null,cookieExpiration:365,logLevel:null,timeout:300,sessionTimeout:30,maxProducts:20,forwarderStatsTimeout:5e3,integrationDelayTimeout:5e3,maxCookieSize:3e3,aliasMaxWindow:90,uploadInterval:0// Maximum milliseconds in between batch uploads, below 500 will mean immediate upload. The server returns this as a string, but we are using it as a number internally
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/"},Base64CookieKeys:{csm:1,sa:1,ss:1,ua:1,ui:1,csd:1,ia:1,con:1},// https://go.mparticle.com/work/SQDSDKS-6039
@@ -1265,7 +1265,7 @@ return t._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===s.audie
1265
1265
  * @deprecated
1266
1266
  */getCartProducts:function getCartProducts(){return t.Logger.warning("Deprecated function Identity.getCurrentUser().getCart().getCartProducts() will be removed in future releases"),t._Persistence.getCartProducts(e)}}},this.parseIdentityResponse=function(r,i,a,d,o,g,l){var u,p,y,c=t.Identity.getUser(i),I=c?c.getMPID():null,_=c?c.getUserIdentities().userIdentities:{},v={};t._Store.identityCallInFlight=!1;try{var m,S,b;if(t.Logger.verbose("Parsing \""+o+"\" identity response from server"),p=null!==(m=r.responseText)&&void 0!==m?m:null,t._Store.isLoggedIn=(null===(S=p)||void 0===S?void 0:S.is_logged_in)||!1,hasMPIDChanged(c,p)&&(t._Store.mpid=p.mpid,c&&t._Persistence.setLastSeenTime(i),u=!t._Persistence.getFirstSeenTime(p.mpid),t._Persistence.setFirstSeenTime(p.mpid)),r.status===HTTP_OK){s(CacheIdentity)&&cacheOrClearIdCache(o,g,n.idCache,r,l);var A=n.IdentityAPI.getUser(p.mpid),P=A?A.getUserIdentities().userIdentities:{};o===Modify$1?(v=t._Identity.IdentityRequest.combineUserIdentities(_,d.userIdentities),t._Store.setUserIdentities(i,v)):(o===Identify&&c&&p.mpid===I&&t._Persistence.setFirstSeenTime(p.mpid),t._Store.addMpidToSessionHistory(p.mpid,i),t._CookieSyncManager.attemptCookieSync(p.mpid,u),t._Persistence.swapCurrentUser(i,p.mpid,t._Store.currentSessionMPIDs),d&&!isEmpty(d.userIdentities)&&(v=n.IdentityRequest.combineUserIdentities(P,d.userIdentities)),t._Store.setUserIdentities(p.mpid,v),t._Persistence.update(),t._Store.syncPersistenceData(),t._Persistence.findPrevCookiesBasedOnUI(d),t._Store.context=p.context||t._Store.context),y=t.Identity.getCurrentUser(),tryOnUserAlias(c,y,d,t.Logger);var U=t._Persistence.getPersistence();y&&(t._Persistence.storeDataInMemory(U,y.getMPID()),n.reinitForwardersOnUserChange(c,y),n.setForwarderCallbacks(y,o));var C=IdentityType.getNewIdentitiesByName(v),k=o===Modify$1?_:P;// https://go.mparticle.com/work/SQDSDKS-6501
1267
1267
  n.sendUserIdentityChangeEvent(C,o,p.mpid,k);}if(a){var f=0===r.status?HTTPCodes$2.noHttpCoverage:r.status;t._Helpers.invokeCallback(a,f,p||null,y);}else p&&!isEmpty(p.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
1268
- t.Logger.error("Received HTTP response code of "+r.status+" - "+p.errors[0].message);t.Logger.verbose("Successfully parsed Identity Response"),null===(b=t._APIClient)||void 0===b||b.processQueuedEvents();}catch(s){a&&t._Helpers.invokeCallback(a,r.status,p||null),t.Logger.error("Error parsing JSON response from Identity server: "+s);}t._Store.isInitialized=!0,t._preInit.readyQueue=processReadyQueue(t._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(e,r,s,i){if(s||r===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1268
+ t.Logger.error("Received HTTP response code of "+r.status+" - "+p.errors[0].message);t.Logger.verbose("Successfully parsed Identity Response"),null===(b=t._APIClient)||void 0===b||b.processQueuedEvents();}catch(s){a&&t._Helpers.invokeCallback(a,r.status,p||null),t.Logger.error("Error parsing JSON response from Identity server: "+s);}t._Store.isInitialized=!0,t._RoktManager.isReady()&&(t._RoktManager.currentUser=t.Identity.getCurrentUser()),t._preInit.readyQueue=processReadyQueue(t._preInit.readyQueue);},this.sendUserIdentityChangeEvent=function(e,r,s,i){if(s||r===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1269
1269
  {// https://go.mparticle.com/work/SQDSDKS-6354
1270
1270
  var a=this.IdentityAPI.getUser(s);for(var d in e)// Verifies a change actually happened
1271
1271
  if(i[d]!==e[d]){var o,g=!i[d],l=n.createUserIdentityChange(d,e[d],i[d],g,a);// If a new identity type was introduced when the identity changes
@@ -1417,16 +1417,17 @@ for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickI
1417
1417
  // Rokt Manager in a "ready" state and it can begin sending data to the kit.
1418
1418
  //
1419
1419
  // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
1420
- var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.filteredUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1420
+ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1421
1421
  * Initializes the RoktManager with configuration settings and user data.
1422
1422
  *
1423
1423
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
1424
1424
  * @param {IMParticleUser} filteredUser - User object with filtered attributes
1425
- * @param {IMParticleUser} currentUser - Current mParticle user object
1426
- * @param {IRoktManagerOptions} options - Options for the RoktManager
1425
+ * @param {SDKIdentityApi} identityService - The mParticle Identity instance
1426
+ * @param {SDKLoggerApi} logger - The mParticle Logger instance
1427
+ * @param {IRoktOptions} options - Options for the RoktManager
1427
1428
  *
1428
1429
  * @throws Logs error to console if placementAttributesMapping parsing fails
1429
- */return a.prototype.init=function(a,b,c,d){var e=a||{},f=e.userAttributeFilters,g=e.settings,h=(g||{}).placementAttributesMapping;try{this.placementAttributesMapping=parseSettingsString(h);}catch(a){console.error("Error parsing placement attributes mapping from config",a);}this.currentUser=c,this.filters={userAttributeFilters:f,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b},this.sandbox=null===d||void 0===d?void 0:d.sandbox;},a.prototype.attachKit=function(a){this.kit=a,this.processMessageQueue();},a.prototype.selectPlacements=function(a){var b;if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),Promise.resolve({});try{var c=a.attributes,d=null!==(b=null===c||void 0===c?void 0:c.sandbox)&&void 0!==b?b:this.sandbox,e=this.mapPlacementAttributes(c,this.placementAttributesMapping);this.setUserAttributes(e);var f=__assign(__assign({},e),null===d?{}:{sandbox:d}),g=__assign(__assign({},a),{attributes:f});return this.kit.selectPlacements(g)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.queueMessage({methodName:"hashAttributes",payload:a}),Promise.resolve({});try{return this.kit.hashAttributes(a)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.queueMessage({methodName:"setExtensionData",payload: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.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1430
+ */return a.prototype.init=function(a,b,c,d,e){var f,g=a||{},h=g.userAttributeFilters,i=g.settings,j=(i||{}).placementAttributesMapping;try{this.placementAttributesMapping=parseSettingsString(j);}catch(a){console.error("Error parsing placement attributes mapping from config",a);}this.identityService=c,this.logger=d,this.filters={userAttributeFilters:h,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b},this.sandbox=null===(f=null===e||void 0===e?void 0:e.managerOptions)||void 0===f?void 0:f.sandbox,this.launcherOptions=null===e||void 0===e?void 0:e.launcherOptions;},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=this;return __generator(this,function(o){switch(o.label){case 0:if(!this.isReady())return this.queueMessage({methodName:"selectPlacements",payload:a}),[2/*return*/,Promise.resolve({})];o.label=1;case 1:if(o.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,!i||h&&h===i)return [3/*break*/,5];h&&h!==i&&this.logger.warning("Email mismatch detected. Current email, ".concat(h," differs from email passed to selectPlacements call, ").concat(i,". Proceeding to call identify with ").concat(i,". Please verify your implementation.")),o.label=2;case 2:return o.trys.push([2,4,,5]),[4/*yield*/,new Promise(function(a){n.identityService.identify({userIdentities:__assign(__assign({},g),{email:i})},function(){a();});})];case 3:return o.sent(),[3/*break*/,5];case 4:return j=o.sent(),this.logger.error("Failed to identify user with new email: "+JSON.stringify(j)),[3/*break*/,5];case 5:return this.setUserAttributes(f),k=__assign(__assign({},f),null===e?{}:{sandbox:e}),l=__assign(__assign({},a),{attributes:k}),[2/*return*/,this.kit.selectPlacements(l)];case 6:return m=o.sent(),[2/*return*/,Promise.reject(m instanceof Error?m:new Error("Unknown error occurred"))];case 7:return [2/*return*/]}})})},a.prototype.hashAttributes=function(a){if(!this.isReady())return this.queueMessage({methodName:"hashAttributes",payload:a}),Promise.resolve({});try{return this.kit.hashAttributes(a)}catch(a){return Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))}},a.prototype.setExtensionData=function(a){if(!this.isReady())return void this.queueMessage({methodName:"setExtensionData",payload: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.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1430
1431
  return !!(this.kit&&this.kit.launcher)},a.prototype.setUserAttributes=function(a){var b=["sandbox"],c={};for(var d in a)a.hasOwnProperty(d)&&-1===b.indexOf(d)&&(c[d]=a[d]);try{this.currentUser.setUserAttributes(c);}catch(a){console.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=this;0<this.messageQueue.length&&this.isReady()&&(this.messageQueue.forEach(function(b){return __awaiter(a,void 0,void 0,function(){return __generator(this,function(a){switch(a.label){case 0:return this.kit&&b.methodName in this.kit?[4/*yield*/,this.kit[b.methodName](b.payload)]:[3/*break*/,2];case 1:a.sent(),a.label=2;case 2:return [2/*return*/]}})})}),this.messageQueue=[]);},a.prototype.queueMessage=function(a){this.messageQueue.push(a);},a}();
1431
1432
 
1432
1433
  var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
@@ -1765,7 +1766,8 @@ function completeSDKInitialization(a,b,c){var d=createKitBlocker(b,c);// Web Vie
1765
1766
  // persistence or Identity directly.
1766
1767
  if(c._APIClient=new APIClient(c,d),c._Forwarders=new Forwarders(c,d),c._Store.processConfig(b),c._Identity.idCache=createIdentityCache(c),removeExpiredIdentityCacheDates(c._Identity.idCache),c._Store.webviewBridgeEnabled)c._NativeSdkHelpers.initializeSessionAttributes(a);else {c._Persistence.initializeStorage(),c._Store.syncPersistenceData();// Set up user identitiy variables for later use
1767
1768
  var e=c.Identity.getCurrentUser(),f=e?e.getMPID():null,g=e?e.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:g}:c._Store.SDKConfig.identifyRequest,c._Helpers.getFeatureFlag(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer(),c._Helpers.getFeatureFlag(CaptureIntegrationSpecificIds)&&c._IntegrationCapture.capture();// Configure Rokt Manager with user and filtered user
1768
- var h=parseConfig(b,"Rokt",181);if(h){var i=h.userAttributeFilters,j=filteredMparticleUser(f,{userAttributeFilters:i},c),k={sandbox:b.isDevelopmentMode};c._RoktManager.init(h,j,e,k);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,e,f,g);}// We will continue to clear out the ready queue as part of the initial init flow
1769
+ var h=parseConfig(b,"Rokt",181);if(h){var i=h.userAttributeFilters,j=filteredMparticleUser(f,{userAttributeFilters:i},c),k={managerOptions:{sandbox:b.isDevelopmentMode},launcherOptions:null===b||void 0===b?void 0:b.launcherOptions};// https://go.mparticle.com/work/SQDSDKS-7339
1770
+ c._RoktManager.init(h,j,c.Identity,c.Logger,k);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,e,f,g);}// We will continue to clear out the ready queue as part of the initial init flow
1769
1771
  // if an identify request is unnecessary, such as if there is an existing session
1770
1772
  (c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue)),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061
1771
1773
  function createKitBlocker(a,b){var c,d,e,f;/* There are three ways a data plan object for blocking can be passed to the SDK:
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.39.1";
206
+ var version = "2.41.0";
207
207
 
208
208
  var Constants = {
209
209
  sdkVersion: version,
@@ -8236,6 +8236,9 @@ var mParticle = (function () {
8236
8236
  mpInstance.Logger.error('Error parsing JSON response from Identity server: ' + e);
8237
8237
  }
8238
8238
  mpInstance._Store.isInitialized = true;
8239
+ if (mpInstance._RoktManager.isReady()) {
8240
+ mpInstance._RoktManager.currentUser = mpInstance.Identity.getCurrentUser();
8241
+ }
8239
8242
  mpInstance._preInit.readyQueue = processReadyQueue(mpInstance._preInit.readyQueue);
8240
8243
  };
8241
8244
 
@@ -9664,7 +9667,6 @@ var mParticle = (function () {
9664
9667
  this.kit = null;
9665
9668
  this.filters = {};
9666
9669
  this.currentUser = null;
9667
- this.filteredUser = null;
9668
9670
  this.messageQueue = [];
9669
9671
  this.sandbox = null;
9670
9672
  this.placementAttributesMapping = [];
@@ -9674,58 +9676,126 @@ var mParticle = (function () {
9674
9676
  *
9675
9677
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
9676
9678
  * @param {IMParticleUser} filteredUser - User object with filtered attributes
9677
- * @param {IMParticleUser} currentUser - Current mParticle user object
9678
- * @param {IRoktManagerOptions} options - Options for the RoktManager
9679
+ * @param {SDKIdentityApi} identityService - The mParticle Identity instance
9680
+ * @param {SDKLoggerApi} logger - The mParticle Logger instance
9681
+ * @param {IRoktOptions} options - Options for the RoktManager
9679
9682
  *
9680
9683
  * @throws Logs error to console if placementAttributesMapping parsing fails
9681
9684
  */
9682
- RoktManager.prototype.init = function (roktConfig, filteredUser, currentUser, options) {
9683
- var _a = roktConfig || {},
9684
- userAttributeFilters = _a.userAttributeFilters,
9685
- settings = _a.settings;
9685
+ RoktManager.prototype.init = function (roktConfig, filteredUser, identityService, logger, options) {
9686
+ var _a;
9687
+ var _b = roktConfig || {},
9688
+ userAttributeFilters = _b.userAttributeFilters,
9689
+ settings = _b.settings;
9686
9690
  var placementAttributesMapping = (settings || {}).placementAttributesMapping;
9687
9691
  try {
9688
9692
  this.placementAttributesMapping = parseSettingsString(placementAttributesMapping);
9689
9693
  } catch (error) {
9690
9694
  console.error('Error parsing placement attributes mapping from config', error);
9691
9695
  }
9692
- this.currentUser = currentUser;
9696
+ this.identityService = identityService;
9697
+ this.logger = logger;
9693
9698
  this.filters = {
9694
9699
  userAttributeFilters: userAttributeFilters,
9695
9700
  filterUserAttributes: KitFilterHelper.filterUserAttributes,
9696
9701
  filteredUser: filteredUser
9697
9702
  };
9698
- this.sandbox = options === null || options === void 0 ? void 0 : options.sandbox;
9703
+ // This is the global setting for sandbox mode
9704
+ // It is set here and passed in to the createLauncher method in the Rokt Kit
9705
+ // This is not to be confused for the `sandbox` flag in the selectPlacements attributes
9706
+ // as that is independent of this setting, though they share the same name.
9707
+ this.sandbox = (_a = options === null || options === void 0 ? void 0 : options.managerOptions) === null || _a === void 0 ? void 0 : _a.sandbox;
9708
+ // Launcher options are set here for the kit to pick up and pass through
9709
+ // to the Rokt Launcher.
9710
+ this.launcherOptions = options === null || options === void 0 ? void 0 : options.launcherOptions;
9699
9711
  };
9700
9712
  RoktManager.prototype.attachKit = function (kit) {
9701
9713
  this.kit = kit;
9702
9714
  this.processMessageQueue();
9703
9715
  };
9716
+ /**
9717
+ * Renders ads based on the options provided
9718
+ *
9719
+ * @param {IRoktSelectPlacementsOptions} options - The options for selecting placements, including attributes and optional identifier
9720
+ * @returns {Promise<IRoktSelection>} A promise that resolves to the selection
9721
+ *
9722
+ * @example
9723
+ * // Correct usage with await
9724
+ * await window.mParticle.Rokt.selectPlacements({
9725
+ * attributes: {
9726
+ * email: 'user@example.com',
9727
+ * customAttr: 'value'
9728
+ * }
9729
+ * });
9730
+ */
9704
9731
  RoktManager.prototype.selectPlacements = function (options) {
9705
- var _a;
9706
- if (!this.isReady()) {
9707
- this.queueMessage({
9708
- methodName: 'selectPlacements',
9709
- payload: options
9710
- });
9711
- return Promise.resolve({});
9712
- }
9713
- try {
9714
- var attributes = options.attributes;
9715
- var sandboxValue = (_a = attributes === null || attributes === void 0 ? void 0 : attributes.sandbox) !== null && _a !== void 0 ? _a : this.sandbox;
9716
- var mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
9717
- this.setUserAttributes(mappedAttributes);
9718
- var enrichedAttributes = __assign(__assign({}, mappedAttributes), sandboxValue !== null ? {
9719
- sandbox: sandboxValue
9720
- } : {});
9721
- var enrichedOptions = __assign(__assign({}, options), {
9722
- attributes: enrichedAttributes
9732
+ var _a, _b;
9733
+ return __awaiter(this, void 0, void 0, function () {
9734
+ var attributes, sandboxValue, mappedAttributes, currentUserIdentities_1, currentEmail, newEmail_1, error_1, enrichedAttributes, enrichedOptions, error_2;
9735
+ var _this = this;
9736
+ return __generator(this, function (_c) {
9737
+ switch (_c.label) {
9738
+ case 0:
9739
+ if (!this.isReady()) {
9740
+ this.queueMessage({
9741
+ methodName: 'selectPlacements',
9742
+ payload: options
9743
+ });
9744
+ return [2 /*return*/, Promise.resolve({})];
9745
+ }
9746
+ _c.label = 1;
9747
+ case 1:
9748
+ _c.trys.push([1, 6,, 7]);
9749
+ attributes = options.attributes;
9750
+ sandboxValue = (attributes === null || attributes === void 0 ? void 0 : attributes.sandbox) || null;
9751
+ mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
9752
+ // Get current user identities
9753
+ this.currentUser = this.identityService.getCurrentUser();
9754
+ currentUserIdentities_1 = ((_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.getUserIdentities()) === null || _b === void 0 ? void 0 : _b.userIdentities) || {};
9755
+ currentEmail = currentUserIdentities_1.email;
9756
+ newEmail_1 = mappedAttributes.email;
9757
+ if (!(newEmail_1 && (!currentEmail || currentEmail !== newEmail_1))) return [3 /*break*/, 5];
9758
+ if (currentEmail && currentEmail !== newEmail_1) {
9759
+ this.logger.warning("Email mismatch detected. Current email, ".concat(currentEmail, " differs from email passed to selectPlacements call, ").concat(newEmail_1, ". Proceeding to call identify with ").concat(newEmail_1, ". Please verify your implementation."));
9760
+ }
9761
+ _c.label = 2;
9762
+ case 2:
9763
+ _c.trys.push([2, 4,, 5]);
9764
+ return [4 /*yield*/, new Promise(function (resolve, reject) {
9765
+ _this.identityService.identify({
9766
+ userIdentities: __assign(__assign({}, currentUserIdentities_1), {
9767
+ email: newEmail_1
9768
+ })
9769
+ }, function () {
9770
+ resolve();
9771
+ });
9772
+ })];
9773
+ case 3:
9774
+ _c.sent();
9775
+ return [3 /*break*/, 5];
9776
+ case 4:
9777
+ error_1 = _c.sent();
9778
+ this.logger.error('Failed to identify user with new email: ' + JSON.stringify(error_1));
9779
+ return [3 /*break*/, 5];
9780
+ case 5:
9781
+ this.setUserAttributes(mappedAttributes);
9782
+ enrichedAttributes = __assign(__assign({}, mappedAttributes), sandboxValue !== null ? {
9783
+ sandbox: sandboxValue
9784
+ } : {});
9785
+ enrichedOptions = __assign(__assign({}, options), {
9786
+ attributes: enrichedAttributes
9787
+ });
9788
+ return [2 /*return*/, this.kit.selectPlacements(enrichedOptions)];
9789
+ case 6:
9790
+ error_2 = _c.sent();
9791
+ return [2 /*return*/, Promise.reject(error_2 instanceof Error ? error_2 : new Error('Unknown error occurred'))];
9792
+ case 7:
9793
+ return [2 /*return*/];
9794
+ }
9723
9795
  });
9724
- return this.kit.selectPlacements(enrichedOptions);
9725
- } catch (error) {
9726
- return Promise.reject(error instanceof Error ? error : new Error('Unknown error occurred'));
9727
- }
9796
+ });
9728
9797
  };
9798
+
9729
9799
  RoktManager.prototype.hashAttributes = function (attributes) {
9730
9800
  if (!this.isReady()) {
9731
9801
  this.queueMessage({
@@ -10795,9 +10865,13 @@ var mParticle = (function () {
10795
10865
  userAttributeFilters: userAttributeFilters
10796
10866
  }, mpInstance);
10797
10867
  var roktOptions = {
10798
- sandbox: config.isDevelopmentMode
10868
+ managerOptions: {
10869
+ sandbox: config.isDevelopmentMode
10870
+ },
10871
+ launcherOptions: config === null || config === void 0 ? void 0 : config.launcherOptions
10799
10872
  };
10800
- mpInstance._RoktManager.init(roktConfig, roktFilteredUser, currentUser, roktOptions);
10873
+ // https://go.mparticle.com/work/SQDSDKS-7339
10874
+ mpInstance._RoktManager.init(roktConfig, roktFilteredUser, mpInstance.Identity, mpInstance.Logger, roktOptions);
10801
10875
  }
10802
10876
  mpInstance._Forwarders.processForwarders(config, mpInstance._APIClient.prepareForwardingStats);
10803
10877
  mpInstance._Forwarders.processPixelConfigs(config);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.39.1",
3
+ "version": "2.41.0",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
package/src/identity.js CHANGED
@@ -1677,6 +1677,10 @@ export default function Identity(mpInstance) {
1677
1677
  }
1678
1678
  mpInstance._Store.isInitialized = true;
1679
1679
 
1680
+ if (mpInstance._RoktManager.isReady()) {
1681
+ mpInstance._RoktManager.currentUser = mpInstance.Identity.getCurrentUser();
1682
+ }
1683
+
1680
1684
  mpInstance._preInit.readyQueue = processReadyQueue(
1681
1685
  mpInstance._preInit.readyQueue
1682
1686
  );
@@ -49,7 +49,7 @@ import { IECommerce } from './ecommerce.interfaces';
49
49
  import { INativeSdkHelpers } from './nativeSdkHelpers.interfaces';
50
50
  import { IPersistence } from './persistence.interfaces';
51
51
  import ForegroundTimer from './foregroundTimeTracker';
52
- import RoktManager, { IRoktManagerOptions } from './roktManager';
52
+ import RoktManager, { IRoktManagerOptions, IRoktOptions } from './roktManager';
53
53
  import filteredMparticleUser from './filteredMparticleUser';
54
54
 
55
55
  export interface IErrorLogMessage {
@@ -1403,10 +1403,20 @@ function completeSDKInitialization(apiKey, config, mpInstance) {
1403
1403
  { userAttributeFilters },
1404
1404
  mpInstance
1405
1405
  );
1406
- const roktOptions: IRoktManagerOptions = {
1407
- sandbox: config.isDevelopmentMode,
1406
+ const roktOptions: IRoktOptions = {
1407
+ managerOptions: {
1408
+ sandbox: config.isDevelopmentMode,
1409
+ },
1410
+ launcherOptions: config?.launcherOptions,
1408
1411
  };
1409
- mpInstance._RoktManager.init(roktConfig, roktFilteredUser, currentUser, roktOptions);
1412
+ // https://go.mparticle.com/work/SQDSDKS-7339
1413
+ mpInstance._RoktManager.init(
1414
+ roktConfig,
1415
+ roktFilteredUser,
1416
+ mpInstance.Identity,
1417
+ mpInstance.Logger,
1418
+ roktOptions
1419
+ );
1410
1420
  }
1411
1421
 
1412
1422
  mpInstance._Forwarders.processForwarders(
@@ -3,6 +3,8 @@ import { UserAttributeFilters } from "./forwarders.interfaces";
3
3
  import { IMParticleUser } from "./identity-user-interfaces";
4
4
  import KitFilterHelper from "./kitFilterHelper";
5
5
  import { Dictionary, parseSettingsString } from "./utils";
6
+ import { SDKIdentityApi } from "./identity.interfaces";
7
+ import { SDKLoggerApi } from "./sdkRuntimeModels";
6
8
 
7
9
  // https://docs.rokt.com/developers/integration-guides/web/library/attributes
8
10
  export interface IRoktPartnerAttributes {
@@ -42,7 +44,7 @@ export interface RoktKitFilterSettings {
42
44
  filteredUser?: IMParticleUser | null;
43
45
  }
44
46
 
45
- export interface IRoktKit {
47
+ export interface IRoktKit {
46
48
  filters: RoktKitFilterSettings;
47
49
  filteredUser: IMParticleUser | null;
48
50
  launcher: IRoktLauncher | null;
@@ -50,12 +52,19 @@ export interface IRoktKit {
50
52
  hashAttributes: (attributes: IRoktPartnerAttributes) => Promise<Record<string, string>>;
51
53
  selectPlacements: (options: IRoktSelectPlacementsOptions) => Promise<IRoktSelection>;
52
54
  setExtensionData<T>(extensionData: IRoktPartnerExtensionData<T>): void;
55
+ launcherOptions?: Dictionary<any>;
53
56
  }
54
57
 
55
- export interface IRoktManagerOptions {
56
- sandbox?: boolean;
58
+ export interface IRoktOptions {
59
+ managerOptions?: IRoktManagerOptions;
60
+ launcherOptions?: IRoktLauncherOptions;
57
61
  }
58
62
 
63
+ export type IRoktLauncherOptions = Dictionary<any>;
64
+ export type IRoktManagerOptions = {
65
+ sandbox?: boolean;
66
+ };
67
+
59
68
  // The purpose of this class is to create a link between the Core mParticle SDK and the
60
69
  // Rokt Web SDK via a Web Kit.
61
70
  // The Rokt Manager should load before the Web Kit and stubs out many of the
@@ -68,24 +77,31 @@ export interface IRoktManagerOptions {
68
77
  export default class RoktManager {
69
78
  public kit: IRoktKit = null;
70
79
  public filters: RoktKitFilterSettings = {};
71
-
72
80
  private currentUser: IMParticleUser | null = null;
73
- private filteredUser: IMParticleUser | null = null;
74
81
  private messageQueue: IRoktMessage[] = [];
75
82
  private sandbox: boolean | null = null;
76
83
  private placementAttributesMapping: Dictionary<string>[] = [];
77
-
84
+ private identityService: SDKIdentityApi;
85
+ private launcherOptions?: IRoktLauncherOptions;
86
+ private logger: SDKLoggerApi;
78
87
  /**
79
88
  * Initializes the RoktManager with configuration settings and user data.
80
89
  *
81
90
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
82
91
  * @param {IMParticleUser} filteredUser - User object with filtered attributes
83
- * @param {IMParticleUser} currentUser - Current mParticle user object
84
- * @param {IRoktManagerOptions} options - Options for the RoktManager
92
+ * @param {SDKIdentityApi} identityService - The mParticle Identity instance
93
+ * @param {SDKLoggerApi} logger - The mParticle Logger instance
94
+ * @param {IRoktOptions} options - Options for the RoktManager
85
95
  *
86
96
  * @throws Logs error to console if placementAttributesMapping parsing fails
87
97
  */
88
- public init(roktConfig: IKitConfigs, filteredUser: IMParticleUser, currentUser: IMParticleUser, options?: IRoktManagerOptions): void {
98
+ public init(
99
+ roktConfig: IKitConfigs,
100
+ filteredUser: IMParticleUser,
101
+ identityService: SDKIdentityApi,
102
+ logger?: SDKLoggerApi,
103
+ options?: IRoktOptions
104
+ ): void {
89
105
  const { userAttributeFilters, settings } = roktConfig || {};
90
106
  const { placementAttributesMapping } = settings || {};
91
107
 
@@ -95,7 +111,8 @@ export default class RoktManager {
95
111
  console.error('Error parsing placement attributes mapping from config', error);
96
112
  }
97
113
 
98
- this.currentUser = currentUser;
114
+ this.identityService = identityService;
115
+ this.logger = logger;
99
116
 
100
117
  this.filters = {
101
118
  userAttributeFilters,
@@ -103,7 +120,15 @@ export default class RoktManager {
103
120
  filteredUser: filteredUser,
104
121
  };
105
122
 
106
- this.sandbox = options?.sandbox;
123
+ // This is the global setting for sandbox mode
124
+ // It is set here and passed in to the createLauncher method in the Rokt Kit
125
+ // This is not to be confused for the `sandbox` flag in the selectPlacements attributes
126
+ // as that is independent of this setting, though they share the same name.
127
+ this.sandbox = options?.managerOptions?.sandbox;
128
+
129
+ // Launcher options are set here for the kit to pick up and pass through
130
+ // to the Rokt Launcher.
131
+ this.launcherOptions = options?.launcherOptions;
107
132
  }
108
133
 
109
134
  public attachKit(kit: IRoktKit): void {
@@ -111,7 +136,22 @@ export default class RoktManager {
111
136
  this.processMessageQueue();
112
137
  }
113
138
 
114
- public selectPlacements(options: IRoktSelectPlacementsOptions): Promise<IRoktSelection> {
139
+ /**
140
+ * Renders ads based on the options provided
141
+ *
142
+ * @param {IRoktSelectPlacementsOptions} options - The options for selecting placements, including attributes and optional identifier
143
+ * @returns {Promise<IRoktSelection>} A promise that resolves to the selection
144
+ *
145
+ * @example
146
+ * // Correct usage with await
147
+ * await window.mParticle.Rokt.selectPlacements({
148
+ * attributes: {
149
+ * email: 'user@example.com',
150
+ * customAttr: 'value'
151
+ * }
152
+ * });
153
+ */
154
+ public async selectPlacements(options: IRoktSelectPlacementsOptions): Promise<IRoktSelection> {
115
155
  if (!this.isReady()) {
116
156
  this.queueMessage({
117
157
  methodName: 'selectPlacements',
@@ -122,15 +162,45 @@ export default class RoktManager {
122
162
 
123
163
  try {
124
164
  const { attributes } = options;
125
- const sandboxValue = attributes?.sandbox ?? this.sandbox;
165
+ const sandboxValue = attributes?.sandbox || null;
126
166
  const mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
127
167
 
168
+ // Get current user identities
169
+ this.currentUser = this.identityService.getCurrentUser();
170
+ const currentUserIdentities = this.currentUser?.getUserIdentities()?.userIdentities || {};
171
+ const currentEmail = currentUserIdentities.email;
172
+ const newEmail = mappedAttributes.email as string;
173
+
174
+ // https://go.mparticle.com/work/SQDSDKS-7338
175
+ // Check if email exists and differs
176
+ if (newEmail && (!currentEmail || currentEmail !== newEmail)) {
177
+ if (currentEmail && currentEmail !== newEmail) {
178
+ this.logger.warning(`Email mismatch detected. Current email, ${currentEmail} differs from email passed to selectPlacements call, ${newEmail}. Proceeding to call identify with ${newEmail}. Please verify your implementation.`);
179
+ }
180
+
181
+ // Call identify with the new user identities
182
+ try {
183
+ await new Promise<void>((resolve, reject) => {
184
+ this.identityService.identify({
185
+ userIdentities: {
186
+ ...currentUserIdentities,
187
+ email: newEmail
188
+ }
189
+ }, () => {
190
+ resolve();
191
+ });
192
+ });
193
+ } catch (error) {
194
+ this.logger.error('Failed to identify user with new email: ' + JSON.stringify(error));
195
+ }
196
+ }
197
+
128
198
  this.setUserAttributes(mappedAttributes);
129
199
 
130
200
  const enrichedAttributes = {
131
201
  ...mappedAttributes,
132
202
  ...(sandboxValue !== null ? { sandbox: sandboxValue } : {}),
133
- };
203
+ };
134
204
 
135
205
  const enrichedOptions = {
136
206
  ...options,
@@ -39,7 +39,7 @@ import _BatchValidator from './mockBatchCreator';
39
39
  import { SDKECommerceAPI } from './ecommerce.interfaces';
40
40
  import { IErrorLogMessage, IMParticleWebSDKInstance, IntegrationDelays } from './mp-instance';
41
41
  import Constants from './constants';
42
- import RoktManager from './roktManager';
42
+ import RoktManager, { IRoktLauncherOptions } from './roktManager';
43
43
 
44
44
  // TODO: Resolve this with version in @mparticle/web-sdk
45
45
  export type SDKEventCustomFlags = Dictionary<any>;
@@ -301,6 +301,8 @@ export interface SDKInitConfig
301
301
  // https://go.mparticle.com/work/SQDSDKS-6460
302
302
  identityCallback?: IdentityCallback;
303
303
 
304
+ launcherOptions?: IRoktLauncherOptions;
305
+
304
306
  rq?: Function[] | any[];
305
307
  }
306
308