@mparticle/web-sdk 2.43.1 → 2.43.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.43.1";
18
+ var version = "2.43.2";
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/"},// These are the paths that are used to construct the CNAME urls
@@ -1427,7 +1427,7 @@ for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickI
1427
1427
  // Rokt Manager in a "ready" state and it can begin sending data to the kit.
1428
1428
  //
1429
1429
  // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
1430
- var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1430
+ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[];}/**
1431
1431
  * Initializes the RoktManager with configuration settings and user data.
1432
1432
  *
1433
1433
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
@@ -1443,8 +1443,8 @@ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters=
1443
1443
  // as that is independent of this setting, though they share the same name.
1444
1444
  var j=(null===e||void 0===e?void 0:e.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through
1445
1445
  // to the Rokt Launcher.
1446
- this.launcherOptions=__assign({sandbox:j},null===e||void 0===e?void 0:e.launcherOptions),(null===e||void 0===e?void 0:e.domain)&&(this.domain=e.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=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
1447
- 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}();
1446
+ this.launcherOptions=__assign({sandbox:j},null===e||void 0===e?void 0:e.launcherOptions),(null===e||void 0===e?void 0:e.domain)&&(this.domain=e.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=this;return __generator(this,function(o){switch(o.label){case 0:if(!this.isReady())return [2/*return*/,this.deferredCall("selectPlacements",a)];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.deferredCall("hashAttributes",a);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.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.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1447
+ 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,b=this;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")),this.messageQueue.forEach(function(a){var c,d,e;if(!(a.methodName in b.kit)||!isFunction(b.kit[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found in kit")));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.kit[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));}}));},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}();
1448
1448
 
1449
1449
  var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
1450
1450
  * <p>All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced <a href="https://docs.mparticle.com/developers/sdk/web/multiple-instances/">multiple instances</a>. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.</p>
@@ -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.43.1";
18
+ var version = "2.43.2";
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/"},// These are the paths that are used to construct the CNAME urls
@@ -1427,7 +1427,7 @@ for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickI
1427
1427
  // Rokt Manager in a "ready" state and it can begin sending data to the kit.
1428
1428
  //
1429
1429
  // https://github.com/mparticle-integrations/mparticle-javascript-integration-rokt
1430
- var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=[],this.sandbox=null,this.placementAttributesMapping=[];}/**
1430
+ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[];}/**
1431
1431
  * Initializes the RoktManager with configuration settings and user data.
1432
1432
  *
1433
1433
  * @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
@@ -1443,8 +1443,8 @@ var RoktManager=/** @class */function(){function a(){this.kit=null,this.filters=
1443
1443
  // as that is independent of this setting, though they share the same name.
1444
1444
  var j=(null===e||void 0===e?void 0:e.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through
1445
1445
  // to the Rokt Launcher.
1446
- this.launcherOptions=__assign({sandbox:j},null===e||void 0===e?void 0:e.launcherOptions),(null===e||void 0===e?void 0:e.domain)&&(this.domain=e.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=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
1447
- 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}();
1446
+ this.launcherOptions=__assign({sandbox:j},null===e||void 0===e?void 0:e.launcherOptions),(null===e||void 0===e?void 0:e.domain)&&(this.domain=e.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=this;return __generator(this,function(o){switch(o.label){case 0:if(!this.isReady())return [2/*return*/,this.deferredCall("selectPlacements",a)];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.deferredCall("hashAttributes",a);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.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.isReady=function(){// The Rokt Manager is ready when a kit is attached and has a launcher
1447
+ 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,b=this;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")),this.messageQueue.forEach(function(a){var c,d,e;if(!(a.methodName in b.kit)||!isFunction(b.kit[a.methodName]))return void(null===(c=b.logger)||void 0===c?void 0:c.error("RoktManager: Method ".concat(a.methodName," not found in kit")));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.kit[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));}}));},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}();
1448
1448
 
1449
1449
  var Messages=Constants.Messages,HTTPCodes=Constants.HTTPCodes,FeatureFlags=Constants.FeatureFlags,ReportBatching=FeatureFlags.ReportBatching,CaptureIntegrationSpecificIds=FeatureFlags.CaptureIntegrationSpecificIds,StartingInitialization=Messages.InformationMessages.StartingInitialization;/**
1450
1450
  * <p>All of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced <a href="https://docs.mparticle.com/developers/sdk/web/multiple-instances/">multiple instances</a>. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.</p>
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.43.1";
206
+ var version = "2.43.2";
207
207
 
208
208
  var Constants = {
209
209
  sdkVersion: version,
@@ -9721,7 +9721,7 @@ var mParticle = (function () {
9721
9721
  this.kit = null;
9722
9722
  this.filters = {};
9723
9723
  this.currentUser = null;
9724
- this.messageQueue = [];
9724
+ this.messageQueue = new Map();
9725
9725
  this.sandbox = null;
9726
9726
  this.placementAttributesMapping = [];
9727
9727
  }
@@ -9795,11 +9795,7 @@ var mParticle = (function () {
9795
9795
  switch (_c.label) {
9796
9796
  case 0:
9797
9797
  if (!this.isReady()) {
9798
- this.queueMessage({
9799
- methodName: 'selectPlacements',
9800
- payload: options
9801
- });
9802
- return [2 /*return*/, Promise.resolve({})];
9798
+ return [2 /*return*/, this.deferredCall('selectPlacements', options)];
9803
9799
  }
9804
9800
  _c.label = 1;
9805
9801
  case 1:
@@ -9856,11 +9852,7 @@ var mParticle = (function () {
9856
9852
 
9857
9853
  RoktManager.prototype.hashAttributes = function (attributes) {
9858
9854
  if (!this.isReady()) {
9859
- this.queueMessage({
9860
- methodName: 'hashAttributes',
9861
- payload: attributes
9862
- });
9863
- return Promise.resolve({});
9855
+ return this.deferredCall('hashAttributes', attributes);
9864
9856
  }
9865
9857
  try {
9866
9858
  return this.kit.hashAttributes(attributes);
@@ -9870,10 +9862,7 @@ var mParticle = (function () {
9870
9862
  };
9871
9863
  RoktManager.prototype.setExtensionData = function (extensionData) {
9872
9864
  if (!this.isReady()) {
9873
- this.queueMessage({
9874
- methodName: 'setExtensionData',
9875
- payload: extensionData
9876
- });
9865
+ this.deferredCall('setExtensionData', extensionData);
9877
9866
  return;
9878
9867
  }
9879
9868
  try {
@@ -9918,29 +9907,57 @@ var mParticle = (function () {
9918
9907
  };
9919
9908
  RoktManager.prototype.processMessageQueue = function () {
9920
9909
  var _this = this;
9921
- if (this.messageQueue.length > 0 && this.isReady()) {
9922
- this.messageQueue.forEach(function (message) {
9923
- return __awaiter(_this, void 0, void 0, function () {
9924
- return __generator(this, function (_a) {
9925
- switch (_a.label) {
9926
- case 0:
9927
- if (!(this.kit && message.methodName in this.kit)) return [3 /*break*/, 2];
9928
- return [4 /*yield*/, this.kit[message.methodName](message.payload)];
9929
- case 1:
9930
- _a.sent();
9931
- _a.label = 2;
9932
- case 2:
9933
- return [2 /*return*/];
9934
- }
9935
- });
9936
- });
9937
- });
9938
-
9939
- this.messageQueue = [];
9910
+ var _a;
9911
+ if (!this.isReady() || this.messageQueue.size === 0) {
9912
+ return;
9940
9913
  }
9914
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.verbose("RoktManager: Processing ".concat(this.messageQueue.size, " queued messages"));
9915
+ this.messageQueue.forEach(function (message) {
9916
+ var _a, _b, _c;
9917
+ if (!(message.methodName in _this.kit) || !isFunction(_this.kit[message.methodName])) {
9918
+ (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error("RoktManager: Method ".concat(message.methodName, " not found in kit"));
9919
+ return;
9920
+ }
9921
+ (_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)));
9922
+ try {
9923
+ var result = _this.kit[message.methodName](message.payload);
9924
+ _this.completePendingPromise(message.messageId, result);
9925
+ } catch (error) {
9926
+ var errorMessage = error instanceof Error ? error.message : String(error);
9927
+ (_c = _this.logger) === null || _c === void 0 ? void 0 : _c.error("RoktManager: Error processing message '".concat(message.methodName, "': ").concat(errorMessage));
9928
+ _this.completePendingPromise(message.messageId, Promise.reject(error));
9929
+ }
9930
+ });
9941
9931
  };
9942
9932
  RoktManager.prototype.queueMessage = function (message) {
9943
- this.messageQueue.push(message);
9933
+ this.messageQueue.set(message.messageId, message);
9934
+ };
9935
+ RoktManager.prototype.deferredCall = function (methodName, payload) {
9936
+ var _this = this;
9937
+ return new Promise(function (resolve, reject) {
9938
+ var messageId = "".concat(methodName, "_").concat(generateUniqueId());
9939
+ _this.queueMessage({
9940
+ messageId: messageId,
9941
+ methodName: methodName,
9942
+ payload: payload,
9943
+ resolve: resolve,
9944
+ reject: reject
9945
+ });
9946
+ });
9947
+ };
9948
+ RoktManager.prototype.completePendingPromise = function (messageId, resultOrError) {
9949
+ if (!messageId || !this.messageQueue.has(messageId)) {
9950
+ return;
9951
+ }
9952
+ var message = this.messageQueue.get(messageId);
9953
+ if (message.resolve) {
9954
+ Promise.resolve(resultOrError).then(function (result) {
9955
+ return message.resolve(result);
9956
+ })["catch"](function (error) {
9957
+ return message.reject(error);
9958
+ });
9959
+ }
9960
+ this.messageQueue["delete"](messageId);
9944
9961
  };
9945
9962
  return RoktManager;
9946
9963
  }();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.43.1",
3
+ "version": "2.43.2",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -2,7 +2,7 @@ import { IKitConfigs } from "./configAPIClient";
2
2
  import { UserAttributeFilters } from "./forwarders.interfaces";
3
3
  import { IMParticleUser } from "./identity-user-interfaces";
4
4
  import KitFilterHelper from "./kitFilterHelper";
5
- import { Dictionary, parseSettingsString } from "./utils";
5
+ import { Dictionary, parseSettingsString, generateUniqueId, isFunction } from "./utils";
6
6
  import { SDKIdentityApi } from "./identity.interfaces";
7
7
  import { SDKLoggerApi } from "./sdkRuntimeModels";
8
8
 
@@ -34,8 +34,11 @@ export interface IRoktLauncher {
34
34
  }
35
35
 
36
36
  export interface IRoktMessage {
37
+ messageId: string;
37
38
  methodName: string;
38
39
  payload: any;
40
+ resolve?: Function;
41
+ reject?: Function;
39
42
  }
40
43
 
41
44
  export interface RoktKitFilterSettings {
@@ -76,7 +79,7 @@ export default class RoktManager {
76
79
  public kit: IRoktKit = null;
77
80
  public filters: RoktKitFilterSettings = {};
78
81
  private currentUser: IMParticleUser | null = null;
79
- private messageQueue: IRoktMessage[] = [];
82
+ private messageQueue: Map<string, IRoktMessage> = new Map();
80
83
  private sandbox: boolean | null = null;
81
84
  private placementAttributesMapping: Dictionary<string>[] = [];
82
85
  private identityService: SDKIdentityApi;
@@ -156,11 +159,7 @@ export default class RoktManager {
156
159
  */
157
160
  public async selectPlacements(options: IRoktSelectPlacementsOptions): Promise<IRoktSelection> {
158
161
  if (!this.isReady()) {
159
- this.queueMessage({
160
- methodName: 'selectPlacements',
161
- payload: options,
162
- });
163
- return Promise.resolve({} as IRoktSelection);
162
+ return this.deferredCall<IRoktSelection>('selectPlacements', options);
164
163
  }
165
164
 
166
165
  try {
@@ -216,13 +215,9 @@ export default class RoktManager {
216
215
  }
217
216
  }
218
217
 
219
- public hashAttributes(attributes: IRoktPartnerAttributes): Promise<Record<string, string>> {
218
+ public hashAttributes(attributes: IRoktPartnerAttributes): Promise<IRoktPartnerAttributes> {
220
219
  if (!this.isReady()) {
221
- this.queueMessage({
222
- methodName: 'hashAttributes',
223
- payload: attributes,
224
- });
225
- return Promise.resolve({} as Record<string, string>);
220
+ return this.deferredCall<IRoktPartnerAttributes>('hashAttributes', attributes);
226
221
  }
227
222
 
228
223
  try {
@@ -234,10 +229,7 @@ export default class RoktManager {
234
229
 
235
230
  public setExtensionData<T>(extensionData: IRoktPartnerExtensionData<T>): void {
236
231
  if (!this.isReady()) {
237
- this.queueMessage({
238
- methodName: 'setExtensionData',
239
- payload: extensionData,
240
- });
232
+ this.deferredCall<void>('setExtensionData', extensionData);
241
233
  return;
242
234
  }
243
235
 
@@ -288,17 +280,62 @@ export default class RoktManager {
288
280
  }
289
281
 
290
282
  private processMessageQueue(): void {
291
- if (this.messageQueue.length > 0 && this.isReady()) {
292
- this.messageQueue.forEach(async (message) => {
293
- if (this.kit && message.methodName in this.kit) {
294
- await (this.kit[message.methodName] as Function)(message.payload);
295
- }
296
- });
297
- this.messageQueue = [];
283
+ if (!this.isReady() || this.messageQueue.size === 0) {
284
+ return;
298
285
  }
286
+
287
+ this.logger?.verbose(`RoktManager: Processing ${this.messageQueue.size} queued messages`);
288
+
289
+ this.messageQueue.forEach((message) => {
290
+ if(!(message.methodName in this.kit) || !isFunction(this.kit[message.methodName])) {
291
+ this.logger?.error(`RoktManager: Method ${message.methodName} not found in kit`);
292
+ return;
293
+ }
294
+
295
+ this.logger?.verbose(`RoktManager: Processing queued message: ${message.methodName} with payload: ${JSON.stringify(message.payload)}`);
296
+
297
+ try {
298
+ const result = (this.kit[message.methodName] as Function)(message.payload);
299
+ this.completePendingPromise(message.messageId, result);
300
+ } catch (error) {
301
+ const errorMessage = error instanceof Error ? error.message : String(error);
302
+ this.logger?.error(`RoktManager: Error processing message '${message.methodName}': ${errorMessage}`);
303
+ this.completePendingPromise(message.messageId, Promise.reject(error));
304
+ }
305
+ });
299
306
  }
300
307
 
301
308
  private queueMessage(message: IRoktMessage): void {
302
- this.messageQueue.push(message);
309
+ this.messageQueue.set(message.messageId, message);
310
+ }
311
+
312
+ private deferredCall<T>(methodName: string, payload: any): Promise<T> {
313
+ return new Promise<T>((resolve, reject) => {
314
+ const messageId = `${methodName}_${generateUniqueId()}`;
315
+
316
+ this.queueMessage({
317
+ messageId,
318
+ methodName,
319
+ payload,
320
+ resolve,
321
+ reject,
322
+ });
323
+ });
324
+ }
325
+
326
+ private completePendingPromise(messageId: string | undefined, resultOrError: any): void {
327
+ if (!messageId || !this.messageQueue.has(messageId)) {
328
+ return;
329
+ }
330
+
331
+ const message = this.messageQueue.get(messageId)!;
332
+
333
+ if (message.resolve) {
334
+ Promise.resolve(resultOrError)
335
+ .then((result) => message.resolve!(result))
336
+ .catch((error) => message.reject!(error));
337
+ }
338
+
339
+ this.messageQueue.delete(messageId);
303
340
  }
304
341
  }