if (typeof globalThis !== 'undefined') {globalThis.regeneratorRuntime = undefined}
// Base64 encoder/decoder - http://www.webtoolkit.info/javascript_base64.html
var Base64$1={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",// Input must be a string
encode:function(a){try{if(window.btoa&&window.atob)return window.btoa(unescape(encodeURIComponent(a)))}catch(a){console.error("Error encoding cookie values into Base64:"+a);}return this._encode(a)},_encode:function(a){var b,c,d,e,f,g,h,j="",k=0;for(a=UTF8.encode(a);k>2,f=(3&b)<<4|c>>4,g=(15&c)<<2|d>>6,h=63&d,isNaN(c)?g=h=64:isNaN(d)&&(h=64),j=j+Base64$1._keyStr.charAt(e)+Base64$1._keyStr.charAt(f)+Base64$1._keyStr.charAt(g)+Base64$1._keyStr.charAt(h);return j},decode:function(a){try{if(window.btoa&&window.atob)return decodeURIComponent(escape(window.atob(a)))}catch(a){//log(e);
}return Base64$1._decode(a)},_decode:function(a){var b,c,d,e,f,g,h,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k>4,c=(15&f)<<4|g>>2,d=(3&g)<<6|h,j+=String.fromCharCode(b),64!==g&&(j+=String.fromCharCode(c)),64!==h&&(j+=String.fromCharCode(d));return j=UTF8.decode(j),j}},UTF8={encode:function(a){for(var b,d="",e=0;eb?d+=String.fromCharCode(b):127b?(d+=String.fromCharCode(192|b>>6),d+=String.fromCharCode(128|63&b)):(d+=String.fromCharCode(224|b>>12),d+=String.fromCharCode(128|63&b>>6),d+=String.fromCharCode(128|63&b));return d},decode:function(a){for(var b="",d=0,e=0,f=0,g=0;de?(b+=String.fromCharCode(e),d++):191e?(f=a.charCodeAt(d+1),b+=String.fromCharCode((31&e)<<6|63&f),d+=2):(f=a.charCodeAt(d+1),g=a.charCodeAt(d+2),b+=String.fromCharCode((15&e)<<12|(63&f)<<6|63&g),d+=3);return b}};var Polyfill = {// forEach polyfill
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
forEach:function forEach(a,b){var c,d;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),f=e.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(1>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(1>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=2<=arguments.length?arguments[1]:void 0,f=0;f 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var Messages$a=Constants.Messages,createCookieString=function(a){return replaceCommasWithPipes(replaceQuotesWithApostrophes(a))},revertCookieString=function(a){return replacePipesWithCommas(replaceApostrophesWithQuotes(a))},inArray=function(a,b){if(!a)return !1;var c=0;if(Array.prototype.indexOf)return 0<=a.indexOf(b,0);for(var d=a.length;c>c/4).toString(16):(c^16*Math.random()>>c/4).toString(16)},generateUniqueId=function(b){return void 0===b&&(b=""),b// if the placeholder was passed, return
?generateRandomValue()// if the placeholder was passed, return
:// [1e7] -> // 10000000 +
// -1e3 -> // -1000 +
// -4e3 -> // -4000 +
// -8e3 -> // -80000000 +
// -1e11 -> //-100000000000,
"".concat(1e7,"-").concat(1e3,"-").concat(4e3,"-").concat(8e3,"-").concat(1e11).replace(/[018]/g,// zeroes, ones, and eights with
generateUniqueId// random hex digits
)},getRampNumber=function(a){if(!a)return 100;var b=generateHash(a);return Math.abs(b%100)+1},isObject=function(a){var b=Object.prototype.toString.call(a);return "[object Object]"===b||"[object Error]"===b},parseNumber=function(a){if(isNaN(a)||!isFinite(a))return 0;var b=parseFloat(a);return isNaN(b)?0:b},parseSettingsString=function(a){try{return a?JSON.parse(a.replace(/"/g,"\"")):[]}catch(a){throw new Error("Settings string contains invalid JSON")}},parseStringOrNumber=function(a){return isStringOrNumber(a)?a:null},replaceCommasWithPipes=function(a){return a.replace(/,/g,"|")},replacePipesWithCommas=function(a){return a.replace(/\|/g,",")},replaceApostrophesWithQuotes=function(a){return a.replace(/\'/g,"\"")},replaceQuotesWithApostrophes=function(a){return a.replace(/\"/g,"'")},replaceMPID=function(a,b){return a.replace("%%mpid%%",b)},replaceAmpWithAmpersand=function(a){return a.replace(/&/g,"&")},createCookieSyncUrl=function(a,b,c,d){var e=replaceAmpWithAmpersand(b),f=c?replaceAmpWithAmpersand(c):null,g=replaceMPID(e,a),h=f?replaceMPID(f,a):"",i=g+encodeURIComponent(h);if(d){var j=i.includes("?")?"&":"?";i+="".concat(j,"domain=").concat(d);}return i},returnConvertedBoolean=function(a){return "false"!==a&&"0"!==a&&!!a},decoded=function(a){return decodeURIComponent(a.replace(/\+/g," "))},converted=function(a){return 0===a.indexOf("\"")&&(a=a.slice(1,-1).replace(/\\"/g,"\"").replace(/\\\\/g,"\\")),a},isString=function(a){return "string"==typeof a},isNumber=function(a){return "number"==typeof a},isBoolean=function(a){return "boolean"==typeof a},isFunction=function(a){return "function"==typeof a},isValidAttributeValue=function(a){return a!==void 0&&!isObject(a)&&!Array.isArray(a)},isValidCustomFlagProperty=function(a){return isNumber(a)||isString(a)||isBoolean(a)},toDataPlanSlug=function(a){// Make sure we are only acting on strings or numbers
return isStringOrNumber(a)?a.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g,"_"):""},isDataPlanSlug=function(a){return a===toDataPlanSlug(a)},isStringOrNumber=function(a){return isString(a)||isNumber(a)},isEmpty=function(a){return null==a||!(Object.keys(a)||a).length},moveElementToEnd=function(a,b){return a.slice(0,b).concat(a.slice(b+1),a[b])},queryStringParser=function(a,b){void 0===b&&(b=[]);var c,d={},e={};if(!a)return d;if("undefined"!=typeof URL&&"undefined"!=typeof URLSearchParams){var f=new URL(a);c=new URLSearchParams(f.search);}else c=queryStringParserFallback(a);return (c.forEach(function(a,b){e[b.toLowerCase()]=a;}),isEmpty(b))?e:(b.forEach(function(a){var b=e[a.toLowerCase()];b&&(d[a]=b);}),d)},queryStringParserFallback=function(a){var b={},c=a.split("?")[1]||"",d=c.split("&");return d.forEach(function(a){var c=a.split("="),d=c[0],e=c.slice(1),f=e.join("=");if(d&&void 0!==f)try{b[d]=decodeURIComponent(f||"");}catch(a){console.error("Failed to decode value for key ".concat(d,": ").concat(a));}}),{get:function get(a){return b[a]},forEach:function forEach(a){for(var c in b)b.hasOwnProperty(c)&&a(b[c],c);}}},getCookies=function(a){// Helper function to parse cookies from document.cookie
var b=function parseCookies(){try{return "undefined"==typeof window?[]:window.document.cookie.split(";").map(function(a){return a.trim()})}catch(a){return console.error("Unable to parse cookies",a),[]}}();// Helper function to filter cookies by keys
// Parse cookies from document.cookie
// Filter cookies by keys if provided
return function filterCookies(a,b){for(var c={},d=0,e=a;db.length)return null;for(var d,e=c._IntegrationCapture,f=c._Helpers,g=f.getFeatureFlag,h=c.Identity.getCurrentUser(),i=[],j=null,k=0,l=b;k=a.MINIMUM_INTERVAL_MILLIS,this.uploadIntervalMillis=f},a.prototype.shouldDebounceAndUpdateLastASTTime=function(){var a=Date.now();return !!(a-this.lastASTEventTimej.status)this.mpInstance.Logger.verbose("Upload success for request ID: ".concat(d[f].source_request_id));else {if(500<=j.status||429===j.status)// Server error, add back current batches and try again later
return this.mpInstance.Logger.error("HTTP error status ".concat(j.status," received")),[2/*return*/,d.slice(f,d.length)];if(401<=j.status)//if we're getting a 401, assume we'll keep getting a 401 and clear the uploads.
return this.mpInstance.Logger.error("HTTP error status ".concat(j.status," while uploading - please verify your API key.")),[2/*return*/,null];throw console.error("HTTP error status ".concat(j.status," while uploading events."),j),new Error("Uncaught HTTP Error ".concat(j.status,". Batch upload will be re-attempted."))}return [3/*break*/,5];case 4:return k=i.sent(),this.mpInstance.Logger.error("Error sending event to mParticle servers. ".concat(k)),[2/*return*/,d.slice(f,d.length)];case 5:return f++,[3/*break*/,1];case 6:return [2/*return*/,null]}})})},a.CONTENT_TYPE="text/plain;charset=UTF-8",a.MINIMUM_INTERVAL_MILLIS=500,a)}();
var ErrorCodes={UNKNOWN_ERROR:"UNKNOWN_ERROR",UNHANDLED_EXCEPTION:"UNHANDLED_EXCEPTION",IDENTITY_REQUEST:"IDENTITY_REQUEST",IDENTITY_MISMATCH:"IDENTITY_MISMATCH",ROKT_KIT_ATTACHED:"ROKT_KIT_ATTACHED"};var WSDKErrorSeverity={ERROR:"ERROR",INFO:"INFO",WARNING:"WARNING"};
var Modify$4=Constants.IdentityMethods.Modify,Validators={// From ./utils
// Utility Functions for backwards compatability
isNumber:isNumber,isFunction:isFunction,isStringOrNumber:isStringOrNumber,// Validator Functions
isValidAttributeValue:isValidAttributeValue,// Validator Functions
// Neither null nor undefined can be a valid Key
isValidKeyValue:function isValidKeyValue(a){return !(!a||isObject(a)||Array.isArray(a)||this.isFunction(a))},removeFalsyIdentityValues:function removeFalsyIdentityValues(a,b){if(!a||!a.userIdentities)return a;var c={},d=__assign({},a.userIdentities);for(var e in a.userIdentities)if(a.userIdentities.hasOwnProperty(e)){var f=a.userIdentities[e];// Check if value is falsy (undefined, false, 0, '', etc.) but not null
null===f||f||(b.warning("Identity value for '".concat(e,"' is falsy (").concat(f,"). This value will be removed from the request.")),delete d[e]);}return c.userIdentities=d,c},validateIdentities:function validateIdentities(a,b){var c={userIdentities:1,onUserAlias:1,copyUserAttributes:1};if(a){if(b===Modify$4&&(isObject(a.userIdentities)&&!Object.keys(a.userIdentities).length||!isObject(a.userIdentities)))return {valid:!1,error:Constants.Messages.ValidationMessages.ModifyIdentityRequestUserIdentitiesPresent};for(var d in a)if(a.hasOwnProperty(d)){if(!c[d])return {valid:!1,error:Constants.Messages.ValidationMessages.IdentityRequesetInvalidKey};if("onUserAlias"===d&&!Validators.isFunction(a[d]))return {valid:!1,error:Constants.Messages.ValidationMessages.OnUserAliasType}}if(0===Object.keys(a).length)return {valid:!0};// identityApiData.userIdentities can't be undefined
if(void 0===a.userIdentities)return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentities};// identityApiData.userIdentities can be null, but if it isn't null or undefined (above conditional), it must be an object
if(null!==a.userIdentities&&!isObject(a.userIdentities))return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentities};if(isObject(a.userIdentities)&&Object.keys(a.userIdentities).length)for(var e in a.userIdentities)if(a.userIdentities.hasOwnProperty(e)){if(!1===Types.IdentityType.getIdentityType(e))return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentitiesInvalidKey};if("string"!=typeof a.userIdentities[e]&&null!==a.userIdentities[e])return {valid:!1,error:Constants.Messages.ValidationMessages.UserIdentitiesInvalidValues}}}return {valid:!0}}};
var HTTPCodes$4=Constants.HTTPCodes;/**
* Sends a POST to mParticle's IDSync Search endpoint and invokes `callback`
* with the HTTP status and parsed body.
*
* Defensive contract:
* - No identifier with a non-empty string value -> callback with
* `{ httpCode: noHttpCoverage }`, no network call.
* - Missing `apiKey` -> callback with `{ httpCode: noHttpCoverage }`,
* no network call.
* - Network/JSON-parse errors are caught and surfaced via the callback,
* never thrown. Network errors are also reported through the optional
* `errorReporter` so any registered IErrorReportingService can observe
* them (matches the pattern used by identifyRequest in identityApiClient).
*/var sendSearchRequest=function(a,b,c,d,e,f,g,h){return __awaiter(void 0,void 0,void 0,function(){var i,j,k,l,m,n,o,p,r,s,t,u;return __generator(this,function(v){switch(v.label){case 0:// Validate the callback up front. If it isn't a function we have nowhere
// to deliver a result to, so log and bail out without invoking anything.
if(!isFunction(e))return f.error("search called without a callback function; skipping request."),[2/*return*/];// No usable identifier -> deliver httpCode: noHttpCoverage so callers
// waiting on the callback (e.g. to clear a loading state) don't hang.
if(i=function(a){try{e(a);}catch(a){f.error("Error invoking search callback: "+((null===a||void 0===a?void 0:a.message)||a+""));}},j=Validators.removeFalsyIdentityValues({userIdentities:null!==a&&void 0!==a?a:{}},f).userIdentities,!Object.values(null!==j&&void 0!==j?j:{}).some(function(a){return "string"==typeof a&&0 same: deliver noHttpCoverage rather than hanging.
if(!b)return f.verbose("search called without a workspace API key; skipping request."),i({httpCode:HTTPCodes$4.noHttpCoverage}),[2/*return*/];v.label=1;case 1:return v.trys.push([1,9,,10]),k=c(),l=__assign(__assign({},k),{known_identities:__assign({},j)}),m={method:"post",headers:{Accept:"application/json","Content-Type":"application/json","x-mp-key":b},body:JSON.stringify(l)},n=g||(window.fetch?new FetchUploader(d):new XHRUploader(d)),f.verbose("Sending search request to "+d),[4/*yield*/,n.upload(m,d)];case 2:if(o=v.sent(),p=void 0,!isFunction(o.json))return [3/*break*/,7];v.label=3;case 3:return v.trys.push([3,5,,6]),[4/*yield*/,o.json()];case 4:return p=v.sent(),[3/*break*/,6];case 5:return v.sent(),f.verbose("search response had no parseable JSON body."),[3/*break*/,6];case 6:return [3/*break*/,8];case 7:if(r=o,null===r||void 0===r?void 0:r.responseText)try{p=JSON.parse(r.responseText);}catch(a){f.verbose("search XHR response was not valid JSON.");}v.label=8;case 8:return o.status===HTTP_OK?f.verbose("search received 200 OK."):o.status===HTTP_NOT_FOUND?f.verbose("search received 404 (no match)."):f.verbose("search received non-success status "+o.status),i({httpCode:o.status,body:p}),[3/*break*/,10];case 9:return s=v.sent(),t=(null===s||void 0===s?void 0:s.message)||s+"",u="Error sending search request: "+t,f.error(u),null===h||void 0===h?void 0:h.report({message:u,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),i({httpCode:HTTPCodes$4.noHttpCoverage}),[3/*break*/,10];case 10:return [2/*return*/]}})})};
var _a=Constants.IdentityMethods,Identify$2=_a.Identify,Modify$3=_a.Modify,Login$2=_a.Login,Logout$2=_a.Logout,HTTPCodes$3=Constants.HTTPCodes,Messages$9=Constants.Messages;var CACHE_HEADER="x-mp-max-age";var cacheOrClearIdCache=function(a,b,c,d,e){// when parsing a response that has already been cached, simply return instead of attempting another cache
if(!e){// default the expire timestamp to one day in milliseconds unless a header comes back
var f=getExpireTimestamp(null===d||void 0===d?void 0:d.cacheMaxAge);a===Login$2||a===Identify$2?cacheIdentityRequest(a,b,f,c,d):a===Modify$3||a===Logout$2?c.purge():void 0;}};var cacheIdentityRequest=function(a,b,c,d,e){var f=e.responseText,g=e.status,h=d.retrieve()||{},i=concatenateIdentities(a,b),j=generateHash(i),k=f.mpid,l=f.is_logged_in;h[j]={responseText:JSON.stringify({mpid:k,is_logged_in:l}),status:g,expireTimestamp:c},d.store(h);};// We need to ensure that identities are concatenated in a deterministic way, so
// we sort the identities based on their enum.
// we create an array, set the user identity at the index of the user identity type
var concatenateIdentities=function(a,b){var c="".concat(a,":").concat("device_application_stamp","=").concat(b.device_application_stamp,";"),d=Object.keys(b).length,e="";// set DAS first since it is not an official identity type
if(d){var f=[];// create an array where each index is equal to the user identity type
for(var g in b)if(g==="device_application_stamp")continue;else f[Types.IdentityType.getIdentityType(g)]=b[g];e=f.reduce(function(a,b,c){var d=Types.IdentityType.getIdentityName(c);return "".concat(a).concat(d,"=").concat(b,";")},c);}return e};var hasValidCachedIdentity=function(a,b,c){// There is an edge case where multiple identity calls are taking place
// before identify fires, so there may not be a cache. See what happens when
// the ? in idCache is removed to the following test
// "queued events contain login mpid instead of identify mpid when calling
// login immediately after mParticle initializes"
var d=null===c||void 0===c?void 0:c.retrieve();// if there is no cache, then there is no valid cached identity
if(!d)return !1;var e=concatenateIdentities(a,b),f=generateHash(e);// if cache doesn't have the cacheKey, there is no valid cached identity
if(!d.hasOwnProperty(f))return !1;// If there is a valid cache key, compare the expireTimestamp to the current time.
// If the current time is greater than the expireTimestamp, it is not a valid
// cached identity.
var g=d[f].expireTimestamp;return !(ga._Store.SDKConfig.integrationDelayTimeout)return !1;for(var e in b){if(!0===b[e])return !0;continue}return !1},this.createMainStorageName=function(a){return a?StorageNames$1.currentStorageName+"_"+a:StorageNames$1.currentStorageName},this.converted=converted,this.findKeyInObject=findKeyInObject,this.parseNumber=parseNumber,this.inArray=inArray,this.isObject=isObject,this.decoded=decoded,this.parseStringOrNumber=parseStringOrNumber,this.generateHash=generateHash,this.generateUniqueId=generateUniqueId,this.Validators=Validators;}
var Messages$8=Constants.Messages,androidBridgeNameBase="mParticleAndroid",iosBridgeNameBase="mParticle";function NativeSdkHelpers(a){var b=this;this.initializeSessionAttributes=function(a){var c=Constants.NativeSdkPaths.SetSessionAttribute,d=JSON.stringify({key:"$src_env",value:"webview"}),e=JSON.stringify({key:"$src_key",value:a});b.sendToNative(c,d),a&&b.sendToNative(c,e);},this.isBridgeV2Available=function(a){if(!a)return !1;var b=iosBridgeNameBase+"_"+a+"_v2";// iOS v2 bridge
return !!(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.hasOwnProperty(b))||!!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName===b)||!!window.hasOwnProperty(androidBridgeNameBase+"_"+a+"_v2");// other iOS v2 bridge
// TODO: what to do about people setting things on mParticle itself?
// android
},this.isWebviewEnabled=function(c,d){return a._Store.bridgeV2Available=b.isBridgeV2Available(c),a._Store.bridgeV1Available=b.isBridgeV1Available(),2===d?a._Store.bridgeV2Available:!(window.mParticle&&window.mParticle.uiwebviewBridgeName&&window.mParticle.uiwebviewBridgeName!==iosBridgeNameBase+"_"+c+"_v2")&&!!(2>d)&&(a._Store.bridgeV2Available||a._Store.bridgeV1Available);// iOS BridgeV1 can be available via mParticle.isIOS, but return false if uiwebviewBridgeName doesn't match requiredWebviewBridgeName
},this.isBridgeV1Available=function(){return !!(a._Store.SDKConfig.useNativeSdk||window.mParticleAndroid||a._Store.SDKConfig.isIOS)},this.sendToNative=function(c,d){return a._Store.bridgeV2Available&&2===a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV2Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV2(c,d,a._Store.SDKConfig.requiredWebviewBridgeName):a._Store.bridgeV1Available&&2>a._Store.SDKConfig.minWebviewBridgeVersion?void b.sendViaBridgeV1(c,d):void 0},this.sendViaBridgeV1=function(c,d){window.mParticleAndroid&&window.mParticleAndroid.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),window.mParticleAndroid[c](d)):a._Store.SDKConfig.isIOS&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d));},this.sendViaIframeToIOS=function(a,b){var c=document.createElement("IFRAME");c.setAttribute("src","mp-sdk://"+a+"/"+encodeURIComponent(b)),document.documentElement.appendChild(c),c.parentNode.removeChild(c);},this.sendViaBridgeV2=function(c,d,e){if(e){var f,g,h=window[androidBridgeNameBase+"_"+e+"_v2"],i=iosBridgeNameBase+"_"+e+"_v2";return window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers[i]&&(f=window.webkit.messageHandlers[i]),a.uiwebviewBridgeName===i&&(g=a[i]),h&&h.hasOwnProperty(c)?(a.Logger.verbose(Messages$8.InformationMessages.SendAndroid+c),void h[c](d)):void(f?(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),f.postMessage(JSON.stringify({path:c,value:d?JSON.parse(d):null}))):g&&(a.Logger.verbose(Messages$8.InformationMessages.SendIOS+c),b.sendViaIframeToIOS(c,d)))}};}
var Messages$7=Constants.Messages,InformationMessages=Messages$7.InformationMessages;var DAYS_IN_MILLISECONDS=86400000;// Partner module IDs for cookie sync configurations
var PARTNER_MODULE_IDS={AdobeEventForwarder:11,DoubleclickDFP:41,AppNexus:50,Lotame:58,TradeDesk:103,VerizonMedia:155,Rokt:1277};function CookieSyncManager(a){var b=this;// Public
// Private
this.attemptCookieSync=function(c,d){var e,f=a._Store,g=f.pixelConfigurations,h=f.webviewBridgeEnabled;if(c&&!h&&(null===(e=a._CookieConsentManager)||void 0===e||!e.getNoFunctional()))// When noFunctional is true, persistence is not saved, so we cannot track cookie sync
// dates. Skip cookie sync to avoid running it on every page load.
{var i=a._Persistence.getPersistence();isEmpty(i)||g.forEach(function(e){var f,g,h=!1,j=e.filteringConsentRuleValues,k=e.pixelUrl,l=e.redirectUrl,m=e.moduleId,// Tells you how often we should do a cookie sync (in days)
n=e.frequencyCap,o=(j||{}).values;// set requiresConsent to false to start each additional pixel configuration
// set to true only if filteringConsenRuleValues.values.length exists
// Filtering rules as defined in UI
if(!isEmpty(k)&&(isEmpty(o)||(h=!0),!(h&&d))&&!(m===PARTNER_MODULE_IDS.Rokt&&a._CookieConsentManager.getNoTargeting()))// For Rokt, block cookie sync when noTargeting privacy flag is true
// If MPID is new to cookies, we should not try to perform the cookie sync
// because a cookie sync can only occur once a user either consents or doesn't.
// we should not check if it's enabled if the user has a blank consent
// The Trade Desk requires a URL parameter for GDPR enabled users.
// It is optional but to simplify the code, we add it for all Trade
// // Desk cookie syncs.
// Add domain parameter for Trade Desk
{var p=a._Consent.isEnabledForUserConsent;if(p(j,a.Identity.getCurrentUser())){var q=null!==(g=null===(f=i[c])||void 0===f?void 0:f.csd)&&void 0!==g?g:{},r=q[m]||null;if(isLastSyncDateExpired(n,r)){var s=m===PARTNER_MODULE_IDS.TradeDesk?window.location.hostname:void 0,t=createCookieSyncUrl(c,k,l,s);b.performCookieSync(t,m.toString(),c,q);}}}});}},this.performCookieSync=function(b,c,d,e){var f=document.createElement("img");a.Logger.verbose(InformationMessages.CookieSync),f.onload=function(){e[c]=new Date().getTime(),a._Persistence.saveUserCookieSyncDatesToPersistence(d,e);},f.src=b;};}var isLastSyncDateExpired=function(a,b){// If there is no lastSyncDate, then there is no previous cookie sync, so we should sync the cookie
return !b||new Date().getTime()>new Date(b).getTime()+a*DAYS_IN_MILLISECONDS;// Otherwise, compare the last sync date to determine if it should do a cookie sync again
};
var Messages$6=Constants.Messages;function SessionManager(a){/**
* Checks if the session has expired based on the last event timestamp
* @param lastEventTimestamp - Unix timestamp in milliseconds of the last event
* @param sessionTimeout - Session timeout in minutes
* @returns true if the session has expired, false otherwise
*/function b(a,b){if(!a||!b||0>=b)return !1;var c=Date.now()-a;return c>=6e4*b}/**
* Performs session end operations:
* - Logs a SessionEnd event
* - Nullifies the session ID and related data
* - Resets the time-on-site timer
*/function c(){var b;a._Events.logEvent({messageType:Types.MessageType.SessionEnd}),a._Store.nullifySession(),null===(b=a._timeOnSiteTimer)||void 0===b?void 0:b.resetTimer();}var d=this;this.initialize=function(){var c;if(a._Store.sessionId){var e=a._Store,f=e.dateLastEventSent,g=e.SDKConfig,h=g.sessionTimeout;if(b(null===f||void 0===f?void 0:f.getTime(),h))d.endSession(),d.startNewSession();else {// https://go.mparticle.com/work/SQDSDKS-6045
// https://go.mparticle.com/work/SQDSDKS-6323
var i=a.Identity.getCurrentUser(),j=g.identifyRequest,k=(null===(c=a._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(a._Store);!k&&hasIdentityRequestChanged(i,j)&&(a.Identity.identify(j,g.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null);}}else d.startNewSession();},this.getSession=function(){return a.Logger.warning(generateDeprecationMessage("SessionManager.getSession()",!1,"SessionManager.getSessionId()")),this.getSessionId()},this.getSessionId=function(){return a._Store.sessionId},this.startNewSession=function(){var b;if(a.Logger.verbose(Messages$6.InformationMessages.StartingNewSession),a._Helpers.canLog()){a._Store.sessionId=a._Helpers.generateUniqueId().toUpperCase();var c=a.Identity.getCurrentUser(),e=c?c.getMPID():null;if(e&&(a._Store.currentSessionMPIDs=[e]),!a._Store.sessionStartDate){var f=new Date;a._Store.sessionStartDate=f,a._Store.dateLastEventSent=f;}d.setSessionTimer();var g=(null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())&&!hasExplicitIdentifier(a._Store);a._Store.identifyCalled||g||(a.Identity.identify(a._Store.SDKConfig.identifyRequest,a._Store.SDKConfig.identityCallback),a._Store.identifyCalled=!0,a._Store.SDKConfig.identityCallback=null),a._Events.logEvent({messageType:Types.MessageType.SessionStart});}else a.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);},this.endSession=function(e){var f,g,h,i;if(a.Logger.verbose(Messages$6.InformationMessages.StartingEndSession),e)return void c();if(!a._Helpers.canLog())return a.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession),void(null===(f=a._timeOnSiteTimer)||void 0===f?void 0:f.resetTimer());var j=a._Persistence.getPersistence();if(!j||j.gs&&!j.gs.sid)return a.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd),void(null===(g=a._timeOnSiteTimer)||void 0===g?void 0:g.resetTimer());// sessionId is not equal to cookies.sid if cookies.sid is changed in another tab
if(j.gs.sid&&a._Store.sessionId!==j.gs.sid&&(a._Store.sessionId=j.gs.sid),null===(h=null===j||void 0===j?void 0:j.gs)||void 0===h?void 0:h.les){var k=a._Store.SDKConfig.sessionTimeout;b(j.gs.les,k)?c():(d.setSessionTimer(),null===(i=a._timeOnSiteTimer)||void 0===i?void 0:i.resetTimer());}},this.setSessionTimer=function(){var b=6e4*a._Store.SDKConfig.sessionTimeout;a._Store.globalTimer=window.setTimeout(function(){d.endSession();},b);},this.resetSessionTimer=function(){a._Store.webviewBridgeEnabled||(!a._Store.sessionId&&d.startNewSession(),d.clearSessionTimeout(),d.setSessionTimer()),d.startNewSessionIfNeeded();},this.clearSessionTimeout=function(){clearTimeout(a._Store.globalTimer);},this.startNewSessionIfNeeded=function(){if(!a._Store.webviewBridgeEnabled){var b=a._Persistence.getPersistence();!a._Store.sessionId&&b&&(b.sid?a._Store.sessionId=b.sid:d.startNewSession());}};}
var Messages$5=Constants.Messages;function Ecommerce(a){var b=this;// https://go.mparticle.com/work/SQDSDKS-4801
// https://go.mparticle.com/work/SQDSDKS-4801
// https://go.mparticle.com/work/SQDSDKS-4801
// https://go.mparticle.com/work/SQDSDKS-4801
// https://go.mparticle.com/work/SQDSDKS-4801
// sanitizes any non number, non string value to 0
this.convertTransactionAttributesToProductAction=function(a,b){a.hasOwnProperty("Id")&&(b.TransactionId=a.Id),a.hasOwnProperty("Affiliation")&&(b.Affiliation=a.Affiliation),a.hasOwnProperty("CouponCode")&&(b.CouponCode=a.CouponCode),a.hasOwnProperty("Revenue")&&(b.TotalAmount=this.sanitizeAmount(a.Revenue,"Revenue")),a.hasOwnProperty("Shipping")&&(b.ShippingAmount=this.sanitizeAmount(a.Shipping,"Shipping")),a.hasOwnProperty("Tax")&&(b.TaxAmount=this.sanitizeAmount(a.Tax,"Tax")),a.hasOwnProperty("Step")&&(b.CheckoutStep=a.Step),a.hasOwnProperty("Option")&&(b.CheckoutOptions=a.Option);},this.getProductActionEventName=function(a){switch(a){case Types.ProductActionType.AddToCart:return "AddToCart";case Types.ProductActionType.AddToWishlist:return "AddToWishlist";case Types.ProductActionType.Checkout:return "Checkout";case Types.ProductActionType.CheckoutOption:return "CheckoutOption";case Types.ProductActionType.Click:return "Click";case Types.ProductActionType.Purchase:return "Purchase";case Types.ProductActionType.Refund:return "Refund";case Types.ProductActionType.RemoveFromCart:return "RemoveFromCart";case Types.ProductActionType.RemoveFromWishlist:return "RemoveFromWishlist";case Types.ProductActionType.ViewDetail:return "ViewDetail";case Types.ProductActionType.Unknown:default:return "Unknown"}},this.getPromotionActionEventName=function(a){return a===Types.PromotionActionType.PromotionClick?"PromotionClick":a===Types.PromotionActionType.PromotionView?"PromotionView":"Unknown"},this.convertProductActionToEventType=function(b){return b===Types.ProductActionType.AddToCart?Types.CommerceEventType.ProductAddToCart:b===Types.ProductActionType.AddToWishlist?Types.CommerceEventType.ProductAddToWishlist:b===Types.ProductActionType.Checkout?Types.CommerceEventType.ProductCheckout:b===Types.ProductActionType.CheckoutOption?Types.CommerceEventType.ProductCheckoutOption:b===Types.ProductActionType.Click?Types.CommerceEventType.ProductClick:b===Types.ProductActionType.Purchase?Types.CommerceEventType.ProductPurchase:b===Types.ProductActionType.Refund?Types.CommerceEventType.ProductRefund:b===Types.ProductActionType.RemoveFromCart?Types.CommerceEventType.ProductRemoveFromCart:b===Types.ProductActionType.RemoveFromWishlist?Types.CommerceEventType.ProductRemoveFromWishlist:b===Types.ProductActionType.Unknown?Types.EventType.Unknown:b===Types.ProductActionType.ViewDetail?Types.CommerceEventType.ProductViewDetail:(a.Logger.error("Could not convert product action type "+b+" to event type"),null)},this.convertPromotionActionToEventType=function(b){return b===Types.PromotionActionType.PromotionClick?Types.CommerceEventType.PromotionClick:b===Types.PromotionActionType.PromotionView?Types.CommerceEventType.PromotionView:(a.Logger.error("Could not convert promotion action type "+b+" to event type"),null)},this.generateExpandedEcommerceName=function(a,b){return "eCommerce - "+a+" - "+(b?"Total":"Item")},this.extractProductAttributes=function(a,b){b.CouponCode&&(a["Coupon Code"]=b.CouponCode),b.Brand&&(a.Brand=b.Brand),b.Category&&(a.Category=b.Category),b.Name&&(a.Name=b.Name),b.Sku&&(a.Id=b.Sku),b.Price&&(a["Item Price"]=b.Price),b.Quantity&&(a.Quantity=b.Quantity),b.Position&&(a.Position=b.Position),b.Variant&&(a.Variant=b.Variant),a["Total Product Amount"]=b.TotalAmount||0;},this.extractTransactionId=function(a,b){b.TransactionId&&(a["Transaction Id"]=b.TransactionId);},this.extractActionAttributes=function(a,c){b.extractTransactionId(a,c),c.Affiliation&&(a.Affiliation=c.Affiliation),c.CouponCode&&(a["Coupon Code"]=c.CouponCode),c.TotalAmount&&(a["Total Amount"]=c.TotalAmount),c.ShippingAmount&&(a["Shipping Amount"]=c.ShippingAmount),c.TaxAmount&&(a["Tax Amount"]=c.TaxAmount),c.CheckoutOptions&&(a["Checkout Options"]=c.CheckoutOptions),c.CheckoutStep&&(a["Checkout Step"]=c.CheckoutStep);},this.extractPromotionAttributes=function(a,b){b.Id&&(a.Id=b.Id),b.Creative&&(a.Creative=b.Creative),b.Name&&(a.Name=b.Name),b.Position&&(a.Position=b.Position);},this.buildProductList=function(a,b){return b?Array.isArray(b)?b:[b]:a.ShoppingCart.ProductList},this.createProduct=function(b,c,d,e,f,g,h,i,j,k){return (k=a._Helpers.sanitizeAttributes(k,b),"string"!=typeof b)?(a.Logger.error("Name is required when creating a product"),null):a._Helpers.Validators.isStringOrNumber(c)?a._Helpers.Validators.isStringOrNumber(d)?(d=a._Helpers.parseNumber(d),i&&!a._Helpers.Validators.isNumber(i)&&(a.Logger.error("Position must be a number, it will be set to null."),i=null),e=a._Helpers.Validators.isStringOrNumber(e)?a._Helpers.parseNumber(e):1,{Name:b,Sku:c,Price:d,Quantity:e,Brand:h,Variant:f,Category:g,Position:i,CouponCode:j,TotalAmount:e*d,Attributes:k}):(a.Logger.error("Price is required when creating a product, and must be a string or a number"),null):(a.Logger.error("SKU is required when creating a product, and must be a string or a number"),null)},this.createPromotion=function(b,c,d,e){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Creative:c,Name:d,Position:e}:(a.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired),null)},this.createImpression=function(b,c){return "string"==typeof b?c?{Name:b,Product:c}:(a.Logger.error("Product is required when creating an impression."),null):(a.Logger.error("Name is required when creating an impression."),null)},this.createTransactionAttributes=function(b,c,d,e,f,g){return a._Helpers.Validators.isStringOrNumber(b)?{Id:b,Affiliation:c,CouponCode:d,Revenue:e,Shipping:f,Tax:g}:(a.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired),null)},this.expandProductImpression=function(c){var d=[];return c.ProductImpressions?(c.ProductImpressions.forEach(function(e){e.ProductList&&e.ProductList.forEach(function(f){var g=extend(!1,{},c.EventAttributes);if(f.Attributes)for(var h in f.Attributes)g[h]=f.Attributes[h];b.extractProductAttributes(g,f),e.ProductImpressionList&&(g["Product Impression List"]=e.ProductImpressionList);var i=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName("Impression"),data:g,eventType:Types.EventType.Transaction});d.push(i);});}),d):d},this.expandCommerceEvent=function(a){return a?b.expandProductAction(a).concat(b.expandPromotionAction(a)).concat(b.expandProductImpression(a)):null},this.expandPromotionAction=function(c){var d=[];if(!c.PromotionAction)return d;var e=c.PromotionAction.PromotionList;return e.forEach(function(e){var f=extend(!1,{},c.EventAttributes);b.extractPromotionAttributes(f,e);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(c.PromotionAction.PromotionActionType)),data:f,eventType:Types.EventType.Transaction});d.push(g);}),d},this.expandProductAction=function(c){var d=[];if(!c.ProductAction)return d;var e=!1;if(c.ProductAction.ProductActionType===Types.ProductActionType.Purchase||c.ProductAction.ProductActionType===Types.ProductActionType.Refund){var f=extend(!1,{},c.EventAttributes);f["Product Count"]=c.ProductAction.ProductList?c.ProductAction.ProductList.length:0,b.extractActionAttributes(f,c.ProductAction),c.CurrencyCode&&(f["Currency Code"]=c.CurrencyCode);var g=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType),!0),data:f,eventType:Types.EventType.Transaction});d.push(g);}else e=!0;var h=c.ProductAction.ProductList;return h?(h.forEach(function(f){var g=extend(!1,c.EventAttributes,f.Attributes);e?b.extractActionAttributes(g,c.ProductAction):b.extractTransactionId(g,c.ProductAction),b.extractProductAttributes(g,f);var h=a._ServerModel.createEventObject({messageType:Types.MessageType.PageEvent,name:b.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(c.ProductAction.ProductActionType)),data:g,eventType:Types.EventType.Transaction});d.push(h);}),d):d},this.createCommerceEventObject=function(b,c){var d,e=a._Helpers.extend;// https://go.mparticle.com/work/SQDSDKS-4801
return (a.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent),a._Helpers.canLog())?(d=a._ServerModel.createEventObject({messageType:Types.MessageType.Commerce,sourceMessageId:null===c||void 0===c?void 0:c.sourceMessageId}),d.EventName="eCommerce - ",d.CurrencyCode=a._Store.currencyCode,d.ShoppingCart=[],d.CustomFlags=e(d.CustomFlags,b),d):(a.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent),null)},this.sanitizeAmount=function(b,c){if(!a._Helpers.Validators.isStringOrNumber(b)){var d=[c,"must be of type number. A",_typeof$1(b),"was passed. Converting to 0"].join(" ");return a.Logger.warning(d),0}// if amount is a string, it will be parsed into a number if possible, or set to 0
return a._Helpers.parseNumber(b)};}
var ForegroundTimeTracker=/** @class */function(){function a(a,b){void 0===b&&(b=!1),this.noFunctional=b,this.isTrackerActive=!1,this.localStorageName="",this.startTime=0,this.totalTime=0,this.localStorageName="mprtcl-tos-".concat(a),this.timerVault=new LocalStorageVault(this.localStorageName),this.noFunctional||this.loadTimeFromStorage(),this.addHandlers(),!1===document.hidden&&this.startTracking();}return a.prototype.addHandlers=function(){var a=this;// when user switches tabs or minimizes the window
document.addEventListener("visibilitychange",function(){return a.handleVisibilityChange()}),window.addEventListener("blur",function(){return a.handleWindowBlur()}),window.addEventListener("focus",function(){return a.handleWindowFocus()}),window.addEventListener("storage",function(b){return a.syncAcrossTabs(b)}),window.addEventListener("beforeunload",function(){return a.updateTimeInPersistence()});},a.prototype.handleVisibilityChange=function(){document.hidden?this.stopTracking():this.startTracking();},a.prototype.handleWindowBlur=function(){this.isTrackerActive&&this.stopTracking();},a.prototype.handleWindowFocus=function(){this.isTrackerActive||this.startTracking();},a.prototype.syncAcrossTabs=function(a){if(a.key===this.localStorageName&&null!==a.newValue){var b=parseFloat(a.newValue)||0;this.totalTime=b;}},a.prototype.updateTimeInPersistence=function(){this.isTrackerActive&&!this.noFunctional&&this.timerVault.store(Math.round(this.totalTime));},a.prototype.loadTimeFromStorage=function(){var a=this.timerVault.retrieve();isNumber(a)&&null!==a&&(this.totalTime=a);},a.prototype.startTracking=function(){document.hidden||(this.startTime=Math.floor(performance.now()),this.isTrackerActive=!0);},a.prototype.stopTracking=function(){this.isTrackerActive&&(this.setTotalTime(),this.updateTimeInPersistence(),this.isTrackerActive=!1);},a.prototype.setTotalTime=function(){if(this.isTrackerActive){var a=Math.floor(performance.now());this.totalTime+=a-this.startTime,this.startTime=a;}},a.prototype.getTimeInForeground=function(){return this.setTotalTime(),this.updateTimeInPersistence(),this.totalTime},a.prototype.resetTimer=function(){this.totalTime=0,this.updateTimeInPersistence();},a}();
function createSDKConfig(a){// TODO: Refactor to create a default config object
var b={};for(var c in Constants.DefaultConfig)Constants.DefaultConfig.hasOwnProperty(c)&&(b[c]=Constants.DefaultConfig[c]);if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);for(var c in Constants.DefaultBaseUrls)b[c]=Constants.DefaultBaseUrls[c];// Always initialize flags to at least an empty object to prevent undefined access
return b.flags=b.flags||{},b}// TODO: Merge this with SDKStoreApi in sdkRuntimeModels
function Store(a,b,c){var d=this,e=b._Helpers.createMainStorageName,f=b._NativeSdkHelpers.isWebviewEnabled,g={isEnabled:!0,sessionAttributes:{},localSessionAttributes:{},currentSessionMPIDs:[],consentState:null,sessionId:null,isFirstRun:null,clientId:null,deviceId:null,devToken:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,identityCallFailed:!1,identifyRequestCount:0,SDKConfig:{},nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,storageName:null,activeForwarders:[],kits:{},sideloadedKits:[],configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},roktAccountId:null,integrationName:null,// Placeholder for in-memory persistence model
persistenceData:{gs:{}}};for(var h in g)this[h]=g[h];if(this.devToken=c||null,this.integrationDelayTimeoutStart=Date.now(),this.SDKConfig=createSDKConfig(a),a){a.hasOwnProperty("flags")||(this.SDKConfig.flags={}),this.SDKConfig.flags=processFlags(a),a.deviceId&&(this.deviceId=a.deviceId),this.SDKConfig.isDevelopmentMode=!!a.hasOwnProperty("isDevelopmentMode")&&returnConvertedBoolean(a.isDevelopmentMode);var i=processBaseUrls(a,this.SDKConfig.flags,c);for(var j in i)this.SDKConfig[j]=i[j];if(this.SDKConfig.useNativeSdk=!!a.useNativeSdk,this.SDKConfig.kits=a.kits||{},this.SDKConfig.sideloadedKits=a.sideloadedKits||[],this.SDKConfig.isIOS=a.hasOwnProperty("isIOS")?a.isIOS:!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.SDKConfig.useCookieStorage=!!a.hasOwnProperty("useCookieStorage")&&a.useCookieStorage,this.SDKConfig.maxProducts=a.hasOwnProperty("maxProducts")?a.maxProducts:Constants.DefaultConfig.maxProducts,this.SDKConfig.maxCookieSize=a.hasOwnProperty("maxCookieSize")?a.maxCookieSize:Constants.DefaultConfig.maxCookieSize,a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("package")&&(this.SDKConfig["package"]=a["package"]),this.SDKConfig.integrationDelayTimeout=a.hasOwnProperty("integrationDelayTimeout")?a.integrationDelayTimeout:Constants.DefaultConfig.integrationDelayTimeout,a.hasOwnProperty("identifyRequest")&&(this.SDKConfig.identifyRequest=a.identifyRequest),a.hasOwnProperty("identityCallback")){var k=a.identityCallback;b._Helpers.Validators.isFunction(k)?this.SDKConfig.identityCallback=a.identityCallback:b.Logger.warning("The optional callback must be a function. You tried entering a(n) "+_typeof$1(k)+" . Callback not set. Please set your callback again.");}if(a.hasOwnProperty("appVersion")&&(this.SDKConfig.appVersion=a.appVersion),a.hasOwnProperty("appName")&&(this.SDKConfig.appName=a.appName),a.hasOwnProperty("sessionTimeout")&&(this.SDKConfig.sessionTimeout=a.sessionTimeout),a.hasOwnProperty("dataPlan")){this.SDKConfig.dataPlan={PlanVersion:null,PlanId:null};var l=a.dataPlan;l.planId&&(isDataPlanSlug(l.planId)?this.SDKConfig.dataPlan.PlanId=l.planId:b.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)")),l.planVersion&&(isNumber(l.planVersion)?this.SDKConfig.dataPlan.PlanVersion=l.planVersion:b.Logger.error("Your data plan version must be a number"));}else this.SDKConfig.dataPlan={};if(this.SDKConfig.forceHttps=!a.hasOwnProperty("forceHttps")||a.forceHttps,this.SDKConfig.customFlags=a.customFlags||{},this.SDKConfig.minWebviewBridgeVersion=a.hasOwnProperty("minWebviewBridgeVersion")?a.minWebviewBridgeVersion:1,this.SDKConfig.aliasMaxWindow=a.hasOwnProperty("aliasMaxWindow")?a.aliasMaxWindow:Constants.DefaultConfig.aliasMaxWindow,a.hasOwnProperty("dataPlanOptions")){var m=a.dataPlanOptions;m.hasOwnProperty("dataPlanVersion")&&m.hasOwnProperty("blockUserAttributes")&&m.hasOwnProperty("blockEventAttributes")&&m.hasOwnProperty("blockEvents")&&m.hasOwnProperty("blockUserIdentities")||b.Logger.error("Ensure your config.dataPlanOptions object has the following keys: a \"dataPlanVersion\" object, and \"blockUserAttributes\", \"blockEventAttributes\", \"blockEvents\", \"blockUserIdentities\" booleans");}a.hasOwnProperty("onCreateBatch")&&("function"==typeof a.onCreateBatch?this.SDKConfig.onCreateBatch=a.onCreateBatch:(b.Logger.error("config.onCreateBatch must be a function"),this.SDKConfig.onCreateBatch=void 0));}this._getFromPersistence=function(a,b){return a?(d.syncPersistenceData(),d.persistenceData&&d.persistenceData[a]&&d.persistenceData[a][b]?d.persistenceData[a][b]:null):null},this._setPersistence=function(a,c,e){var f;a&&(d.syncPersistenceData(),d.persistenceData&&(d.persistenceData[a]?d.persistenceData[a][c]=e:d.persistenceData[a]=(f={},f[c]=e,f),isObject(d.persistenceData[a][c])&&isEmpty(d.persistenceData[a][c])&&delete d.persistenceData[a][c],b._Persistence.savePersistence(d.persistenceData)));},this.hasInvalidIdentifyRequest=function(){var a=d.SDKConfig.identifyRequest;return isObject(a)&&isObject(a.userIdentities)&&isEmpty(a.userIdentities)||!a},this.getConsentState=function(a){var c=b._Consent.ConsentSerialization.fromMinifiedJsonObject,e=d._getFromPersistence(a,"con");return isEmpty(e)?null:c(e)},this.setConsentState=function(a,c){var e=b._Consent.ConsentSerialization.toMinifiedJsonObject;// If ConsentState is null, we assume the intent is to clear out the consent state
(c||null===c)&&d._setPersistence(a,"con",e(c));},this.getDeviceId=function(){return d.deviceId},this.setDeviceId=function(a){d.deviceId=a,d.persistenceData.gs.das=a,b._Persistence.update();},this.getFirstSeenTime=function(a){return d._getFromPersistence(a,"fst")},this.setFirstSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"fst",c);}},this.getLastSeenTime=function(a){if(!a)return null;// https://go.mparticle.com/work/SQDSDKS-6315
var c=b.Identity.getCurrentUser();return a===(null===c||void 0===c?void 0:c.getMPID())?new Date().getTime():d._getFromPersistence(a,"lst")},this.setLastSeenTime=function(a,b){if(a){var c=b||new Date().getTime();d._setPersistence(a,"lst",c);}},this.getLocalSessionAttributes=function(){return d.localSessionAttributes||{}},this.setLocalSessionAttribute=function(a,c){var e;d.localSessionAttributes[a]=c,d.persistenceData.gs.lsa=__assign(__assign({},d.persistenceData.gs.lsa||{}),(e={},e[a]=c,e)),b._Persistence.savePersistence(d.persistenceData);},this.syncPersistenceData=function(){var a=b._Persistence.getPersistence();d.persistenceData=extend({},d.persistenceData,a);},this.getUserAttributes=function(a){return d._getFromPersistence(a,"ua")||{}},this.setUserAttributes=function(a,b){return d._setPersistence(a,"ua",b)},this.getUserIdentities=function(a){return d._getFromPersistence(a,"ui")||{}},this.setUserIdentities=function(a,b){d._setPersistence(a,"ui",b);},this.getRoktAccountId=function(){return d.roktAccountId},this.setRoktAccountId=function(a){d.roktAccountId=a;},this.getIntegrationName=function(){return d.integrationName},this.setIntegrationName=function(a){d.integrationName=a;},this.addMpidToSessionHistory=function(a,b){var c=d.currentSessionMPIDs.indexOf(a);return a&&b!==a&&0>c?void d.currentSessionMPIDs.push(a):void(0<=c&&(d.currentSessionMPIDs=moveElementToEnd(d.currentSessionMPIDs,c)))},this.nullifySession=function(){d.sessionId=null,d.dateLastEventSent=null,d.sessionStartDate=null,d.sessionAttributes={},d.localSessionAttributes={},b._Persistence.update();},this.processConfig=function(a){var g,h=a.workspaceToken,i=a.requiredWebviewBridgeName;a.flags&&(d.SDKConfig.flags=processFlags(a));var j=processBaseUrls(a,d.SDKConfig.flags,c);for(var k in j)d.SDKConfig[k]=j[k];if(h){d.SDKConfig.workspaceToken=h;var l=!0===(null===(g=null===a||void 0===a?void 0:a.launcherOptions)||void 0===g?void 0:g.noFunctional);b._timeOnSiteTimer=new ForegroundTimeTracker(h,l);}else b.Logger.warning("You should have a workspaceToken on your config object for security purposes.");// add a new function to apply items to the store that require config to be returned
d.storageName=e(h),d.SDKConfig.requiredWebviewBridgeName=i||h,d.webviewBridgeEnabled=f(d.SDKConfig.requiredWebviewBridgeName,d.SDKConfig.minWebviewBridgeVersion),d.configurationLoaded=!0;};}// https://go.mparticle.com/work/SQDSDKS-6317
function processFlags(a){var b={},c=Constants.FeatureFlags,d=c.ReportBatching,e=c.EventBatchingIntervalMillis,f=c.OfflineStorage,g=c.DirectUrlRouting,h=c.CacheIdentity,i=c.AudienceAPI,j=c.CaptureIntegrationSpecificIds,k=c.CaptureIntegrationSpecificIdsV2,l=c.AstBackgroundEvents;return a.flags?(b[d]=a.flags[d]||!1,b[e]=parseNumber(a.flags[e])||Constants.DefaultConfig.uploadInterval,b[f]=a.flags[f]||"0",b[g]="True"===a.flags[g],b[h]="True"===a.flags[h],b[i]="True"===a.flags[i],b[j]="True"===a.flags[j],b[k]=a.flags[k]||"none",b[l]="True"===a.flags[l],b):{};// https://go.mparticle.com/work/SQDSDKS-6317
// Passed in config flags take priority over defaults
}function processBaseUrls(a,b,c){// an API key is not present in a webview only mode. In this case, no baseUrls are needed
if(!c)return {};// Set default baseUrls
// A CNAME (config.domain, e.g. set by the snippet v2.6+) takes precedence
// over direct URL routing so that customer-configured first-party domains
// and the snippet's fallback domain are always honored.
return isEmpty(a.domain)?b.directURLRouting?processDirectBaseUrls(a,c):processCustomBaseUrls(a):processCustomBaseUrls(a);// When direct URL routing is false, update baseUrls based custom urls
// passed to the config
}function processCustomBaseUrls(a){var b=Constants.DefaultBaseUrls,c=Constants.CNAMEUrlPaths,d={};// newBaseUrls are default if the customer is not using a CNAME
// If a customer passes either config.domain or config.v3SecureServiceUrl,
// config.identityUrl, etc, the customer is using a CNAME.
// config.domain will take priority if a customer passes both.
// If config.domain exists, the customer is using a CNAME. We append the url paths to the provided domain.
// This flag is set on the Rokt/MP snippet (starting at version 2.6), meaning config.domain will alwys be empty
// if a customer is using a snippet prior to 2.6.
if(!isEmpty(a.domain)){for(var e in c)d[e]="".concat(a.domain).concat(c[e]);return d}for(var f in b)d[f]=a[f]||b[f];return d}function processDirectBaseUrls(a,b){var c=Constants.DefaultBaseUrls,d={},e=b.split("-"),f=1>=e.length?"us1":e[0];// When Direct URL Routing is true, we create a new set of baseUrls that
// include the silo in the urls. mParticle API keys are prefixed with the
// silo and a hyphen (ex. "us1-", "us2-", "eu1-"). us1 was the first silo,
// and before other silos existed, there were no prefixes and all apiKeys
// were us1. As such, if we split on a '-' and the resulting array length
// is 1, then it is an older APIkey that should route to us1.
// When splitKey.length is greater than 1, then splitKey[0] will be
// us1, us2, eu1, au1, or st1, etc as new silos are added
for(var g in c){// Any custom endpoints passed to mpConfig will take priority over direct
// mapping to the silo. The most common use case is a customer provided CNAME.
if("configUrl"==g){d[g]=a[g]||c[g];continue}if(a.hasOwnProperty(g))d[g]=a[g];else {var h=c[g].split(".");d[g]=__spreadArray([h[0],f],h.slice(1),!0).join(".");}}return d}
var Logger=/** @class */function(){function a(a){var b,c;this.logLevel=null!==(b=a.logLevel)&&void 0!==b?b:LogLevelType.Warning,this.logger=null!==(c=a.logger)&&void 0!==c?c:new ConsoleLogger;}return a.prototype.verbose=function(a){this.logLevel===LogLevelType.None||this.logger.verbose&&this.logLevel===LogLevelType.Verbose&&this.logger.verbose(a);},a.prototype.warning=function(a){this.logLevel===LogLevelType.None||this.logger.warning&&(this.logLevel===LogLevelType.Verbose||this.logLevel===LogLevelType.Warning)&&this.logger.warning(a);},a.prototype.error=function(a){this.logLevel===LogLevelType.None||this.logger.error&&this.logger.error(a);},a.prototype.isVerbose=function(){return this.logLevel===LogLevelType.Verbose},a.prototype.setLogLevel=function(a){this.logLevel=a;},a}();var ConsoleLogger=/** @class */function(){function a(){}return a.prototype.verbose=function(a){console&&console.info&&console.info(a);},a.prototype.error=function(a){console&&console.error&&console.error(a);},a.prototype.warning=function(a){console&&console.warn&&console.warn(a);},a}();
var Base64=Polyfill.Base64,Messages$4=Constants.Messages,Base64CookieKeys=Constants.Base64CookieKeys,SDKv2NonMPIDCookieKeys=Constants.SDKv2NonMPIDCookieKeys,StorageNames=Constants.StorageNames;function _Persistence(a){function b(b){var c=a._Store;return b.gs.sid=c.sessionId,b.gs.ie=c.isEnabled,b.gs.sa=c.sessionAttributes,b.gs.lsa=c.localSessionAttributes,b.gs.ss=c.serverSettings,b.gs.dt=c.devToken,b.gs.les=c.dateLastEventSent?c.dateLastEventSent.getTime():null,b.gs.av=c.SDKConfig.appVersion,b.gs.cgid=c.clientId,b.gs.das=c.deviceId,b.gs.c=c.context,b.gs.ssd=c.sessionStartDate?c.sessionStartDate.getTime():0,b.gs.ia=c.integrationAttributes,b}function c(a){localStorage.removeItem(a);}function d(a,b,c){return f.encodePersistence(JSON.stringify(a))+";expires="+b+";path=/"+c}var f=this;// https://go.mparticle.com/work/SQDSDKS-5022
// https://go.mparticle.com/work/SQDSDKS-6045
// https://go.mparticle.com/work/SQDSDKS-5022
// https://go.mparticle.com/work/SQDSDKS-6021
// https://go.mparticle.com/work/SQDSDKS-5022
// https://go.mparticle.com/work/SQDSDKS-6021
/* This function determines if a cookie is greater than the configured maxCookieSize.
- If it is, we remove an MPID and its associated UI/UA/CSD from the cookie.
- Once removed, check size, and repeat.
- Never remove the currentUser's MPID from the cookie.
MPID removal priority:
1. If there are no currentSessionMPIDs, remove a random MPID from the the cookie.
2. If there are currentSessionMPIDs:
a. Remove at random MPIDs on the cookie that are not part of the currentSessionMPIDs
b. Then remove MPIDs based on order in currentSessionMPIDs array, which
stores MPIDs based on earliest login.
*/ // TODO: This should actually be decodePersistenceString or
// we should refactor this to take a string and return an object
// This function loops through the parts of a full hostname, attempting to set a cookie on that domain. It will set a cookie at the highest level possible.
// For example subdomain.domain.co.uk would try the following combinations:
// "co.uk" -> fail
// "domain.co.uk" -> success, return
// "subdomain.domain.co.uk" -> skipped, because already found
// https://go.mparticle.com/work/SQDSDKS-6021
/**
* set the "first seen" time for a user. the time will only be set once for a given
* mpid after which subsequent calls will be ignored
*/ /**
* returns the "last seen" time for a user. If the mpid represents the current user, the
* return value will always be the current time, otherwise it will be to stored "last seen"
* time
*/ // https://go.mparticle.com/work/SQDSDKS-6045
// Forwarder Batching Code
this.useLocalStorage=function(){return !a._Store.SDKConfig.useCookieStorage&&a._Store.isLocalStorageAvailable},this.initializeStorage=function(){try{var b,c,d=f.getLocalStorage(),e=f.getCookie();// https://go.mparticle.com/work/SQDSDKS-6045
// Determine if there is any data in cookies or localStorage to figure out if it is the first time the browser is loading mParticle
// https://go.mparticle.com/work/SQDSDKS-6046
// Stores all non-current user MPID information into the store
for(var g in d||e?a._Store.isFirstRun=!1:(a._Store.isFirstRun=!0,a._Store.mpid=0),a._Store.isLocalStorageAvailable||(a._Store.SDKConfig.useCookieStorage=!0),a._Store.isLocalStorageAvailable?(b=window.localStorage,a._Store.SDKConfig.useCookieStorage?(d?(c=e?extend(!1,d,e):d,b.removeItem(a._Store.storageName)):e&&(c=e),f.storeDataInMemory(c)):e?(c=d?extend(!1,d,e):e,f.storeDataInMemory(c),f.expireCookies(a._Store.storageName)):f.storeDataInMemory(d)):f.storeDataInMemory(e),c)c.hasOwnProperty(g)&&(SDKv2NonMPIDCookieKeys[g]||(a._Store.nonCurrentUserMPIDs[g]=c[g]));f.update();}catch(b){f.useLocalStorage()&&a._Store.isLocalStorageAvailable?localStorage.removeItem(a._Store.storageName):f.expireCookies(a._Store.storageName),a.Logger.error("Error initializing storage: "+b);}},this.update=function(){a._Store.webviewBridgeEnabled||(a._Store.SDKConfig.useCookieStorage&&f.setCookie(),f.setLocalStorage());},this.storeDataInMemory=function(b,c){try{b?(a._Store.mpid=c?c:b.cu||0,b.gs=b.gs||{},a._Store.sessionId=b.gs.sid||a._Store.sessionId,a._Store.isEnabled="undefined"==typeof b.gs.ie?a._Store.isEnabled:b.gs.ie,a._Store.sessionAttributes=b.gs.sa||a._Store.sessionAttributes,a._Store.localSessionAttributes=b.gs.lsa||a._Store.localSessionAttributes,a._Store.serverSettings=b.gs.ss||a._Store.serverSettings,a._Store.devToken=a._Store.devToken||b.gs.dt,a._Store.SDKConfig.appVersion=a._Store.SDKConfig.appVersion||b.gs.av,a._Store.clientId=b.gs.cgid||a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||b.gs.das||a._Helpers.generateUniqueId(),a._Store.integrationAttributes=b.gs.ia||{},a._Store.context=b.gs.c||a._Store.context,a._Store.currentSessionMPIDs=b.gs.csm||a._Store.currentSessionMPIDs,a._Store.isLoggedIn=!0===b.l,b.gs.les&&(a._Store.dateLastEventSent=new Date(b.gs.les)),a._Store.sessionStartDate=b.gs.ssd?new Date(b.gs.ssd):new Date,b=c?b[c]:b[b.cu]):(a.Logger.verbose(Messages$4.InformationMessages.CookieNotFound),a._Store.clientId=a._Store.clientId||a._Helpers.generateUniqueId(),a._Store.deviceId=a._Store.deviceId||a._Helpers.generateUniqueId());}catch(b){a.Logger.error(Messages$4.ErrorMessages.CookieParseError);}},this.determineLocalStorageAvailability=function(a){var b;window.mParticle&&window.mParticle._forceNoLocalStorage&&(a=void 0);try{return a.setItem("mparticle","test"),b="test"===a.getItem("mparticle"),a.removeItem("mparticle"),b&&a}catch(a){return !1}},this.setLocalStorage=function(){var c;if(a._Store.isLocalStorageAvailable&&!(null!==(c=a._CookieConsentManager)&&void 0!==c&&c.getNoFunctional()))// Block mprtcl-v4 localStorage when noFunctional is true
{var d=a._Store.storageName,e=f.getLocalStorage()||{},g=a.Identity.getCurrentUser(),h=g?g.getMPID():null;if(!a._Store.SDKConfig.useCookieStorage){e.gs=e.gs||{},e.l=a._Store.isLoggedIn?1:0,a._Store.sessionId&&(e.gs.csm=a._Store.currentSessionMPIDs),e.gs.ie=a._Store.isEnabled,h&&(e.cu=h),Object.keys(a._Store.nonCurrentUserMPIDs).length&&(e=extend({},e,a._Store.nonCurrentUserMPIDs),a._Store.nonCurrentUserMPIDs={}),e=b(e);try{window.localStorage.setItem(encodeURIComponent(d),f.encodePersistence(JSON.stringify(e)));}catch(b){a.Logger.error("Error with setting localStorage item.");}}}},this.getLocalStorage=function(){if(!a._Store.isLocalStorageAvailable)return null;var b,c=a._Store.storageName,d=f.decodePersistence(window.localStorage.getItem(c)),e={};if(d)for(b in d=JSON.parse(d),d)d.hasOwnProperty(b)&&(e[b]=d[b]);return Object.keys(e).length?e:null},this.expireCookies=function(a){var b,c,d,e=new Date;d=f.getCookieDomain(),c=""===d?"":";domain="+d,e.setTime(e.getTime()-86400000),b="; expires="+e.toUTCString(),document.cookie=a+"="+b+"; path=/"+c;},this.getCookie=function(){var b,c,d,e,g,h,j=a._Store.storageName,k=j?void 0:{};a.Logger.verbose(Messages$4.InformationMessages.CookieSearch);try{b=window.document.cookie.split("; ");}catch(b){return a.Logger.verbose("Unable to parse undefined cookie"),null}for(c=0,d=b.length;cf&&!SDKv2NonMPIDCookieKeys[j]&&j!==b.cu&&delete b[j]);else {// Comment 2 above - First create an object of all MPIDs on the cookie
var k={};for(var l in b)b.hasOwnProperty(l)&&(SDKv2NonMPIDCookieKeys[l]||l===b.cu||(k[l]=1));// Comment 2a above
if(Object.keys(k).length)for(var m in k)g=d(b,c,e),g.length>f&&k.hasOwnProperty(m)&&-1===h.indexOf(m)&&delete b[m];// Comment 2b above
for(var n,o=0;of);o++)n=h[o],b[n]?(a.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of "+f+". Removing from cookie the earliest logged in MPID containing: "+JSON.stringify(b[n],0,2)),delete b[n]):a.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of "+f+". We recommend using a maxCookieSize of 1500.");}return g},this.findPrevCookiesBasedOnUI=function(b){var c,d=a._Persistence.getPersistence();if(b)for(var e in b.userIdentities)if(d&&Object.keys(d).length)for(var g in d)// any value in persistence that has an MPID key will be an MPID to search through
// other keys on the cookie are currentSessionMPIDs and currentMPID which should not be searched
if(d[g].mpid){var h=d[g].ui;for(var i in h)if(e===i&&b.userIdentities[e]===h[i]){c=g;break}}c&&f.storeDataInMemory(d,c);},this.encodePersistence=function(b){for(var c in b=JSON.parse(b),b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]?Array.isArray(b.gs[c])&&b.gs[c].length||a._Helpers.isObject(b.gs[c])&&Object.keys(b.gs[c]).length?b.gs[c]=Base64.encode(JSON.stringify(b.gs[c])):delete b.gs[c]:delete b.gs[c]:"ie"===c?b.gs[c]=b.gs[c]?1:0:!b.gs[c]&&delete b.gs[c]);for(var d in b)if(b.hasOwnProperty(d)&&!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&(a._Helpers.isObject(b[d][c])&&Object.keys(b[d][c]).length?b[d][c]=Base64.encode(JSON.stringify(b[d][c])):delete b[d][c]);return createCookieString(JSON.stringify(b))},this.decodePersistence=function(b){try{if(b){if(b=JSON.parse(revertCookieString(b)),a._Helpers.isObject(b)&&Object.keys(b).length){for(var c in b.gs)b.gs.hasOwnProperty(c)&&(Base64CookieKeys[c]?b.gs[c]=JSON.parse(Base64.decode(b.gs[c])):"ie"===c&&(b.gs[c]=!!b.gs[c]));for(var d in b)if(b.hasOwnProperty(d))if(!SDKv2NonMPIDCookieKeys[d])for(c in b[d])b[d].hasOwnProperty(c)&&Base64CookieKeys[c]&&b[d][c].length&&(b[d][c]=JSON.parse(Base64.decode(b[d][c])));else "l"===d&&(b[d]=!!b[d]);}return JSON.stringify(b)}}catch(b){a.Logger.error("Problem with decoding cookie",b);}},this.getCookieDomain=function(){if(a._Store.SDKConfig.cookieDomain)return a._Store.SDKConfig.cookieDomain;var b=f.getDomain(document,location.hostname);return ""===b?"":"."+b},this.getDomain=function(a,b){var c,d,e=b.split(".");for(c=e.length-1;0<=c;c--)if(d=e.slice(c).join("."),a.cookie="mptest=cookie;domain=."+d+";",-1= 0; --o) {
var i = this.tryEntries[o],
a = i.completion;
if ("root" === i.tryLoc) return handle("end");
if (i.tryLoc <= this.prev) {
var c = n.call(i, "catchLoc"),
u = n.call(i, "finallyLoc");
if (c && u) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
} else if (c) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
} else {
if (!u) throw new Error("try statement without catch or finally");
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
}
}
}
},
abrupt: function abrupt(t, e) {
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
var o = this.tryEntries[r];
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
var i = o;
break;
}
}
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
var a = i ? i.completion : {};
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
},
complete: function complete(t, e) {
if ("throw" === t.type) throw t.arg;
return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
},
finish: function finish(t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
}
},
"catch": function _catch(t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.tryLoc === t) {
var n = r.completion;
if ("throw" === n.type) {
var o = n.arg;
resetTryEntry(r);
}
return o;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function delegateYield(e, r, n) {
return this.delegate = {
iterator: values(e),
resultName: r,
nextLoc: n
}, "next" === this.method && (this.arg = t), y;
}
}, e;
}
module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
} (regeneratorRuntime$1));
var regeneratorRuntimeExports = regeneratorRuntime$1.exports;
// TODO(Babel 8): Remove this file.
var runtime = regeneratorRuntimeExports();
var regenerator = runtime;
// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
if (typeof globalThis === "object") {
globalThis.regeneratorRuntime = runtime;
} else {
Function("r", "regeneratorRuntime = r")(runtime);
}
}
var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator);
function filteredMparticleUser(a,b,c,d){var e=this;return {getUserIdentities:function getUserIdentities(){var e={},f=c._Store.getUserIdentities(a);for(var g in f)if(f.hasOwnProperty(g)){var h=Types.IdentityType.getIdentityName(c._Helpers.parseNumber(g));d&&(!d||d.isIdentityBlocked(h))||(//if identity type is not blocked
e[h]=f[g]);}return e=c._Helpers.filterUserIdentitiesForForwarders(e,b.userIdentityFilters),{userIdentities:e}},getMPID:function getMPID(){return a},getUserAttributesLists:function getUserAttributesLists(a){var b,f={};for(var g in b=e.getAllUserAttributes(),b)b.hasOwnProperty(g)&&Array.isArray(b[g])&&(d&&(!d||d.isAttributeKeyBlocked(g))||(f[g]=b[g].slice()));return f=c._Helpers.filterUserAttributes(f,a.userAttributeFilters),f},getAllUserAttributes:function getAllUserAttributes(){var e={},f=c._Store.getUserAttributes(a);if(f)for(var g in f)f.hasOwnProperty(g)&&(d&&(!d||d.isAttributeKeyBlocked(g))||(Array.isArray(f[g])?e[g]=f[g].slice():e[g]=f[g]));return e=c._Helpers.filterUserAttributes(e,b.userAttributeFilters),e}}}
var FORWARDING_RULE_MESSAGE_TYPES=[Types.MessageType.PageEvent,Types.MessageType.PageView,Types.MessageType.Commerce];function inFilteredList(a,b){return !!(a&&a.length)&&inArray(a,b)}function isBlockedByForwardingRule(a,b,c){if(!FORWARDING_RULE_MESSAGE_TYPES.includes(a)||!c.filteringEventAttributeValue||!c.filteringEventAttributeValue.eventAttributeName||!c.filteringEventAttributeValue.eventAttributeValue)return !1;var d=null;if(b)for(var e in b)if(b.hasOwnProperty(e)){var f=KitFilterHelper.hashAttributeConditionalForwarding(e);if(f===c.filteringEventAttributeValue.eventAttributeName){d={name:f,value:KitFilterHelper.hashAttributeConditionalForwarding(b[e])};break}}var g=null!==d&&d.value===c.filteringEventAttributeValue.eventAttributeValue,h=!0===c.filteringEventAttributeValue.includeOnMatch?g:!g;return !h}function isBlockedByEventFilter(a,b,c,d){if(a===Types.MessageType.PageEvent&&(inFilteredList(d.eventNameFilters,b)||inFilteredList(d.eventTypeFilters,c)))return !0;return !!(a===Types.MessageType.Commerce&&inFilteredList(d.eventTypeFilters,c))||!!(a===Types.MessageType.PageView&&inFilteredList(d.screenNameFilters,b))}function filterEventAttributes(a,b,c,d,e){if(!d)return d;var f;if(a===Types.MessageType.PageEvent?f=e.attributeFilters:a===Types.MessageType.PageView&&(f=e.screenAttributeFilters),!f)return d;var g={};for(var h in d)if(d.hasOwnProperty(h)){var i=KitFilterHelper.hashEventAttributeKey(b,c,h);inArray(f,i)||(g[h]=d[h]);}return g}function filterUserIdentities(a,b){return a&&a.length?a.filter(function(a){return !inArray(b,KitFilterHelper.hashUserIdentity(a.Type))}):a||[]}function isBatchEventAllowed(a,b){if(!a||!a.data)return !0;var c=getMessageTypeFromEventType(a.event_type),d=getEventNameFromBatchEvent(a),e=getEventCategoryFromBatchEvent(a);if(isBlockedByForwardingRule(c,a.data.custom_attributes,b))return !1;var f=KitFilterHelper.hashEventName(d,e),g=KitFilterHelper.hashEventType(e);return !isBlockedByEventFilter(c,f,g,b)}function filterBatchEventAttributes(a,b){if(a&&a.data){var c=getMessageTypeFromEventType(a.event_type),d=getEventNameFromBatchEvent(a),e=getEventCategoryFromBatchEvent(a);a.data.custom_attributes=filterEventAttributes(c,e,d,a.data.custom_attributes,b);}}function filterBatchIdentities(a,b){if(!a||!b)return a;var c={};for(var d in a)if(a.hasOwnProperty(d)){var e=getIdentityTypeFromBatchKey(d);-1!==e&&inArray(b,e)||(c[d]=a[d]);}return c}
function _createForOfIteratorHelper(a,b){var c="undefined"!=typeof Symbol&&a[Symbol.iterator]||a["@@iterator"];if(!c){if(Array.isArray(a)||(c=_unsupportedIterableToArray(a))||b&&a&&"number"==typeof a.length){c&&(a=c);var d=0,e=function(){};return {s:e,n:function n(){return d>=a.length?{done:!0}:{done:!1,value:a[d++]}},e:function e(a){throw a},f:e}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var g=!0,h=!1;return {s:function s(){c=c.call(a);},n:function n(){var a=c.next();return g=a.done,a},e:function e(a){h=!0;},f:function f(){try{g||null==c["return"]||c["return"]();}finally{if(h)throw f}}}}function _unsupportedIterableToArray(a,b){if(a){if("string"==typeof a)return _arrayLikeToArray(a,b);var c=Object.prototype.toString.call(a).slice(8,-1);return "Object"===c&&a.constructor&&(c=a.constructor.name),"Map"===c||"Set"===c?Array.from(a):"Arguments"===c||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(c)?_arrayLikeToArray(a,b):void 0}}function _arrayLikeToArray(a,b){(null==b||b>a.length)&&(b=a.length);for(var c=0,d=Array(b);ce.status))?[3/*break*/,4]:(this.logger.verbose("User Audiences successfully received"),[4/*yield*/,e.json()]);case 3:f=i.sent(),g={currentAudienceMemberships:null===f||void 0===f?void 0:f.audience_memberships};try{b(g);}catch(a){throw new Error("Error invoking callback on user audience response.")}return [3/*break*/,5];case 4:if(401===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`");else if(403===e.status)throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`");else// In case there is an HTTP error we did not anticipate.
throw new Error("Uncaught HTTP Error ".concat(e.status,"."));case 5:return [3/*break*/,7];case 6:return h=i.sent(),this.logger.error("Error retrieving audiences. ".concat(h)),[3/*break*/,7];case 7:return [2/*return*/]}})})},a}();
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
if("undefined"!=typeof window&&window.mParticle&&window.mParticle[b[0]])window.mParticle[c].apply(window.mParticle,b);else {var d=c.split(".");try{// Track both the function and its context
for(var e,f=window.mParticle,g=window.mParticle,h=0,i=d;hs?-1:1}),r},/**
* Initiate an alias request to the mParticle server
* @method aliasUsers
* @param {Object} aliasRequest object representing an AliasRequest
* @param {Function} [callback] A callback function that is called when the aliasUsers request completes
*/aliasUsers:function aliasUsers(e,r){var s;if(e.destinationMpid&&e.sourceMpid||(s=Messages$2.ValidationMessages.AliasMissingMpid),e.destinationMpid===e.sourceMpid&&(s=Messages$2.ValidationMessages.AliasNonUniqueMpid),e.startTime&&e.endTime||(s=Messages$2.ValidationMessages.AliasMissingTime),e.startTime>e.endTime&&(s=Messages$2.ValidationMessages.AliasStartBeforeEndTime),s)return t.Logger.warning(s),void t._Helpers.invokeAliasCallback(r,HTTPCodes$2.validationIssue,s);if(!t._Helpers.canLog())t._Helpers.invokeAliasCallback(r,HTTPCodes$2.loggingDisabledOrMissingAPIKey,Messages$2.InformationMessages.AbandonAliasUsers),t.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers);else if(t._Store.webviewBridgeEnabled)t._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias,JSON.stringify(t._Identity.IdentityRequest.convertAliasToNative(e))),t._Helpers.invokeAliasCallback(r,HTTPCodes$2.nativeIdentityRequest,"Alias request sent to native sdk");else {t.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest+": "+e.sourceMpid+" -> "+e.destinationMpid);var i=t._Identity.IdentityRequest.createAliasNetworkRequest(e);t._IdentityAPIClient.sendAliasRequest(i,r);}},/**
* Search the IDSync Workspace endpoint for a known identity.
*
* POSTs to mParticle's `/v1/search` endpoint and invokes `callback`
* with `{ httpCode, body? }`.
*
* The `workspaceApiKey` is a workspace-specific API key supplied by
* the caller (passed in from a kit's settings). It is intentionally
* NOT read from the SDK's own workspace token, so that workspace
* searches can be authorised independently of the host SDK's
* workspace.
*
* @method search
* @param {String} workspaceApiKey Workspace API key (sent as x-mp-key).
* @param {Object} knownIdentities A `UserIdentities` map.
* @param {Function} callback Invoked with the `IIdentitySearchResult`.
*/search:function search(e,r,s){executeSearchRequest(t,e,r,s);},/**
Create a default AliasRequest for 2 MParticleUsers. This will construct the request
using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime.
In the unlikely scenario that the sourceUser does not have a firstSeenTime, which will only
be the case if they have not been the current user since this functionality was added, the
startTime will be populated with the earliest firstSeenTime out of any stored user. Similarly,
if the sourceUser does not have a lastSeenTime, the endTime will be populated with the current time
There is a limit to how old the startTime can be, represented by the config field 'aliasMaxWindow', in days.
If the startTime falls before the limit, it will be adjusted to the oldest allowed startTime.
In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit,
after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers()
validation that the startTime must be less than the endTime
*/createAliasRequest:function createAliasRequest(e,r,s){try{if(!r||!e)return t.Logger.error("'destinationUser' and 'sourceUser' must both be present"),null;var i=e.getFirstSeenTime();i||t.Identity.getUsers().forEach(function(e){e.getFirstSeenTime()&&(!i||e.getFirstSeenTime()
* Usage: const consent = mParticle.Consent.createConsentState()
*
* consent.setGDPRCoonsentState()
*
* @class Consent
*/ /**
* Add a GDPR Consent State to the consent state object
*
* @method addGDPRConsentState
* @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data
* @param gdprConsent [Object] A GDPR consent object created via mParticle.Consent.createGDPRConsent(...)
*/function e(c,e){var f=d(c);if(!f)return a.Logger.error("Purpose must be a string."),this;if(!isObject(e))return a.Logger.error("Invoked with a bad or empty consent object."),this;var g=b.createPrivacyConsent(e.Consented,e.Timestamp,e.ConsentDocument,e.Location,e.HardwareId);return g&&(k[f]=g),this}function f(a){if(!a)k={};else if(isObject(a))for(var b in k={},a)a.hasOwnProperty(b)&&this.addGDPRConsentState(b,a[b]);return this}/**
* Remove a GDPR Consent State to the consent state object
*
* @method removeGDPRConsentState
* @param purpose [String] Data processing purpose that describes the type of processing done on the data subject’s data
*/function g(a){var b=d(a);return b?(delete k[b],this):this}/**
* Gets the GDPR Consent State
*
* @method getGDPRConsentState
* @return {Object} A GDPR Consent State
*/function h(){return Object.assign({},k)}/**
* Sets a CCPA Consent state (has a single purpose of 'data_sale_opt_out')
*
* @method setCCPAConsentState
* @param {Object} ccpaConsent CCPA Consent State
*/function i(c){if(!isObject(c))return a.Logger.error("Invoked with a bad or empty CCPA consent object."),this;var d=b.createPrivacyConsent(c.Consented,c.Timestamp,c.ConsentDocument,c.Location,c.HardwareId);return d&&(l[CCPAPurpose]=d),this}/**
* Gets the CCPA Consent State
*
* @method getCCPAConsentStatensent
* @return {Object} A CCPA Consent State
*/ /**
* Removes CCPA from the consent state object
*
* @method removeCCPAConsentState
*/function j(){return delete l[CCPAPurpose],this}// TODO: Can we remove this? It is deprecated.
var k={},l={};if(c){var m=b.createConsentState();// TODO: Remove casting once `removeCCPAState` is removed;
return m.setGDPRConsentState(c.getGDPRConsentState()),m.setCCPAConsentState(c.getCCPAConsentState()),m}return {setGDPRConsentState:f,addGDPRConsentState:e,setCCPAConsentState:i,getCCPAConsentState:function a(){return l[CCPAPurpose]},getGDPRConsentState:h,removeGDPRConsentState:g,removeCCPAState:function b(){// @ts-ignore
return a.Logger.warning("removeCCPAState is deprecated and will be removed in a future release; use removeCCPAConsentState instead"),j()},removeCCPAConsentState:j}};}
/*
TODO: Including this as a workaround because attempting to import it from
@mparticle/data-planning-models directly creates a build error.
*/var DataPlanMatchType={ScreenView:"screen_view",CustomEvent:"custom_event",Commerce:"commerce",UserAttributes:"user_attributes",UserIdentities:"user_identities",ProductAction:"product_action",PromotionAction:"promotion_action",ProductImpression:"product_impression"},KitBlocker=/** @class */function(){function a(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r=this;// if data plan is not requested, the data plan is {document: null}
if(this.dataPlanMatchLookups={},this.blockEvents=!1,this.blockEventAttributes=!1,this.blockUserAttributes=!1,this.blockUserIdentities=!1,this.kitBlockingEnabled=!1,a&&!a.document)return void(this.kitBlockingEnabled=!1);this.kitBlockingEnabled=!0,this.mpInstance=b,this.blockEvents=null===(e=null===(d=null===(c=null===a||void 0===a?void 0:a.document)||void 0===c?void 0:c.dtpn)||void 0===d?void 0:d.blok)||void 0===e?void 0:e.ev,this.blockEventAttributes=null===(h=null===(g=null===(f=null===a||void 0===a?void 0:a.document)||void 0===f?void 0:f.dtpn)||void 0===g?void 0:g.blok)||void 0===h?void 0:h.ea,this.blockUserAttributes=null===(k=null===(j=null===(i=null===a||void 0===a?void 0:a.document)||void 0===i?void 0:i.dtpn)||void 0===j?void 0:j.blok)||void 0===k?void 0:k.ua,this.blockUserIdentities=null===(n=null===(m=null===(l=null===a||void 0===a?void 0:a.document)||void 0===l?void 0:l.dtpn)||void 0===m?void 0:m.blok)||void 0===n?void 0:n.id;var s=null===(q=null===(p=null===(o=null===a||void 0===a?void 0:a.document)||void 0===o?void 0:o.dtpn)||void 0===p?void 0:p.vers)||void 0===q?void 0:q.version_document,t=null===s||void 0===s?void 0:s.data_points;if(s)try{0<(null===t||void 0===t?void 0:t.length)&&t.forEach(function(a){return r.addToMatchLookups(a)});}catch(a){this.mpInstance.Logger.error("There was an issue with the data plan: "+a);}}return a.prototype.addToMatchLookups=function(a){var b,c,d;if(!a.match||!a.validator)return void this.mpInstance.Logger.warning("Data Plan Point is not valid' + ".concat(a));// match keys for non product custom attribute related data points
var e=this.generateMatchKey(a.match),f=this.getPlannedProperties(a.match.type,a.validator);this.dataPlanMatchLookups[e]=f,((null===(b=null===a||void 0===a?void 0:a.match)||void 0===b?void 0:b.type)===DataPlanMatchType.ProductImpression||(null===(c=null===a||void 0===a?void 0:a.match)||void 0===c?void 0:c.type)===DataPlanMatchType.ProductAction||(null===(d=null===a||void 0===a?void 0:a.match)||void 0===d?void 0:d.type)===DataPlanMatchType.PromotionAction)&&(e=this.generateProductAttributeMatchKey(a.match),f=this.getProductProperties(a.match.type,a.validator),this.dataPlanMatchLookups[e]=f);},a.prototype.generateMatchKey=function(a){var b=a.criteria||"";switch(a.type){case DataPlanMatchType.CustomEvent:var c=b;return [DataPlanMatchType.CustomEvent,c.custom_event_type,c.event_name].join(":");case DataPlanMatchType.ScreenView:return [DataPlanMatchType.ScreenView,"",b.screen_name].join(":");case DataPlanMatchType.ProductAction:return [a.type,b.action].join(":");case DataPlanMatchType.PromotionAction:return [a.type,b.action].join(":");case DataPlanMatchType.ProductImpression:return [a.type,b.action].join(":");case DataPlanMatchType.UserIdentities:case DataPlanMatchType.UserAttributes:return [a.type].join(":");default:return null}},a.prototype.generateProductAttributeMatchKey=function(a){var b=a.criteria||"";switch(a.type){case DataPlanMatchType.ProductAction:return [a.type,b.action,"ProductAttributes"].join(":");case DataPlanMatchType.PromotionAction:return [a.type,b.action,"ProductAttributes"].join(":");case DataPlanMatchType.ProductImpression:return [a.type,"ProductAttributes"].join(":");default:return null}},a.prototype.getPlannedProperties=function(a,b){var c,d,e,f,g,h,i,j,k,l;switch(a){case DataPlanMatchType.CustomEvent:case DataPlanMatchType.ScreenView:case DataPlanMatchType.ProductAction:case DataPlanMatchType.PromotionAction:case DataPlanMatchType.ProductImpression:if(k=null===(f=null===(e=null===(d=null===(c=null===b||void 0===b?void 0:b.definition)||void 0===c?void 0:c.properties)||void 0===d?void 0:d.data)||void 0===e?void 0:e.properties)||void 0===f?void 0:f.custom_attributes,k){if(!0===k.additionalProperties||void 0===k.additionalProperties)return !0;for(var m,n={},o=0,p=Object.keys(k.properties);o=HTTP_SERVER_ERROR)throw new Error("Received HTTP Code of "+u.status);return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,A="Received HTTP Code of "+u.status,o.error("Error sending identity request to servers - "+A),n(d,HTTPCodes$1.noHttpCoverage,A),[2/*return*/]}case 8:return a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!1,w&&o.verbose(w),(null===(j=a._RoktManager)||void 0===j?void 0:j.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),f(v,q,d,e,c,h,!1),[3/*break*/,10];case 9:return E=G.sent(),a._Store.identityCallInFlight=!1,a._Store.identityCallFailed=!0,(null===(k=a._RoktManager)||void 0===k?void 0:k.isInitialized)&&(m=a._Store.identifyRequestCount,a.captureTiming("".concat(m,"-identityRequestEnd"))),A=E.message||E.toString(),F="Error sending identity request to servers - "+A,o.error(F),null===p||void 0===p?void 0:p.report({message:F,code:ErrorCodes.IDENTITY_REQUEST,severity:WSDKErrorSeverity.ERROR}),null===(l=a.processQueueOnIdentityFailure)||void 0===l?void 0:l.call(a),n(d,HTTPCodes$1.noHttpCoverage,A),[3/*break*/,10];case 10:return [2/*return*/]}})})},this.getUploadUrl=function(b,c){var d=a._Helpers.createServiceUrl(a._Store.SDKConfig.identityUrl),e=b===Modify?d+c+"/"+b:d+b;return e},this.getIdentityResponseFromFetch=function(a,b){return {status:a.status,responseText:b,cacheMaxAge:parseInt(a.headers.get(CACHE_HEADER))||0,expireTimestamp:0}},this.getIdentityResponseFromXHR=function(a){return {status:a.status,responseText:a.responseText?JSON.parse(a.responseText):{},cacheMaxAge:parseNumber(a.getResponseHeader(CACHE_HEADER)||""),expireTimestamp:0}};}
// The formatted ClickID value must be of the form version.subdomainIndex.creationTime., where:
// - version is always this prefix: fb
// - subdomainIndex is which domain the cookie is defined on ('com' = 0, 'example.com' = 1, 'www.example.com' = 2)
// - creationTime is the UNIX time since epoch in milliseconds when the _fbc was stored. If you don't save the _fbc cookie, use the timestamp when you first observed or received this fbclid value
// - is the value for the fbclid query parameter in the page URL.
// https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc
var facebookClickIdProcessor=function(a,b,c){if(!a||!b)return "";var d=null===b||void 0===b?void 0:b.split("//");if(!d)return "";var e=d[1].split("/"),f=e[0].split("."),g=1;// The rules for subdomainIndex are for parsing the domain portion
// of the URL for cookies, but in this case we are parsing the URL
// itself, so we can ignore the use of 0 for 'com'
3<=f.length&&(g=2);// If timestamp is not provided, use the current time
var h=c||Date.now();return "fb.".concat(g,".").concat(h,".").concat(a)};// Integration outputs are used to determine how click ids are used within the SDK
// CUSTOM_FLAGS are sent out when an Event is created via ServerModel.createEventObject
// PARTNER_IDENTITIES are sent out in a Batch when a group of events are converted to a Batch
// INTEGRATION_ATTRIBUTES are stored initially on the SDKEvent level but then is added to the Batch when the batch is created
var IntegrationOutputs={CUSTOM_FLAGS:"custom_flags",PARTNER_IDENTITIES:"partner_identities",INTEGRATION_ATTRIBUTES:"integration_attributes"},integrationMappingExternal={// Facebook / Meta
fbclid:{mappedKey:"Facebook.ClickId",processor:facebookClickIdProcessor,output:IntegrationOutputs.CUSTOM_FLAGS},_fbp:{mappedKey:"Facebook.BrowserId",output:IntegrationOutputs.CUSTOM_FLAGS},_fbc:{mappedKey:"Facebook.ClickId",output:IntegrationOutputs.CUSTOM_FLAGS},// Google
gclid:{mappedKey:"GoogleEnhancedConversions.Gclid",output:IntegrationOutputs.CUSTOM_FLAGS},gbraid:{mappedKey:"GoogleEnhancedConversions.Gbraid",output:IntegrationOutputs.CUSTOM_FLAGS},wbraid:{mappedKey:"GoogleEnhancedConversions.Wbraid",output:IntegrationOutputs.CUSTOM_FLAGS},// TIKTOK
ttclid:{mappedKey:"TikTok.Callback",output:IntegrationOutputs.CUSTOM_FLAGS},_ttp:{mappedKey:"tiktok_cookie_id",output:IntegrationOutputs.PARTNER_IDENTITIES},// Snapchat
// https://businesshelp.snapchat.com/s/article/troubleshooting-click-id?language=en_US
ScCid:{mappedKey:"SnapchatConversions.ClickId",output:IntegrationOutputs.CUSTOM_FLAGS},// Snapchat
// https://developers.snap.com/api/marketing-api/Conversions-API/UsingTheAPI#sending-click-id
_scid:{mappedKey:"SnapchatConversions.Cookie1",output:IntegrationOutputs.CUSTOM_FLAGS}},integrationMappingRokt={// Rokt
// https://docs.rokt.com/developers/integration-guides/web/advanced/rokt-id-tag/
// https://go.mparticle.com/work/SQDSDKS-7167
rtid:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277},rclid:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277},RoktTransactionId:{mappedKey:"passbackconversiontrackingid",output:IntegrationOutputs.INTEGRATION_ATTRIBUTES,moduleId:1277}},IntegrationCapture=/** @class */function(){function a(a){this.initialTimestamp=Date.now(),this.captureMode=a,this.filteredPartnerIdentityMappings=this.filterMappings(IntegrationOutputs.PARTNER_IDENTITIES),this.filteredCustomFlagMappings=this.filterMappings(IntegrationOutputs.CUSTOM_FLAGS),this.filteredIntegrationAttributeMappings=this.filterMappings(IntegrationOutputs.INTEGRATION_ATTRIBUTES);}/**
* Captures Integration Ids from cookies and query params and stores them in clickIds object
*/return a.prototype.capture=function(){var a=this.captureQueryParams()||{},b=this.captureCookies()||{},c=this.captureLocalStorage()||{};a.fbclid&&b._fbc&&delete b._fbc;// ROKT Rules
// If both rtid or rclid and RoktTransactionId are present, prioritize rtid/rclid
// If RoktTransactionId is present in both cookies and localStorage,
// prioritize localStorage
var d=a.rtid||a.rclid,e=c.RoktTransactionId,f=b.RoktTransactionId;d?(e&&delete c.RoktTransactionId,f&&delete b.RoktTransactionId):e&&f&&delete b.RoktTransactionId,this.clickIds=__assign(__assign(__assign(__assign({},this.clickIds),a),c),b);},a.prototype.captureCookies=function(){var a=this.getAllowedKeysForMode(),b=getCookies(a);return this.applyProcessors(b,getHref(),this.initialTimestamp)},a.prototype.captureQueryParams=function(){var a=this.getQueryParams();return this.applyProcessors(a,getHref(),this.initialTimestamp)},a.prototype.captureLocalStorage=function(){for(var a=this.getAllowedKeysForMode(),b={},c=0,d=a;c": {
// "mappedKey": "clickIdValue"
// }
// }
// }
for(var e in this.clickIds)if(this.clickIds.hasOwnProperty(e)){var f=this.clickIds[e],g=null===(b=this.filteredIntegrationAttributeMappings[e])||void 0===b?void 0:b.mappedKey;if(!isEmpty(g)){var h=null===(c=this.filteredIntegrationAttributeMappings[e])||void 0===c?void 0:c.moduleId;h&&!d[h]&&(d[h]=(a={},a[g]=f,a));}}return d},a.prototype.getClickIds=function(a,b){var c,d={};if(!a)return d;for(var e in a)if(a.hasOwnProperty(e)){var f=a[e],g=null===(c=b[e])||void 0===c?void 0:c.mappedKey;isEmpty(g)||(d[g]=f);}return d},a.prototype.applyProcessors=function(a,b,c){var d,e={},f=this.getActiveIntegrationMapping();for(var g in a)if(a.hasOwnProperty(g)){var h=a[g],i=null===(d=f[g])||void 0===d?void 0:d.processor;e[g]=i?i(h,b,c):h;}return e},a.prototype.filterMappings=function(a){var b={},c=this.getActiveIntegrationMapping();for(var d in c)c[d].output===a&&(b[d]=c[d]);return b},a.prototype.getAllowedKeysForMode=function(){return Object.keys(this.getActiveIntegrationMapping())},a.prototype.getActiveIntegrationMapping=function(){return this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.RoktOnly?integrationMappingRokt:this.captureMode===Constants.CaptureIntegrationSpecificIdsV2Modes.All?__assign(__assign({},integrationMappingExternal),integrationMappingRokt):{}},a}();
var ON_SHOPPABLE_ADS_READY_METHOD="onShoppableAdsReady",RoktManager=/** @class */function(){function a(){this.kit=null,this.filters={},this.currentUser=null,this.messageQueue=new Map,this.sandbox=null,this.placementAttributesMapping=[],this.onReadyCallback=null,this.initialized=!1,this.isShoppableAdsLoaded=!1;}/**
* Sets a callback to be invoked when RoktManager becomes ready
*/return a.prototype.setOnReadyCallback=function(a){this.onReadyCallback=a;},a.prototype.init=function(a,b,c,d,e,f,g,h,i){var j,k,l=a||{},m=l.userAttributeFilters,n=l.settings,o=n||{},p=o.placementAttributesMapping,q=o.hashedEmailUserIdentityType;this.mappedEmailShaIdentityType=null!==(j=null===q||void 0===q?void 0:q.toLowerCase())&&void 0!==j?j:null,this.identityService=c,this.store=d,this.logger=e,this.errorReporter=h,this.loggingService=i,this.captureTiming=g,null===(k=this.captureTiming)||void 0===k?void 0:k.call(this,PerformanceMarkType.JointSdkRoktKitInit),this.filters={userAttributeFilters:m,filterUserAttributes:KitFilterHelper.filterUserAttributes,filteredUser:b};try{this.placementAttributesMapping=parseSettingsString(p);}catch(a){this.logger.error("Error parsing placement attributes mapping from config: "+a);}// This is the global setting for sandbox mode
// It is set here and passed in to the createLauncher method in the Rokt Kit
// This is not to be confused for the `sandbox` flag in the selectPlacements attributes
// as that is independent of this setting, though they share the same name.
var r=(null===f||void 0===f?void 0:f.sandbox)||!1;// Launcher options are set here for the kit to pick up and pass through
// to the Rokt Launcher.
this.launcherOptions=__assign({sandbox:r},null===f||void 0===f?void 0:f.launcherOptions),(null===f||void 0===f?void 0:f.domain)&&(this.domain=f.domain),this.initialized=!0;},Object.defineProperty(a.prototype,"isInitialized",{get:function get(){return this.initialized},enumerable:!1,configurable:!0}),a.prototype.attachKit=function(a){var b,c,d,e,f;this.kit=a,(null===(b=a.settings)||void 0===b?void 0:b.accountId)&&this.store.setRoktAccountId(a.settings.accountId),a.integrationName&&(null===(c=this.store)||void 0===c?void 0:c.setIntegrationName(a.integrationName)),null===(d=this.loggingService)||void 0===d?void 0:d.log({message:"RoktManager: Kit attached, Rokt is ready",code:ErrorCodes.ROKT_KIT_ATTACHED}),this.processMessageQueue();try{null===(e=this.onReadyCallback)||void 0===e?void 0:e.call(this);}catch(a){null===(f=this.logger)||void 0===f?void 0:f.error("RoktManager: Error in onReadyCallback: "+a);}},a.prototype.selectPlacements=function(a){var b,c,d,e,f,g,h,i,j;return __awaiter(this,void 0,void 0,function(){var k,l,m,n,o,p,q,r,s,t,u,v,w,x,x,y,z,A,B,C,D=this;return __generator(this,function(){// Queue if kit isn't ready OR if identity is in flight
if(null===(b=this.captureTiming)||void 0===b?void 0:b.call(this,PerformanceMarkType.JointSdkSelectPlacements),!this.isReady()||(null===(c=this.store)||void 0===c?void 0:c.identityCallInFlight))return [2/*return*/,this.deferredCall("selectPlacements",a)];try{if(k=a.attributes,l=(null===k||void 0===k?void 0:k.sandbox)||null,m=this.mapPlacementAttributes(k,this.placementAttributesMapping),(null===(d=this.logger)||void 0===d?void 0:d.isVerbose())&&(n=obfuscateDevData(k,null===(f=null===(e=this.store)||void 0===e?void 0:e.SDKConfig)||void 0===f?void 0:f.isDevelopmentMode),this.logger.verbose("mParticle.Rokt selectPlacements called with attributes:\n".concat(JSON.stringify(n,null,2)))),this.currentUser=this.identityService.getCurrentUser(),o=(null===(h=null===(g=this.currentUser)||void 0===g?void 0:g.getUserIdentities())||void 0===h?void 0:h.userIdentities)||{},p=o.email,q=m.email,r=void 0,s=void 0,t=this.mappedEmailShaIdentityType&&!1!==IdentityType.getIdentityType(this.mappedEmailShaIdentityType),t&&(r=o[this.mappedEmailShaIdentityType],s=m.emailsha256||m[this.mappedEmailShaIdentityType]||void 0),u=this.hasIdentityChanged(p,q),v=this.hasIdentityChanged(r,s),w={},u&&(w.email=q,q&&(x="Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.",this.logger.warning(x),null===(i=this.errorReporter)||void 0===i?void 0:i.report({message:x,code:ErrorCodes.IDENTITY_MISMATCH,severity:WSDKErrorSeverity.WARNING}))),v&&(w[this.mappedEmailShaIdentityType]=s,x="emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.",this.logger.warning(x),null===(j=this.errorReporter)||void 0===j?void 0:j.report({message:x,code:ErrorCodes.IDENTITY_MISMATCH,severity:WSDKErrorSeverity.WARNING})),!isEmpty(w))// Fire-and-forget identify — best-effort, does not block selectPlacements
try{this.identityService.identify({userIdentities:__assign(__assign({},o),w)},function(a){var b=+(null===a||void 0===a?void 0:a.httpCode);b&&(400<=b||0>b)&&D.logger.error("Background identify failed with HTTP "+b),D.processMessageQueue();});}catch(a){y=a instanceof Error?a.message:JSON.stringify(a),this.logger.error("Background identify threw an error: "+y);}return z=__assign(__assign({},o),w),this.setUserAttributes(m),A=__assign(__assign({},m),null===l?{}:{sandbox:l}),z.email&&!A.email&&(A.email=z.email),t&&(B=z[this.mappedEmailShaIdentityType],B&&!A.emailsha256&&!A[this.mappedEmailShaIdentityType]&&(A.emailsha256=B)),this.filters.filteredUser=this.currentUser||this.filters.filteredUser||null,C=__assign(__assign({},a),{attributes:A}),[2/*return*/,this.kit.selectPlacements(C)]}catch(a){return [2/*return*/,Promise.reject(a instanceof Error?a:new Error("Unknown error occurred"))]}return [2/*return*/]})})},a.prototype.hashAttributes=function(a){return __awaiter(this,void 0,void 0,function(){var b,c,d,e,f,g,h,i,j,k,l,m,n=this;return __generator(this,function(o){switch(o.label){case 0:return (o.trys.push([0,2,,3]),!a||"object"!==_typeof$1(a))?[2/*return*/,{}]:(b=Object.keys(a),0===b.length)?[2/*return*/,{}]:(c=b.map(function(b){return __awaiter(n,void 0,void 0,function(){var c,d;return __generator(this,function(e){switch(e.label){case 0:return c=a[b],[4/*yield*/,this.hashSha256(c)];case 1:return d=e.sent(),[2/*return*/,{key:b,attributeValue:c,hashedValue:d}]}})})}),[4/*yield*/,Promise.all(c)]);case 1:for(d=o.sent(),e={},(f=0,g=d);fAll of the following methods can be called on the primary mParticle class. In version 2.10.0, we introduced multiple instances. If you are using multiple instances (self hosted environments only), you should call these methods on each instance.
* In current versions of mParticle, if your site has one instance, that instance name is 'default_instance'. Any methods called on mParticle on a site with one instance will be mapped to the `default_instance`.
* This is for simplicity and backwards compatibility. For example, calling mParticle.logPageView() automatically maps to mParticle.getInstance('default_instance').logPageView().
* If you have multiple instances, instances must first be initialized and then a method can be called on that instance. For example:
*
* mParticle.init('apiKey', config, 'another_instance');
* mParticle.getInstance('another_instance').logPageView();
*
*
* @class mParticle & mParticleInstance
*/function mParticleInstance(a){var b=this;// These classes are for internal use only. Not documented for public consumption
this._instanceName=a,this._NativeSdkHelpers=new NativeSdkHelpers(this),this._SessionManager=new SessionManager(this),this._Persistence=new _Persistence(this),this._Helpers=new Helpers(this),this._Events=new Events(this),this._CookieSyncManager=new CookieSyncManager(this),this._ServerModel=new ServerModel(this),this._Ecommerce=new Ecommerce(this),this._ForwardingStatsUploader=new forwardingStatsUploader(this),this._Consent=new Consent(this),this._IdentityAPIClient=new IdentityAPIClient(this),this._preInit={readyQueue:[],integrationDelays:{},forwarderConstructors:[]},this._ErrorReportingDispatcher=new ErrorReportingDispatcher,this._LoggingDispatcher=new LoggingDispatcher,this._RoktManager=new RoktManager,this._RoktManager.setOnReadyCallback(function(){b.processQueueOnIdentityFailure();}),this.processQueueOnIdentityFailure=function(){var a,c,d;(null===(a=b._Store)||void 0===a?void 0:a.isInitialized)||(null===(c=b._Store)||void 0===c?void 0:c.identityCallFailed)&&(null===(d=b._RoktManager)||void 0===d?void 0:d.isReady())&&(b._RoktManager.processMessageQueue(),b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));},this.processQueueOnNoFunctional=function(){var a,c;if(!(null!==(a=b._Store)&&void 0!==a)||!a.isInitialized){var d=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);d&&(b._preInit.readyQueue=processReadyQueue(b._preInit.readyQueue));}},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this._Identity=new Identity(this),this.Identity=this._Identity.IdentityAPI,this.generateHash=this._Helpers.generateHash,this.getDeviceId=this._Persistence.getDeviceId,"undefined"!=typeof window&&window.mParticle&&window.mParticle.config&&window.mParticle.config.hasOwnProperty("rq")&&(this._preInit.readyQueue=window.mParticle.config.rq),this.init=function(a,b){var c=this;// config code - Fetch config when requestConfig = true, otherwise, proceed with SDKInitialization
// Since fetching the configuration is asynchronous, we must pass completeSDKInitialization
// to it for it to be run after fetched
if(b||console.warn("You did not pass a config object to init(). mParticle will not initialize properly"),runPreConfigFetchInitialization(this,a,b),!b)return void console.error("No config available on the window, please pass a config object to mParticle.init()");if(!b.hasOwnProperty("requestConfig")||b.requestConfig){var d=new ConfigAPIClient(a,b,this);d.getSDKConfiguration().then(function(d){var e=extend({},b,d);completeSDKInitialization(a,e,c);});}else completeSDKInitialization(a,b,this);},this.setLogLevel=function(a){b.Logger.setLogLevel(a);},this.reset=function(a){try{a._Persistence.resetPersistence(),a._Store&&delete a._Store;}catch(a){console.error("Cannot reset mParticle",a);}},this._resetForTests=function(a,b,c){c._Store&&delete c._Store,c._ErrorReportingDispatcher=new ErrorReportingDispatcher,c._LoggingDispatcher=new LoggingDispatcher,c.Logger=new Logger(a),c._ErrorReportingDispatcher.logger=c.Logger,c._LoggingDispatcher.logger=c.Logger,c._Store=new Store(a,c),c._Store.isLocalStorageAvailable=c._Persistence.determineLocalStorageAvailability(window.localStorage),c._Events.stopTracking(),b||c._Persistence.resetPersistence(),c._Persistence.forwardingStatsBatches.uploadsTable={},c._Persistence.forwardingStatsBatches.forwardingStatsEventQueue=[],c._preInit={readyQueue:[],pixelConfigurations:[],integrationDelays:{},forwarderConstructors:[],isDevelopmentMode:!1};},this.ready=function(a){var c,d,e,f=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store),g=isFunction(a)&&((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||(null===(e=b._Store)||void 0===e?void 0:e.identityCallFailed)&&b._RoktManager.isReady()||f);g?a():b._preInit.readyQueue.push(a);},this.getEnvironment=function(){return b._Store.SDKConfig.isDevelopmentMode?Constants.Environment.Development:Constants.Environment.Production},this.getVersion=function(){return Constants.sdkVersion},this.setAppVersion=function(a){var c=queueIfNotInitialized(function(){b.setAppVersion(a);},b);c||(b._Store.SDKConfig.appVersion=a,b._Persistence.update());},this.setDeviceId=function(a){var c=queueIfNotInitialized(function(){b.setDeviceId(a);},b);c||this._Store.setDeviceId(a);},this.isInitialized=function(){return !!b._Store&&b._Store.isInitialized},this.getAppName=function(){return b._Store.SDKConfig.appName},this.setAppName=function(a){var c=queueIfNotInitialized(function(){b.setAppName(a);},b);c||(b._Store.SDKConfig.appName=a);},this.getAppVersion=function(){return b._Store.SDKConfig.appVersion},this.stopTrackingLocation=function(){b._SessionManager.resetSessionTimer(),b._Events.stopTracking();},this.startTrackingLocation=function(a){isFunction(a)||b.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location."),b._SessionManager.resetSessionTimer(),b._Events.startTracking(a);},this.setPosition=function(a,c){var d=queueIfNotInitialized(function(){b.setPosition(a,c);},b);d||(b._SessionManager.resetSessionTimer(),"number"==typeof a&&"number"==typeof c?b._Store.currentPosition={lat:a,lng:c}:b.Logger.error("Position latitude and/or longitude must both be of type number"));},this.startNewSession=function(){b._SessionManager.startNewSession();},this.endSession=function(){// Sends true as an over ride vs when endSession is called from the setInterval
b._SessionManager.endSession(!0);},this.logBaseEvent=function(a,c){var d=queueIfNotInitialized(function(){b.logBaseEvent(a,c);},b);if(!d)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a.name)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(a.eventType||(a.eventType=EventType.Unknown),b._Helpers.canLog()?void b._Events.logEvent(a,c):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled))},this.logEvent=function(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.logEvent(a,c,d,e,f);},b);if(!g)return (b._SessionManager.resetSessionTimer(),"string"!=typeof a)?void b.Logger.error(Messages.ErrorMessages.EventNameInvalidType):(c||(c=EventType.Unknown),b._Helpers.isEventType(c)?b._Helpers.canLog()?void b._Events.logEvent({messageType:MessageType$1.PageEvent,name:a,data:d,eventType:c,customFlags:e},f):void b.Logger.error(Messages.ErrorMessages.LoggingDisabled):void b.Logger.error("Invalid event type: "+c+", must be one of: \n"+JSON.stringify(EventType)))},this.logError=function(a,c){var d=queueIfNotInitialized(function(){b.logError(a,c);},b);if(!d&&(b._SessionManager.resetSessionTimer(),!!a)){"string"==typeof a&&(a={message:a});var e={m:a.message?a.message:a,s:"Error",t:a.stack||null};if(c){var f=b._Helpers.sanitizeAttributes(c,e.m);for(var g in f)e[g]=f[g];}b._Events.logEvent({messageType:MessageType$1.CrashReport,name:a.name?a.name:"Error",eventType:EventType.Other,data:e});}},this.logLink=function(a,c,d,e){b._Events.addEventHandler("click",a,c,e,d);},this.logForm=function(a,c,d,e){b._Events.addEventHandler("submit",a,c,e,d);},this.logPageView=function(a,c,d,e){var f=queueIfNotInitialized(function(){b.logPageView(a,c,d,e);},b);if(!f){if(b._SessionManager.resetSessionTimer(),b._Helpers.canLog()){if(b._Helpers.Validators.isStringOrNumber(a)||(a="PageView"),!c)c={hostname:window.location.hostname,title:window.document.title};else if(!b._Helpers.isObject(c))return void b.Logger.error("The attributes argument must be an object. A "+_typeof$1(c)+" was entered. Please correct and retry.");if(d&&!b._Helpers.isObject(d))return void b.Logger.error("The customFlags argument must be an object. A "+_typeof$1(d)+" was entered. Please correct and retry.")}b._Events.logEvent({messageType:MessageType$1.PageView,name:a,data:c,eventType:EventType.Unknown,customFlags:d},e);}},this.upload=function(){var a,c;b._Helpers.canLog()&&(b._Store.webviewBridgeEnabled?b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload):null===(c=null===(a=b._APIClient)||void 0===a?void 0:a.uploader)||void 0===c?void 0:c.prepareAndUpload(!1,!1));},this.Consent={/**
* Creates a CCPA Opt Out Consent State.
*
* @method createCCPAConsent
* @param {Boolean} optOut true represents a "data sale opt-out", false represents the user declining a "data sale opt-out"
* @param {Number} timestamp Unix time (likely to be Date.now())
* @param {String} consentDocument document version or experience that the user may have consented to
* @param {String} location location where the user gave consent
* @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users
* @return {Object} CCPA Consent State
*/createCCPAConsent:b._Consent.createPrivacyConsent,/**
* Creates a GDPR Consent State.
*
* @method createGDPRConsent
* @param {Boolean} consent true represents a "data sale opt-out", false represents the user declining a "data sale opt-out"
* @param {Number} timestamp Unix time (likely to be Date.now())
* @param {String} consentDocument document version or experience that the user may have consented to
* @param {String} location location where the user gave consent
* @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users
* @return {Object} GDPR Consent State
*/createGDPRConsent:b._Consent.createPrivacyConsent,/**
* Creates a Consent State Object, which can then be used to set CCPA states, add multiple GDPR states, as well as get and remove these privacy states.
*
* @method createConsentState
* @return {Object} ConsentState object
*/createConsentState:b._Consent.createConsentState},this.eCommerce={/**
* Invoke these methods on the mParticle.eCommerce.Cart object.
* Example: mParticle.eCommerce.Cart.add(...)
* @class mParticle.eCommerce.Cart
* @deprecated
*/Cart:{/**
* Adds a product to the cart
* @method add
* @param {Object} product The product you want to add to the cart
* @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
* @deprecated
*/add:function add(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.add()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/**
* Removes a product from the cart
* @method remove
* @param {Object} product The product you want to add to the cart
* @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
* @deprecated
*/remove:function remove(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.remove()",!0,"eCommerce.logProductAction()","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));},/**
* Clears the cart
* @method clear
* @deprecated
*/clear:function clear(){b.Logger.warning(generateDeprecationMessage("eCommerce.Cart.clear()",!0,"","https://docs.mparticle.com/developers/sdk/web/commerce-tracking"));}},/**
* Sets the currency code
* @for mParticle.eCommerce
* @method setCurrencyCode
* @param {String} code The currency code
*/setCurrencyCode:function setCurrencyCode(a){var c=queueIfNotInitialized(function(){b.eCommerce.setCurrencyCode(a);},b);return c?void 0:"string"==typeof a?void(b._SessionManager.resetSessionTimer(),b._Store.currencyCode=a):void b.Logger.error("Code must be a string")},/**
* Creates a product
* @for mParticle.eCommerce
* @method createProduct
* @param {String} name product name
* @param {String} sku product sku
* @param {Number} price product price
* @param {Number} [quantity] product quantity. If blank, defaults to 1.
* @param {String} [variant] product variant
* @param {String} [category] product category
* @param {String} [brand] product brand
* @param {Number} [position] product position
* @param {String} [coupon] product coupon
* @param {Object} [attributes] product attributes
*/createProduct:function createProduct(a,c,d,e,f,g,h,i,j,k){return b._Ecommerce.createProduct(a,c,d,e,f,g,h,i,j,k)},/**
* Creates a promotion
* @for mParticle.eCommerce
* @method createPromotion
* @param {String} id a unique promotion id
* @param {String} [creative] promotion creative
* @param {String} [name] promotion name
* @param {Number} [position] promotion position
*/createPromotion:function createPromotion(a,c,d,e){return b._Ecommerce.createPromotion(a,c,d,e)},/**
* Creates a product impression
* @for mParticle.eCommerce
* @method createImpression
* @param {String} name impression name
* @param {Object} product the product for which an impression is being created
*/createImpression:function createImpression(a,c){return b._Ecommerce.createImpression(a,c)},/**
* Creates a transaction attributes object to be used with a checkout
* @for mParticle.eCommerce
* @method createTransactionAttributes
* @param {String or Number} id a unique transaction id
* @param {String} [affiliation] affilliation
* @param {String} [couponCode] the coupon code for which you are creating transaction attributes
* @param {Number} [revenue] total revenue for the product being purchased
* @param {String} [shipping] the shipping method
* @param {Number} [tax] the tax amount
*/createTransactionAttributes:function createTransactionAttributes(a,c,d,e,f,g){return b._Ecommerce.createTransactionAttributes(a,c,d,e,f,g)},/**
* Logs a checkout action
* @for mParticle.eCommerce
* @method logCheckout
* @param {Number} step checkout step number
* @param {String} checkout option string
* @param {Object} attrs
* @param {Object} [customFlags] Custom flags for the event
* @deprecated
*/logCheckout:function logCheckout(a,c,d,e){return b.Logger.warning("mParticle.logCheckout is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logCheckoutEvent(a,c,d,e)):void b.ready(function(){b.eCommerce.logCheckout(a,c,d,e);})},/**
* Logs a product action
* @for mParticle.eCommerce
* @method logProductAction
* @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218)
* @param {Object} product the product for which you are creating the product action
* @param {Object} [attrs] attributes related to the product action
* @param {Object} [customFlags] Custom flags for the event
* @param {Object} [transactionAttributes] Transaction Attributes for the event
* @param {Object} [eventOptions] For Event-level Configuration Options
*/logProductAction:function logProductAction(a,c,d,e,f,g){var h=queueIfNotInitialized(function(){b.eCommerce.logProductAction(a,c,d,e,f,g);},b);h||(b._SessionManager.resetSessionTimer(),b._Events.logProductActionEvent(a,c,d,e,f,g));},/**
* Logs a product purchase
* @for mParticle.eCommerce
* @method logPurchase
* @param {Object} transactionAttributes transactionAttributes object
* @param {Object} product the product being purchased
* @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false
* @param {Object} [attrs] other attributes related to the product purchase
* @param {Object} [customFlags] Custom flags for the event
* @deprecated
*/logPurchase:function logPurchase(a,c,d,e,f){return b.Logger.warning("mParticle.logPurchase is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?a&&c?void(b._SessionManager.resetSessionTimer(),b._Events.logPurchaseEvent(a,c,e,f)):void b.Logger.error(Messages.ErrorMessages.BadLogPurchase):void b.ready(function(){b.eCommerce.logPurchase(a,c,d,e,f);})},/**
* Logs a product promotion
* @for mParticle.eCommerce
* @method logPromotion
* @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279)
* @param {Object} promotion promotion object
* @param {Object} [attrs] boolean to clear the cart after logging or not
* @param {Object} [customFlags] Custom flags for the event
* @param {Object} [eventOptions] For Event-level Configuration Options
*/logPromotion:function logPromotion(a,c,d,e,f){var g=queueIfNotInitialized(function(){b.eCommerce.logPromotion(a,c,d,e,f);},b);g||(b._SessionManager.resetSessionTimer(),b._Events.logPromotionEvent(a,c,d,e,f));},/**
* Logs a product impression
* @for mParticle.eCommerce
* @method logImpression
* @param {Object} impression product impression object
* @param {Object} attrs attributes related to the impression log
* @param {Object} [customFlags] Custom flags for the event
* @param {Object} [eventOptions] For Event-level Configuration Options
*/logImpression:function logImpression(a,c,d,e){var f=queueIfNotInitialized(function(){b.eCommerce.logImpression(a,c,d,e);},b);f||(b._SessionManager.resetSessionTimer(),b._Events.logImpressionEvent(a,c,d,e));},/**
* Logs a refund
* @for mParticle.eCommerce
* @method logRefund
* @param {Object} transactionAttributes transaction attributes related to the refund
* @param {Object} product product being refunded
* @param {Boolean} [clearCart] boolean to clear the cart after refund is logged. Defaults to false.
* @param {Object} [attrs] attributes related to the refund
* @param {Object} [customFlags] Custom flags for the event
* @deprecated
*/logRefund:function logRefund(a,c,d,e,f){return b.Logger.warning("mParticle.logRefund is deprecated, please use mParticle.logProductAction instead"),b._Store.isInitialized?void(b._SessionManager.resetSessionTimer(),b._Events.logRefundEvent(a,c,e,f)):void b.ready(function(){b.eCommerce.logRefund(a,c,d,e,f);})},expandCommerceEvent:function expandCommerceEvent(a){return b._Ecommerce.expandCommerceEvent(a)}},this.setSessionAttribute=function(a,c){var d,e=(null===(d=b._CookieConsentManager)||void 0===d?void 0:d.getNoFunctional())&&!hasExplicitIdentifier(b._Store);if(!e){var f=queueIfNotInitialized(function(){b.setSessionAttribute(a,c);},b);if(f)return}// Logs to cookie
// And logs to in-memory object
// Example: mParticle.setSessionAttribute('location', '33431');
if(b._Helpers.canLog()){if(!b._Helpers.Validators.isValidAttributeValue(c))return void b.Logger.error(Messages.ErrorMessages.BadAttribute);if(!b._Helpers.Validators.isValidKeyValue(a))return void b.Logger.error(Messages.ErrorMessages.BadKey);if(b._Store.webviewBridgeEnabled)b._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute,JSON.stringify({key:a,value:c}));else {var g=b._Helpers.findKeyInObject(b._Store.sessionAttributes,a);g&&(a=g),b._Store.sessionAttributes[a]=c,b._Persistence.update(),b._Forwarders.applyToForwarders("setSessionAttribute",[a,c]);}}},this.setOptOut=function(a){var c=queueIfNotInitialized(function(){b.setOptOut(a);},b);c||(b._SessionManager.resetSessionTimer(),b._Store.isEnabled=!a,b._Events.logOptOut(),b._Persistence.update(),b._Store.activeForwarders.length&&b._Store.activeForwarders.forEach(function(c){if(c.setOptOut){var d=c.setOptOut(a);d&&b.Logger.verbose(d);}}));},this.setIntegrationAttribute=function(a,c){var d=queueIfNotInitialized(function(){b.setIntegrationAttribute(a,c);},b);if(!d){if("number"!=typeof a)return void b.Logger.error("integrationId must be a number");if(null===c)b._Store.integrationAttributes[a]={};else {if(!b._Helpers.isObject(c))return void b.Logger.error("Attrs must be an object with keys and values. You entered a "+_typeof$1(c));if(0===Object.keys(c).length)b._Store.integrationAttributes[a]={};else for(var e in c)if("string"!=typeof e){b.Logger.error("Keys must be strings, you entered a "+_typeof$1(e));continue}else if("string"==typeof c[e])b._Helpers.isObject(b._Store.integrationAttributes[a])?b._Store.integrationAttributes[a][e]=c[e]:(b._Store.integrationAttributes[a]={},b._Store.integrationAttributes[a][e]=c[e]);else {b.Logger.error("Values for integration attributes must be strings. You entered a "+_typeof$1(c[e]));continue}}b._Persistence.update();}},this.getIntegrationAttributes=function(a){return b._Store.integrationAttributes[a]?b._Store.integrationAttributes[a]:{}},this.addForwarder=function(a){b._preInit.forwarderConstructors.push(a);},this.configurePixel=function(a){b._Forwarders.configurePixel(a);},this._getActiveForwarders=function(){return b._Store.activeForwarders},this._getIntegrationDelays=function(){return b._preInit.integrationDelays},this._setIntegrationDelay=function(a,c){// If the integration delay is set to true, no further action needed
if(b._preInit.integrationDelays[a]=c,!0!==c){// If the integration delay is set to false, check to see if there are any
// other integration delays set to true. It not, process the queued events/.
var d=Object.keys(b._preInit.integrationDelays);if(0!==d.length){var e=d.some(function(a){return !0===b._preInit.integrationDelays[a]});e||b._APIClient.processQueuedEvents();}}},this._setWrapperSDKInfo=function(a,c){var d=queueIfNotInitialized(function(){b._setWrapperSDKInfo(a,c);},b);d||(b._Store.wrapperSDKInfo===void 0||!b._Store.wrapperSDKInfo.isInfoSet)&&(b._Store.wrapperSDKInfo={name:a,version:c,isInfoSet:!0});},this._registerErrorReportingService=function(a){b._ErrorReportingDispatcher.register(a);},this._registerLoggingService=function(a){b._LoggingDispatcher.register(a);};var c=Constants.Rokt.LauncherInstanceGuidKey;this.setLauncherInstanceGuid=function(){window[c]&&"string"==typeof window[c]||(window[c]=b._Helpers.generateUniqueId());},this.getLauncherInstanceGuid=function(){return window[c]},this.captureTiming=function(a){var b;"undefined"!=typeof window&&(null===(b=window.performance)||void 0===b?void 0:b.mark)&&window.performance.mark(a);};}// Some (server) config settings need to be returned before they are set on SDKConfig in a self hosted environment
function completeSDKInitialization(a,b,c){var d,e,f,g,h=createKitBlocker(b,c),i=c._Helpers.getFeatureFlag;// Destroy previous batch uploader to prevent leaked timers and event listeners
// Web View Bridge is used for cases where the Web SDK is loaded within an iOS or Android device's
// Web View. The Web SDK simply acts as a passthrough to the mParticle Native SDK. It is not
// responsible for sending events directly to mParticle's servers. The Web SDK will not initialize
// persistence or Identity directly.
if((null===(d=c._APIClient)||void 0===d?void 0:d.uploader)&&c._APIClient.uploader.destroy(),c._APIClient=new APIClient(c,h),c._Forwarders=new Forwarders(c,h),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
var j=c.Identity.getCurrentUser(),k=j?j.getMPID():null,l=j?j.getUserIdentities().userIdentities:{};c._Store.SDKConfig.identifyRequest=c._Store.hasInvalidIdentifyRequest()?{userIdentities:l}:c._Store.SDKConfig.identifyRequest,i(ReportBatching)&&c._ForwardingStatsUploader.startForwardingStatsTimer();// https://go.mparticle.com/work/SQDSDKS-7639
var m=i(CaptureIntegrationSpecificIds),n=i(CaptureIntegrationSpecificIdsV2),o=n&&n!==CaptureIntegrationSpecificIdsV2Modes.None||!0===m;if(o){var p;m||n===CaptureIntegrationSpecificIdsV2Modes.All?p="all":n===CaptureIntegrationSpecificIdsV2Modes.RoktOnly&&(p="roktonly"),c._IntegrationCapture=new IntegrationCapture(p),c._IntegrationCapture.capture();}// Configure Rokt Manager with user and filtered user
var q=parseConfig(b,"Rokt",181);if(q){var r=null===(e=q.settings)||void 0===e?void 0:e.accountId;c._Store.setRoktAccountId(r);var s=q.userAttributeFilters,t=filteredMparticleUser(k,{userAttributeFilters:s},c),u={sandbox:null===b||void 0===b?void 0:b.isDevelopmentMode,launcherOptions:null===b||void 0===b?void 0:b.launcherOptions,domain:null===b||void 0===b?void 0:b.domain};// https://go.mparticle.com/work/SQDSDKS-7339
c._RoktManager.init(q,t,c.Identity,c._Store,c.Logger,u,c.captureTiming,c._ErrorReportingDispatcher,c._LoggingDispatcher);}c._Forwarders.processForwarders(b,c._APIClient.prepareForwardingStats),c._Forwarders.processPixelConfigs(b),c._SessionManager.initialize(),c._Events.logAST(),processIdentityCallback(c,j,k,l);}// We will continue to clear out the ready queue as part of the initial init flow
// if an identify request is unnecessary, such as if there is an existing session
(c._Store.mpid&&!c._Store.identifyCalled||c._Store.webviewBridgeEnabled)&&(c._Store.isInitialized=!0,null===(f=c._CookieConsentManager)||void 0===f?void 0:f.syncNoTargetingAttribute(c.Identity.getCurrentUser()),c._preInit.readyQueue=processReadyQueue(c._preInit.readyQueue)),null===(g=c.processQueueOnNoFunctional)||void 0===g?void 0:g.call(c),c._Store.isFirstRun&&(c._Store.isFirstRun=!1);}// https://go.mparticle.com/work/SQDSDKS-7061
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:
1. Manually via config.dataPlanOptions (this takes priority)
If not passed in manually, we user the server provided via either
2. Snippet via /mparticle.js endpoint (config.dataPlan.document)
3. Self hosting via /config endpoint (config.dataPlanResult)
*/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){var b;// Identity expects mpInstance._Identity.idCache to always exist. DisabledVault
// ensures no identity response data is written to localStorage when noFunctional is true
return (null===(b=a._CookieConsentManager)||void 0===b?void 0:b.getNoFunctional())?new DisabledVault("".concat(a._Store.storageName,"-id-cache")):new LocalStorageVault("".concat(a._Store.storageName,"-id-cache"))}function runPreConfigFetchInitialization(a,b,c){var d;a.Logger=new Logger(c),a._ErrorReportingDispatcher.logger=a.Logger,a._LoggingDispatcher.logger=a.Logger,a._Store=new Store(c,a,b),window.mParticle.Store=a._Store,a.Logger.verbose(StartingInitialization);// Initialize CookieConsentManager with privacy flags from launcherOptions
var e=null!==(d=null===c||void 0===c?void 0:c.launcherOptions)&&void 0!==d?d:{},f=e.noFunctional,g=e.noTargeting;a._CookieConsentManager=new CookieConsentManager({noFunctional:f,noTargeting:g});// Check to see if localStorage is available before main configuration runs
// since we will need this for the current implementation of user persistence
// TODO: Refactor this when we refactor User Identity Persistence
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){var c,d,e=(null===(c=b._CookieConsentManager)||void 0===c?void 0:c.getNoFunctional())&&!hasExplicitIdentifier(b._Store);// When noFunctional is true with no explicit identifier, the SDK will never
// receive an MPID. Let these calls through so events can still reach forwarders immediately.
// sendEventToServer handles queuing for the MP server upload path separately.
return !((null===(d=b._Store)||void 0===d?void 0:d.isInitialized)||e)&&(b._preInit.readyQueue.push(function(){var c;(null===(c=b._Store)||void 0===c?void 0:c.isInitialized)&&a();}),!0)}
// This file is used ONLY for the mParticle ESLint plugin. It should NOT be used otherwise!
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
_Helpers:{sanitizeAttributes:window.mParticle.getInstance()._Helpers.sanitizeAttributes,generateHash:function generateHash(){return "mockHash"},generateUniqueId:function generateUniqueId(){return "mockId"},extend:extend,createServiceUrl:mockFunction,parseNumber:mockFunction,isObject:mockFunction,Validators:null},_resetForTests:mockFunction,_APIClient:null,_timeOnSiteTimer:{getTimeInForeground:mockFunction},MPSideloadedKit:null,_Consent:null,_Events:null,_Forwarders:null,_NativeSdkHelpers:null,_Persistence:null,_preInit:null,Consent:null,_ServerModel:null,_SessionManager:null,_Store:{sessionId:"mockSessionId",sideloadedKits:[],devToken:"test_dev_token",isFirstRun:!0,isEnabled:!0,sessionAttributes:{},currentSessionMPIDs:[],consentState:null,clientId:null,deviceId:null,serverSettings:{},dateLastEventSent:null,sessionStartDate:null,currentPosition:null,isTracking:!1,watchPositionId:null,cartProducts:[],eventQueue:[],currencyCode:null,globalTimer:null,context:null,configurationLoaded:!1,identityCallInFlight:!1,nonCurrentUserMPIDs:{},identifyCalled:!1,isLoggedIn:!1,cookieSyncDates:{},integrationAttributes:{},requireDelay:!0,isLocalStorageAvailable:null,integrationDelayTimeoutStart:null,storageName:null,prodStorageName:null,activeForwarders:[],kits:{},configuredForwarders:[],pixelConfigurations:[],wrapperSDKInfo:{name:"none",version:null,isInfoSet:!1},SDKConfig:{isDevelopmentMode:!1,onCreateBatch:mockFunction}},config:null,eCommerce:null,Identity:{getCurrentUser:mockFunction,IdentityAPI:{},identify:mockFunction,login:mockFunction,logout:mockFunction,modify:mockFunction},Logger:{verbose:mockFunction,error:mockFunction,warning:mockFunction},ProductActionType:null,ServerModel:null,addForwarder:mockFunction,generateHash:mockFunction,getAppVersion:mockFunction,getAppName:mockFunction,getInstance:mockFunction,getDeviceId:mockFunction,init:mockFunction,logBaseEvent:mockFunction,logEvent:mockFunction,logLevel:"none",setPosition:mockFunction,upload:mockFunction}},a.prototype.createSDKEventFunction=function(a){return new ServerModel(this.getMPInstance()).createEventObject(a)},a.prototype.returnBatch=function(a){var b=this,c=this.getMPInstance(),d=Array.isArray(a)?a.map(function(a){return b.createSDKEventFunction(a)}):[this.createSDKEventFunction(a)],e=convertEvents("0",d,c);return e},a}();
var MPSideloadedKit=/** @class */function(){function a(a){this.filterDictionary={eventTypeFilters:[],eventNameFilters:[],screenNameFilters:[],screenAttributeFilters:[],userIdentityFilters:[],userAttributeFilters:[],attributeFilters:[],consentRegulationFilters:[],consentRegulationPurposeFilters:[],messageTypeFilters:[],messageTypeStateFilters:[],// The below filtering members are optional, but we instantiate them
// to simplify public method assignment
filteringEventAttributeValue:{},filteringUserAttributeValue:{},filteringConsentRuleValues:{}},this.kitInstance=a;}return a.prototype.addEventTypeFilter=function(a){var b=KitFilterHelper.hashEventType(a);this.filterDictionary.eventTypeFilters.push(b);},a.prototype.addEventNameFilter=function(a,b){var c=KitFilterHelper.hashEventName(b,a);this.filterDictionary.eventNameFilters.push(c);},a.prototype.addEventAttributeFilter=function(a,b,c){var d=KitFilterHelper.hashEventAttributeKey(a,b,c);this.filterDictionary.attributeFilters.push(d);},a.prototype.addScreenNameFilter=function(a){var b=KitFilterHelper.hashEventName(a,EventType.Unknown);this.filterDictionary.screenNameFilters.push(b);},a.prototype.addScreenAttributeFilter=function(a,b){var c=KitFilterHelper.hashEventAttributeKey(EventType.Unknown,a,b);this.filterDictionary.screenAttributeFilters.push(c);},a.prototype.addUserIdentityFilter=function(a){var b=KitFilterHelper.hashUserIdentity(a);this.filterDictionary.userIdentityFilters.push(b);},a.prototype.addUserAttributeFilter=function(a){var b=KitFilterHelper.hashUserAttribute(a);this.filterDictionary.userAttributeFilters.push(b);},a}();
Array.prototype.forEach||(Array.prototype.forEach=Polyfill.forEach),Array.prototype.map||(Array.prototype.map=Polyfill.map),Array.prototype.filter||(Array.prototype.filter=Polyfill.filter),Array.isArray||(Array.prototype.isArray=Polyfill.isArray);function mParticleInstanceManager(){var a=this;// Only leaving this here in case any clients are trying to access mParticle.Store, to prevent from throwing
/**
* Initializes the mParticle instance. If no instanceName is provided, an instance name of `default_instance` will be used.
*
* If you'd like to initiate multiple mParticle instances, first review our doc site, and ensure you pass a unique instance name as the third argument as shown below.
* @method init
* @param {String} apiKey your mParticle assigned API key
* @param {Object} [config] an options object for additional configuration
* @param {String} [instanceName] If you are self hosting the JS SDK and working with multiple instances, you would pass an instanceName to `init`. This instance will be selected when invoking other methods. See the above link to the doc site for more info and examples.
*/this.Store={},this._instances={},this.IdentityType=IdentityType,this.EventType=EventType,this.CommerceEventType=CommerceEventType,this.PromotionType=PromotionActionType,this.ProductActionType=ProductActionType,this.MPSideloadedKit=MPSideloadedKit,"undefined"!=typeof window&&(this.isIOS=!!(window.mParticle&&window.mParticle.isIOS)&&window.mParticle.isIOS,this.config=window.mParticle&&window.mParticle.config?window.mParticle.config:{}),this.init=function(b,c,d){!c&&window.mParticle&&window.mParticle.config&&(console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly"),c=window.mParticle?window.mParticle.config:{}),d=(d&&0!==d.length?d:Constants.DefaultInstance).toLowerCase();var e=a._instances[d];e===void 0&&(e=new mParticleInstance(d),a._instances[d]=e),e.captureTiming(PerformanceMarkType.SdkStart),e.setLauncherInstanceGuid(),e.init(b,c,d);},this.captureTiming=function(b){a.getInstance().captureTiming(b);},this.getInstance=function(b){var c;return b?(c=a._instances[b.toLowerCase()],c?c:(console.log("You tried to initialize an instance named "+b+". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it."),null)):(b=Constants.DefaultInstance,c=a._instances[b],c||(c=new mParticleInstance(b),a._instances[Constants.DefaultInstance]=c),c)},this.Rokt=a.getInstance()._RoktManager,this.getDeviceId=function(){return a.getInstance().getDeviceId()},this.setDeviceId=function(b){return a.getInstance().setDeviceId(b)},this.isInitialized=function(){return a.getInstance().isInitialized()},this.startNewSession=function(){a.getInstance().startNewSession();},this.endSession=function(){a.getInstance().endSession();},this.setLogLevel=function(b){a.getInstance().setLogLevel(b);},this.ready=function(b){a.getInstance().ready(b);},this.setAppVersion=function(b){a.getInstance().setAppVersion(b);},this.getAppName=function(){return a.getInstance().getAppName()},this.setAppName=function(b){a.getInstance().setAppName(b);},this.getAppVersion=function(){return a.getInstance().getAppVersion()},this.getEnvironment=function(){return a.getInstance().getEnvironment()},this.stopTrackingLocation=function(){a.getInstance().stopTrackingLocation();},this.startTrackingLocation=function(b){a.getInstance().startTrackingLocation(b);},this.setPosition=function(b,c){a.getInstance().setPosition(b,c);},this.logBaseEvent=function(b,c){a.getInstance().logBaseEvent(b,c);},this.logEvent=function(b,c,d,e,f){a.getInstance().logEvent(b,c,d,e,f);},this.logError=function(b,c){a.getInstance().logError(b,c);},this.logLink=function(b,c,d,e){a.getInstance().logLink(b,c,d,e);},this.logForm=function(b,c,d,e){a.getInstance().logForm(b,c,d,e);},this.logPageView=function(b,c,d,e){a.getInstance().logPageView(b,c,d,e);},this.upload=function(){a.getInstance().upload();},this.eCommerce={Cart:{add:function add(b,c){a.getInstance().eCommerce.Cart.add(b,c);},remove:function remove(b,c){a.getInstance().eCommerce.Cart.remove(b,c);},clear:function clear(){a.getInstance().eCommerce.Cart.clear();}},setCurrencyCode:function setCurrencyCode(b){a.getInstance().eCommerce.setCurrencyCode(b);},createProduct:function createProduct(b,c,d,e,f,g,h,i,j,k){return a.getInstance().eCommerce.createProduct(b,c,d,e,f,g,h,i,j,k)},createPromotion:function createPromotion(b,c,d,e){return a.getInstance().eCommerce.createPromotion(b,c,d,e)},createImpression:function createImpression(b,c){return a.getInstance().eCommerce.createImpression(b,c)},createTransactionAttributes:function createTransactionAttributes(b,c,d,e,f,g){return a.getInstance().eCommerce.createTransactionAttributes(b,c,d,e,f,g)},logCheckout:function logCheckout(b,c,d,e){a.getInstance().eCommerce.logCheckout(b,c,d,e);},logProductAction:function logProductAction(b,c,d,e,f,g){a.getInstance().eCommerce.logProductAction(b,c,d,e,f,g);},logPurchase:function logPurchase(b,c,d,e,f){a.getInstance().eCommerce.logPurchase(b,c,d,e,f);},logPromotion:function logPromotion(b,c,d,e,f){a.getInstance().eCommerce.logPromotion(b,c,d,e,f);},logImpression:function logImpression(b,c,d,e){a.getInstance().eCommerce.logImpression(b,c,d,e);},logRefund:function logRefund(b,c,d,e,f){a.getInstance().eCommerce.logRefund(b,c,d,e,f);},expandCommerceEvent:function expandCommerceEvent(b){return a.getInstance().eCommerce.expandCommerceEvent(b)}},this.setSessionAttribute=function(b,c){a.getInstance().setSessionAttribute(b,c);},this.setOptOut=function(b){a.getInstance().setOptOut(b);},this.setIntegrationAttribute=function(b,c){a.getInstance().setIntegrationAttribute(b,c);},this.getIntegrationAttributes=function(b){return a.getInstance().getIntegrationAttributes(b)},this.Identity={HTTPCodes:Constants.HTTPCodes,aliasUsers:function aliasUsers(b,c){a.getInstance().Identity.aliasUsers(b,c);},createAliasRequest:function createAliasRequest(b,c,d){return a.getInstance().Identity.createAliasRequest(b,c,d)},getCurrentUser:function getCurrentUser(){return a.getInstance().Identity.getCurrentUser()},getUser:function getUser(b){return a.getInstance().Identity.getUser(b)},getUsers:function getUsers(){return a.getInstance().Identity.getUsers()},identify:function identify(b,c){a.getInstance().Identity.identify(b,c);},login:function login(b,c){a.getInstance().Identity.login(b,c);},logout:function logout(b,c){a.getInstance().Identity.logout(b,c);},modify:function modify(b,c){a.getInstance().Identity.modify(b,c);},search:function search(b,c,d){a.getInstance().Identity.search(b,c,d);}},this.sessionManager={getSession:function getSession(){return a.getInstance()._SessionManager.getSessionId()}},this.Consent={createConsentState:function createConsentState(){return a.getInstance().Consent.createConsentState()},createGDPRConsent:function createGDPRConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)},createCCPAConsent:function createCCPAConsent(b,c,d,e,f){return a.getInstance().Consent.createGDPRConsent(b,c,d,e,f)}},this.reset=function(){a.getInstance().reset(a.getInstance());},this._resetForTests=function(b,c){"boolean"==typeof c?a.getInstance()._resetForTests(b,c,a.getInstance()):a.getInstance()._resetForTests(b,!1,a.getInstance());},this.configurePixel=function(b){a.getInstance().configurePixel(b);},this._setIntegrationDelay=function(b,c){a.getInstance()._setIntegrationDelay(b,c);},this._getIntegrationDelays=function(){return a.getInstance()._getIntegrationDelays()},this.getVersion=function(){return a.getInstance().getVersion()},this.generateHash=function(b){return a.getInstance().generateHash(b)},this.addForwarder=function(b){a.getInstance().addForwarder(b);},this._getActiveForwarders=function(){return a.getInstance()._getActiveForwarders()},this._setWrapperSDKInfo=function(b,c){a.getInstance()._setWrapperSDKInfo(b,c);},this._registerErrorReportingService=function(b){a.getInstance()._registerErrorReportingService(b);},this._registerLoggingService=function(b){a.getInstance()._registerLoggingService(b);};}var mParticleManager=new mParticleInstanceManager;"undefined"!=typeof window&&(window.mParticle=mParticleManager,window.mParticle._BatchValidator=new _BatchValidator);
export { mParticleManager as default };