@mparticle/web-sdk 2.30.2 → 2.30.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,7 +8,7 @@ Hello! This is the public repo of the mParticle Web SDK. We've built the mPartic
8
8
 
9
9
  ## Documentation
10
10
 
11
- Fully detailed documentation and other information about mParticle web SDK can be found at our doc site [here](https://docs.mparticle.com/developers/sdk/web/getting-started)
11
+ Fully detailed documentation and other information about mParticle web SDK can be found at our doc site [here](https://docs.mparticle.com/developers/sdk/web/initialization/)
12
12
 
13
13
  ## Include and Initialize the SDK
14
14
 
@@ -154,7 +154,7 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
154
154
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
155
155
  };
156
156
 
157
- var version = "2.30.2";
157
+ var version = "2.30.4";
158
158
 
159
159
  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
160
160
  },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
@@ -1128,6 +1128,9 @@ throw new Error("Uncaught HTTP Error ".concat(e.status,"."));case 5:return [3/*b
1128
1128
  function hasMPIDAndUserLoginChanged(a,b){return !a||b.getMPID()!==a.getMPID()||a.isLoggedIn()!==b.isLoggedIn()}// https://go.mparticle.com/work/SQDSDKS-6504
1129
1129
  function hasMPIDChanged(a,b){return !a||a.getMPID()&&b.mpid&&b.mpid!==a.getMPID()}
1130
1130
 
1131
+ var _this=undefined;var processReadyQueue=function(a){return isEmpty(a)||a.forEach(function(a){isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a);}),[]};var processPreloadedItem=function(a){var b=a,c=b.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it
1132
+ if("undefined"!=typeof window&&window.mParticle&&window.mParticle[b[0]])window.mParticle[c].apply(_this,b);else {var d=c.split(".");try{for(var e,f=window.mParticle,g=0,h=d;g<h.length;g++)e=h[g],f=f[e];f.apply(_this,b);}catch(a){throw new Error("Unable to compute proper mParticle function "+a)}}};
1133
+
1131
1134
  var Messages$3=Constants.Messages,HTTPCodes$3=Constants.HTTPCodes,FeatureFlags$1=Constants.FeatureFlags,IdentityMethods=Constants.IdentityMethods,ErrorMessages=Messages$3.ErrorMessages,CacheIdentity=FeatureFlags$1.CacheIdentity,Identify=IdentityMethods.Identify,Modify$1=IdentityMethods.Modify,Login=IdentityMethods.Login,Logout=IdentityMethods.Logout;function Identity(t){var r=t._Helpers,s=r.getFeatureFlag,i=r.extend,n=this;// https://go.mparticle.com/work/SQDSDKS-6353
1132
1135
  /**
1133
1136
  * Invoke these methods on the mParticle.Identity object.
@@ -1300,7 +1303,7 @@ return t._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===s.audie
1300
1303
  * @deprecated
1301
1304
  */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(i,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=getNewIdentitiesByName(v),k=o===Modify$1?_:P;// https://go.mparticle.com/work/SQDSDKS-6501
1302
1305
  n.sendUserIdentityChangeEvent(C,o,p.mpid,k);}if(a){var f=0===r.status?HTTPCodes$3.noHttpCoverage:r.status;t._Helpers.invokeCallback(a,f,p||null,y);}else p&&!isEmpty(p.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
1303
- 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);}},this.sendUserIdentityChangeEvent=function(e,r,s,i){if(s||r===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1306
+ 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
1304
1307
  {// https://go.mparticle.com/work/SQDSDKS-6354
1305
1308
  var a=this.IdentityAPI.getUser(s);for(var d in e)// Verifies a change actually happened
1306
1309
  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
@@ -1753,9 +1756,9 @@ function completeSDKInitialization(a,b,c){var d=createKitBlocker(b,c);// Web Vie
1753
1756
  // responsible for sending events directly to mParticle's servers. The Web SDK will not initialize
1754
1757
  // persistence or Identity directly.
1755
1758
  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
1756
- 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(),c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,e,f,g);}c._Store.isInitialized=!0;// Call any functions that are waiting for the library to be initialized
1757
- try{c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue);}catch(a){c.Logger.error(a);}// https://go.mparticle.com/work/SQDSDKS-6040
1758
- c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}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:
1759
+ 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(),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
1760
+ // if an identify request is unnecessary, such as if there is an existing session
1761
+ (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);}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:
1759
1762
  1. Manually via config.dataPlanOptions (this takes priority)
1760
1763
  If not passed in manually, we user the server provided via either
1761
1764
  2. Snippet via /mparticle.js endpoint (config.dataPlan.document)
@@ -1763,9 +1766,7 @@ c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}function createKitBlocker(a,b){va
1763
1766
  */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){return new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(StartingInitialization);// Check to see if localStorage is available before main configuration runs
1764
1767
  // since we will need this for the current implementation of user persistence
1765
1768
  // TODO: Refactor this when we refactor User Identity Persistence
1766
- try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function processPreloadedItem(a){var b=a,c=b.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it
1767
- if(mParticle[b[0]])mParticle[c].apply(this,b);else {var d=c.split(".");try{for(var e,f=mParticle,g=0;g<d.length;g++)e=d[g],f=f[e];f.apply(this,b);}catch(a){throw new Error("Unable to compute proper mParticle function "+a)}}}function processReadyQueue(a){// https://go.mparticle.com/work/SQDSDKS-6835
1768
- return isEmpty(a)||a.forEach(function(a){isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a);}),[]}function queueIfNotInitialized(a,b){return !b.isInitialized()&&(b.ready(function(){a();}),!0)}
1769
+ try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function queueIfNotInitialized(a,b){return !b.isInitialized()&&(b.ready(function(){a();}),!0)}
1769
1770
 
1770
1771
  // This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise!
1771
1772
  var mockFunction=function(){return null},_BatchValidator=/** @class */function(){function a(){}return a.prototype.getMPInstance=function(){return {// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method
@@ -154,7 +154,7 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
154
154
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
155
155
  };
156
156
 
157
- var version = "2.30.2";
157
+ var version = "2.30.4";
158
158
 
159
159
  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
160
160
  },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
@@ -1128,6 +1128,9 @@ throw new Error("Uncaught HTTP Error ".concat(e.status,"."));case 5:return [3/*b
1128
1128
  function hasMPIDAndUserLoginChanged(a,b){return !a||b.getMPID()!==a.getMPID()||a.isLoggedIn()!==b.isLoggedIn()}// https://go.mparticle.com/work/SQDSDKS-6504
1129
1129
  function hasMPIDChanged(a,b){return !a||a.getMPID()&&b.mpid&&b.mpid!==a.getMPID()}
1130
1130
 
1131
+ var _this=undefined;var processReadyQueue=function(a){return isEmpty(a)||a.forEach(function(a){isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a);}),[]};var processPreloadedItem=function(a){var b=a,c=b.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it
1132
+ if("undefined"!=typeof window&&window.mParticle&&window.mParticle[b[0]])window.mParticle[c].apply(_this,b);else {var d=c.split(".");try{for(var e,f=window.mParticle,g=0,h=d;g<h.length;g++)e=h[g],f=f[e];f.apply(_this,b);}catch(a){throw new Error("Unable to compute proper mParticle function "+a)}}};
1133
+
1131
1134
  var Messages$3=Constants.Messages,HTTPCodes$3=Constants.HTTPCodes,FeatureFlags$1=Constants.FeatureFlags,IdentityMethods=Constants.IdentityMethods,ErrorMessages=Messages$3.ErrorMessages,CacheIdentity=FeatureFlags$1.CacheIdentity,Identify=IdentityMethods.Identify,Modify$1=IdentityMethods.Modify,Login=IdentityMethods.Login,Logout=IdentityMethods.Logout;function Identity(t){var r=t._Helpers,s=r.getFeatureFlag,i=r.extend,n=this;// https://go.mparticle.com/work/SQDSDKS-6353
1132
1135
  /**
1133
1136
  * Invoke these methods on the mParticle.Identity object.
@@ -1300,7 +1303,7 @@ return t._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)?void(null===s.audie
1300
1303
  * @deprecated
1301
1304
  */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(i,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=getNewIdentitiesByName(v),k=o===Modify$1?_:P;// https://go.mparticle.com/work/SQDSDKS-6501
1302
1305
  n.sendUserIdentityChangeEvent(C,o,p.mpid,k);}if(a){var f=0===r.status?HTTPCodes$3.noHttpCoverage:r.status;t._Helpers.invokeCallback(a,f,p||null,y);}else p&&!isEmpty(p.errors)&&// https://go.mparticle.com/work/SQDSDKS-6500
1303
- 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);}},this.sendUserIdentityChangeEvent=function(e,r,s,i){if(s||r===Modify$1)// https://go.mparticle.com/work/SQDSDKS-6501
1306
+ 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
1304
1307
  {// https://go.mparticle.com/work/SQDSDKS-6354
1305
1308
  var a=this.IdentityAPI.getUser(s);for(var d in e)// Verifies a change actually happened
1306
1309
  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
@@ -1753,9 +1756,9 @@ function completeSDKInitialization(a,b,c){var d=createKitBlocker(b,c);// Web Vie
1753
1756
  // responsible for sending events directly to mParticle's servers. The Web SDK will not initialize
1754
1757
  // persistence or Identity directly.
1755
1758
  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
1756
- 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(),c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,e,f,g);}c._Store.isInitialized=!0;// Call any functions that are waiting for the library to be initialized
1757
- try{c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue);}catch(a){c.Logger.error(a);}// https://go.mparticle.com/work/SQDSDKS-6040
1758
- c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}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:
1759
+ 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(),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
1760
+ // if an identify request is unnecessary, such as if there is an existing session
1761
+ (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);}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:
1759
1762
  1. Manually via config.dataPlanOptions (this takes priority)
1760
1763
  If not passed in manually, we user the server provided via either
1761
1764
  2. Snippet via /mparticle.js endpoint (config.dataPlan.document)
@@ -1763,9 +1766,7 @@ c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}function createKitBlocker(a,b){va
1763
1766
  */return a.dataPlanOptions&&(b.Logger.verbose("Customer provided data plan found"),f=a.dataPlanOptions,d={document:{dtpn:{vers:f.dataPlanVersion,blok:{ev:f.blockEvents,ea:f.blockEventAttributes,ua:f.blockUserAttributes,id:f.blockUserIdentities}}}}),d||(a.dataPlan&&a.dataPlan.document?a.dataPlan.document.error_message?e=a.dataPlan.document.error_message:(b.Logger.verbose("Data plan found from mParticle.js"),d=a.dataPlan):a.dataPlanResult&&(a.dataPlanResult.error_message?e=a.dataPlanResult.error_message:(b.Logger.verbose("Data plan found from /config"),d={document:a.dataPlanResult}))),e&&b.Logger.error(e),d&&(c=new KitBlocker(d,b)),c}function createIdentityCache(a){return new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"),{logger:a.Logger})}function runPreConfigFetchInitialization(a,b,c){a.Logger=new Logger(c),a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(StartingInitialization);// Check to see if localStorage is available before main configuration runs
1764
1767
  // since we will need this for the current implementation of user persistence
1765
1768
  // TODO: Refactor this when we refactor User Identity Persistence
1766
- try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function processPreloadedItem(a){var b=a,c=b.splice(0,1)[0];// if the first argument is a method on the base mParticle object, run it
1767
- if(mParticle[b[0]])mParticle[c].apply(this,b);else {var d=c.split(".");try{for(var e,f=mParticle,g=0;g<d.length;g++)e=d[g],f=f[e];f.apply(this,b);}catch(a){throw new Error("Unable to compute proper mParticle function "+a)}}}function processReadyQueue(a){// https://go.mparticle.com/work/SQDSDKS-6835
1768
- return isEmpty(a)||a.forEach(function(a){isFunction(a)?a():Array.isArray(a)&&processPreloadedItem(a);}),[]}function queueIfNotInitialized(a,b){return !b.isInitialized()&&(b.ready(function(){a();}),!0)}
1769
+ try{a._Store.isLocalStorageAvailable=a._Persistence.determineLocalStorageAvailability(window.localStorage);}catch(b){a.Logger.warning("localStorage is not available, using cookies if available"),a._Store.isLocalStorageAvailable=!1;}}function processIdentityCallback(a,b,c,d){!a._Store.identifyCalled&&a._Store.SDKConfig.identityCallback&&b&&c&&a._Store.SDKConfig.identityCallback({httpCode:HTTPCodes.activeSession,getUser:function getUser(){return a._Identity.mParticleUser(c)},getPreviousUser:function getPreviousUser(){var b=a.Identity.getUsers(),d=b.shift(),e=d.getMPID();return d&&e===c&&(d=b.shift()),d||null},body:{mpid:c,is_logged_in:a._Store.isLoggedIn,matched_identities:d,context:null,is_ephemeral:!1}});}function queueIfNotInitialized(a,b){return !b.isInitialized()&&(b.ready(function(){a();}),!0)}
1769
1770
 
1770
1771
  // This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise!
1771
1772
  var mockFunction=function(){return null},_BatchValidator=/** @class */function(){function a(){}return a.prototype.getMPInstance=function(){return {// Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method
package/dist/mparticle.js CHANGED
@@ -393,7 +393,7 @@ var mParticle = (function () {
393
393
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
394
394
  };
395
395
 
396
- var version = "2.30.2";
396
+ var version = "2.30.4";
397
397
 
398
398
  var Constants = {
399
399
  sdkVersion: version,
@@ -7047,6 +7047,41 @@ var mParticle = (function () {
7047
7047
  return !prevUser || prevUser.getMPID() && identityApiResult.mpid && identityApiResult.mpid !== prevUser.getMPID();
7048
7048
  }
7049
7049
 
7050
+ var _this = undefined;
7051
+ var processReadyQueue = function processReadyQueue(readyQueue) {
7052
+ if (!isEmpty(readyQueue)) {
7053
+ readyQueue.forEach(function (readyQueueItem) {
7054
+ if (isFunction(readyQueueItem)) {
7055
+ readyQueueItem();
7056
+ } else if (Array.isArray(readyQueueItem)) {
7057
+ processPreloadedItem(readyQueueItem);
7058
+ }
7059
+ });
7060
+ }
7061
+ return [];
7062
+ };
7063
+ var processPreloadedItem = function processPreloadedItem(readyQueueItem) {
7064
+ var args = readyQueueItem;
7065
+ var method = args.splice(0, 1)[0];
7066
+ // if the first argument is a method on the base mParticle object, run it
7067
+ if (typeof window !== 'undefined' && window.mParticle && window.mParticle[args[0]]) {
7068
+ window.mParticle[method].apply(_this, args);
7069
+ // otherwise, the method is on either eCommerce or Identity objects, ie. "eCommerce.setCurrencyCode", "Identity.login"
7070
+ } else {
7071
+ var methodArray = method.split('.');
7072
+ try {
7073
+ var computedMPFunction = window.mParticle;
7074
+ for (var _i = 0, methodArray_1 = methodArray; _i < methodArray_1.length; _i++) {
7075
+ var currentMethod = methodArray_1[_i];
7076
+ computedMPFunction = computedMPFunction[currentMethod];
7077
+ }
7078
+ computedMPFunction.apply(_this, args);
7079
+ } catch (e) {
7080
+ throw new Error('Unable to compute proper mParticle function ' + e);
7081
+ }
7082
+ }
7083
+ };
7084
+
7050
7085
  var Messages$3 = Constants.Messages,
7051
7086
  HTTPCodes$3 = Constants.HTTPCodes,
7052
7087
  FeatureFlags$1 = Constants.FeatureFlags,
@@ -8051,6 +8086,8 @@ var mParticle = (function () {
8051
8086
  }
8052
8087
  mpInstance.Logger.error('Error parsing JSON response from Identity server: ' + e);
8053
8088
  }
8089
+ mpInstance._Store.isInitialized = true;
8090
+ mpInstance._preInit.readyQueue = processReadyQueue(mpInstance._preInit.readyQueue);
8054
8091
  };
8055
8092
 
8056
8093
  // send a user identity change request on identify, login, logout, modify when any values change.
@@ -10287,13 +10324,12 @@ var mParticle = (function () {
10287
10324
  mpInstance._Events.logAST();
10288
10325
  processIdentityCallback(mpInstance, currentUser, currentUserMPID, currentUserIdentities);
10289
10326
  }
10290
- mpInstance._Store.isInitialized = true;
10291
10327
 
10292
- // Call any functions that are waiting for the library to be initialized
10293
- try {
10328
+ // We will continue to clear out the ready queue as part of the initial init flow
10329
+ // if an identify request is unnecessary, such as if there is an existing session
10330
+ if (mpInstance._Store.mpid && !mpInstance._Store.identifyCalled || mpInstance._Store.webviewBridgeEnabled) {
10331
+ mpInstance._Store.isInitialized = true;
10294
10332
  mpInstance._preInit.readyQueue = processReadyQueue(mpInstance._preInit.readyQueue);
10295
- } catch (error) {
10296
- mpInstance.Logger.error(error);
10297
10333
  }
10298
10334
 
10299
10335
  // https://go.mparticle.com/work/SQDSDKS-6040
@@ -10410,40 +10446,6 @@ var mParticle = (function () {
10410
10446
  });
10411
10447
  }
10412
10448
  }
10413
- function processPreloadedItem(readyQueueItem) {
10414
- var args = readyQueueItem;
10415
- var method = args.splice(0, 1)[0];
10416
- // if the first argument is a method on the base mParticle object, run it
10417
- if (mParticle[args[0]]) {
10418
- mParticle[method].apply(this, args);
10419
- // otherwise, the method is on either eCommerce or Identity objects, ie. "eCommerce.setCurrencyCode", "Identity.login"
10420
- } else {
10421
- var methodArray = method.split('.');
10422
- try {
10423
- var computedMPFunction = mParticle;
10424
- for (var i = 0; i < methodArray.length; i++) {
10425
- var currentMethod = methodArray[i];
10426
- computedMPFunction = computedMPFunction[currentMethod];
10427
- }
10428
- computedMPFunction.apply(this, args);
10429
- } catch (e) {
10430
- throw new Error('Unable to compute proper mParticle function ' + e);
10431
- }
10432
- }
10433
- }
10434
- function processReadyQueue(readyQueue) {
10435
- if (!isEmpty(readyQueue)) {
10436
- readyQueue.forEach(function (readyQueueItem) {
10437
- if (isFunction(readyQueueItem)) {
10438
- readyQueueItem();
10439
- } else if (Array.isArray(readyQueueItem)) {
10440
- processPreloadedItem(readyQueueItem);
10441
- }
10442
- });
10443
- }
10444
- // https://go.mparticle.com/work/SQDSDKS-6835
10445
- return [];
10446
- }
10447
10449
  function queueIfNotInitialized(func, self) {
10448
10450
  if (!self.isInitialized()) {
10449
10451
  self.ready(function () {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.30.2",
3
+ "version": "2.30.4",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
package/src/identity.js CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  } from './utils';
19
19
  import { hasMPIDAndUserLoginChanged, hasMPIDChanged } from './user-utils';
20
20
  import { getNewIdentitiesByName } from './type-utils';
21
+ import { processReadyQueue } from './pre-init-utils';
21
22
 
22
23
  export default function Identity(mpInstance) {
23
24
  const { getFeatureFlag, extend } = mpInstance._Helpers;
@@ -1679,6 +1680,11 @@ export default function Identity(mpInstance) {
1679
1680
  'Error parsing JSON response from Identity server: ' + e
1680
1681
  );
1681
1682
  }
1683
+ mpInstance._Store.isInitialized = true;
1684
+
1685
+ mpInstance._preInit.readyQueue = processReadyQueue(
1686
+ mpInstance._preInit.readyQueue
1687
+ );
1682
1688
  };
1683
1689
 
1684
1690
  // send a user identity change request on identify, login, logout, modify when any values change.
@@ -36,10 +36,11 @@ import Consent from './consent';
36
36
  import KitBlocker from './kitBlocking';
37
37
  import ConfigAPIClient from './configAPIClient';
38
38
  import IdentityAPIClient from './identityApiClient';
39
- import { isEmpty, isFunction } from './utils';
39
+ import { isFunction } from './utils';
40
40
  import { LocalStorageVault } from './vault';
41
41
  import { removeExpiredIdentityCacheDates } from './identity-utils';
42
42
  import IntegrationCapture from './integrationCapture';
43
+ import { processReadyQueue } from './pre-init-utils';
43
44
 
44
45
  const { Messages, HTTPCodes, FeatureFlags } = Constants;
45
46
  const { ReportBatching, CaptureIntegrationSpecificIds } = FeatureFlags;
@@ -1361,15 +1362,17 @@ function completeSDKInitialization(apiKey, config, mpInstance) {
1361
1362
  );
1362
1363
  }
1363
1364
 
1364
- mpInstance._Store.isInitialized = true;
1365
+ // We will continue to clear out the ready queue as part of the initial init flow
1366
+ // if an identify request is unnecessary, such as if there is an existing session
1367
+ if (
1368
+ (mpInstance._Store.mpid && !mpInstance._Store.identifyCalled) ||
1369
+ mpInstance._Store.webviewBridgeEnabled
1370
+ ) {
1371
+ mpInstance._Store.isInitialized = true;
1365
1372
 
1366
- // Call any functions that are waiting for the library to be initialized
1367
- try {
1368
1373
  mpInstance._preInit.readyQueue = processReadyQueue(
1369
1374
  mpInstance._preInit.readyQueue
1370
1375
  );
1371
- } catch (error) {
1372
- mpInstance.Logger.error(error);
1373
1376
  }
1374
1377
 
1375
1378
  // https://go.mparticle.com/work/SQDSDKS-6040
@@ -1508,42 +1511,6 @@ function processIdentityCallback(
1508
1511
  }
1509
1512
  }
1510
1513
 
1511
- function processPreloadedItem(readyQueueItem) {
1512
- const args = readyQueueItem;
1513
- const method = args.splice(0, 1)[0];
1514
- // if the first argument is a method on the base mParticle object, run it
1515
- if (mParticle[args[0]]) {
1516
- mParticle[method].apply(this, args);
1517
- // otherwise, the method is on either eCommerce or Identity objects, ie. "eCommerce.setCurrencyCode", "Identity.login"
1518
- } else {
1519
- const methodArray = method.split('.');
1520
- try {
1521
- var computedMPFunction = mParticle;
1522
- for (let i = 0; i < methodArray.length; i++) {
1523
- const currentMethod = methodArray[i];
1524
- computedMPFunction = computedMPFunction[currentMethod];
1525
- }
1526
- computedMPFunction.apply(this, args);
1527
- } catch (e) {
1528
- throw new Error('Unable to compute proper mParticle function ' + e);
1529
- }
1530
- }
1531
- }
1532
-
1533
- function processReadyQueue(readyQueue) {
1534
- if (!isEmpty(readyQueue)) {
1535
- readyQueue.forEach(function(readyQueueItem) {
1536
- if (isFunction(readyQueueItem)) {
1537
- readyQueueItem();
1538
- } else if (Array.isArray(readyQueueItem)) {
1539
- processPreloadedItem(readyQueueItem);
1540
- }
1541
- });
1542
- }
1543
- // https://go.mparticle.com/work/SQDSDKS-6835
1544
- return [];
1545
- }
1546
-
1547
1514
  function queueIfNotInitialized(func, self) {
1548
1515
  if (!self.isInitialized()) {
1549
1516
  self.ready(function() {
@@ -0,0 +1,36 @@
1
+ import { isEmpty, isFunction } from './utils';
2
+
3
+ export const processReadyQueue = (readyQueue): Function[] => {
4
+ if (!isEmpty(readyQueue)) {
5
+ readyQueue.forEach(readyQueueItem => {
6
+ if (isFunction(readyQueueItem)) {
7
+ readyQueueItem();
8
+ } else if (Array.isArray(readyQueueItem)) {
9
+ processPreloadedItem(readyQueueItem);
10
+ }
11
+ });
12
+ }
13
+ return [];
14
+ };
15
+
16
+ const processPreloadedItem = (readyQueueItem): void => {
17
+ const args = readyQueueItem;
18
+ const method = args.splice(0, 1)[0];
19
+
20
+ // if the first argument is a method on the base mParticle object, run it
21
+ if (typeof window !== 'undefined' && window.mParticle && window.mParticle[args[0]]) {
22
+ window.mParticle[method].apply(this, args);
23
+ // otherwise, the method is on either eCommerce or Identity objects, ie. "eCommerce.setCurrencyCode", "Identity.login"
24
+ } else {
25
+ const methodArray = method.split('.');
26
+ try {
27
+ let computedMPFunction = window.mParticle;
28
+ for (const currentMethod of methodArray) {
29
+ computedMPFunction = computedMPFunction[currentMethod];
30
+ }
31
+ ((computedMPFunction as unknown) as Function).apply(this, args);
32
+ } catch (e) {
33
+ throw new Error('Unable to compute proper mParticle function ' + e);
34
+ }
35
+ }
36
+ };