"use strict"; var mParticle = (function() { var Base64$1 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", // Input must be a string encode: function encode(input) { try { if (window.btoa && window.atob) { return window.btoa(unescape(encodeURIComponent(input))); } } catch (e) { console.error("Error encoding cookie values into Base64:" + e); } return this._encode(input); }, _encode: function _encode(input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = UTF8.encode(input); while (i > 2; enc2 = (chr1 & 3) > 4; enc3 = (chr2 & 15) > 6; enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + Base64$1._keyStr.charAt(enc1) + Base64$1._keyStr.charAt(enc2) + Base64$1._keyStr.charAt(enc3) + Base64$1._keyStr.charAt(enc4); } return output; }, decode: function decode(input) { try { if (window.btoa && window.atob) { return decodeURIComponent(escape(window.atob(input))); } } catch (e) { } return Base64$1._decode(input); }, _decode: function _decode(input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i > 4; chr2 = (enc2 & 15) > 2; chr3 = (enc3 & 3) 127 && c > 6 | 192); utftext += String.fromCharCode(c & 63 | 128); } else { utftext += String.fromCharCode(c >> 12 | 224); utftext += String.fromCharCode(c >> 6 & 63 | 128); utftext += String.fromCharCode(c & 63 | 128); } } return utftext; }, decode: function decode(utftext) { var s = ""; var i = 0; var c = 0, c1 = 0, c2 = 0; while (i 191 && c >> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k >> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } A = new Array(len); k = 0; while (k >> 0; if (typeof fun !== "function") { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] = 0; } else { for (var n = items.length; i > a / 4).toString(16); } return (a ^ Math.random() * 16 >> a / 4).toString(16); }; var generateUniqueId = function generateUniqueId2(a) { if (a === void 0) { a = ""; } return a ? generateRandomValue() : ( // [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 generateUniqueId2 // random hex digits ) ); }; var getRampNumber = function getRampNumber2(value2) { if (!value2) { return 100; } var hash = generateHash(value2); return Math.abs(hash % 100) + 1; }; var isObject = function isObject2(value2) { var objType = Object.prototype.toString.call(value2); return objType === "[object Object]" || objType === "[object Error]"; }; var parseNumber = function parseNumber2(value2) { if (isNaN(value2) || !isFinite(value2)) { return 0; } var floatValue = parseFloat(value2); return isNaN(floatValue) ? 0 : floatValue; }; var parseSettingsString = function parseSettingsString2(settingsString) { try { return settingsString ? JSON.parse(settingsString.replace(/"/g, '"')) : []; } catch (error) { throw new Error("Settings string contains invalid JSON"); } }; var parseStringOrNumber = function parseStringOrNumber2(value2) { if (isStringOrNumber(value2)) { return value2; } else { return null; } }; var replaceCommasWithPipes = function replaceCommasWithPipes2(value2) { return value2.replace(/,/g, "|"); }; var replacePipesWithCommas = function replacePipesWithCommas2(value2) { return value2.replace(/\|/g, ","); }; var replaceApostrophesWithQuotes = function replaceApostrophesWithQuotes2(value2) { return value2.replace(/\'/g, '"'); }; var replaceQuotesWithApostrophes = function replaceQuotesWithApostrophes2(value2) { return value2.replace(/\"/g, "'"); }; var replaceMPID = function replaceMPID2(value2, mpid) { return value2.replace("%%mpid%%", mpid); }; var replaceAmpWithAmpersand = function replaceAmpWithAmpersand2(value2) { return value2.replace(/&/g, "&"); }; var createCookieSyncUrl = function createCookieSyncUrl2(mpid, pixelUrl, redirectUrl) { var modifiedPixelUrl = replaceAmpWithAmpersand(pixelUrl); var modifiedDirectUrl = redirectUrl ? replaceAmpWithAmpersand(redirectUrl) : null; var url = replaceMPID(modifiedPixelUrl, mpid); var redirect = modifiedDirectUrl ? replaceMPID(modifiedDirectUrl, mpid) : ""; return url + encodeURIComponent(redirect); }; var returnConvertedBoolean = function returnConvertedBoolean2(data) { if (data === "false" || data === "0") { return false; } else { return Boolean(data); } }; var decoded = function decoded2(s) { return decodeURIComponent(s.replace(/\+/g, " ")); }; var converted = function converted2(s) { if (s.indexOf('"') === 0) { s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\"); } return s; }; var isString = function isString2(value2) { return typeof value2 === "string"; }; var isNumber = function isNumber2(value2) { return typeof value2 === "number"; }; var isBoolean = function isBoolean2(value2) { return typeof value2 === "boolean"; }; var isFunction = function isFunction2(fn) { return typeof fn === "function"; }; var isValidAttributeValue = function isValidAttributeValue2(value2) { return value2 !== void 0 && !isObject(value2) && !Array.isArray(value2); }; var isValidCustomFlagProperty = function isValidCustomFlagProperty2(value2) { return isNumber(value2) || isString(value2) || isBoolean(value2); }; var toDataPlanSlug = function toDataPlanSlug2(value2) { return isStringOrNumber(value2) ? value2.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g, "_") : ""; }; var isDataPlanSlug = function isDataPlanSlug2(str) { return str === toDataPlanSlug(str); }; var isStringOrNumber = function isStringOrNumber2(value2) { return isString(value2) || isNumber(value2); }; var isEmpty = function isEmpty2(value2) { return value2 == null || !(Object.keys(value2) || value2).length; }; var moveElementToEnd = function moveElementToEnd2(array, index) { return array.slice(0, index).concat(array.slice(index + 1), array[index]); }; var queryStringParser = function queryStringParser2(url, keys) { if (keys === void 0) { keys = []; } var urlParams; var results = {}; var lowerCaseUrlParams = {}; if (!url) return results; if (typeof URL !== "undefined" && typeof URLSearchParams !== "undefined") { var urlObject = new URL(url); urlParams = new URLSearchParams(urlObject.search); } else { urlParams = queryStringParserFallback(url); } urlParams.forEach(function(value2, key) { lowerCaseUrlParams[key.toLowerCase()] = value2; }); if (isEmpty(keys)) { return lowerCaseUrlParams; } else { keys.forEach(function(key) { var value2 = lowerCaseUrlParams[key.toLowerCase()]; if (value2) { results[key] = value2; } }); } return results; }; var queryStringParserFallback = function queryStringParserFallback2(url) { var params = {}; var queryString = url.split("?")[1] || ""; var pairs = queryString.split("&"); pairs.forEach(function(pair) { var _a2 = pair.split("="), key = _a2[0], valueParts = _a2.slice(1); var value2 = valueParts.join("="); if (key && value2 !== void 0) { try { params[key] = decodeURIComponent(value2 || ""); } catch (e) { console.error("Failed to decode value for key ".concat(key, ": ").concat(e)); } } }); return { get: function get(key) { return params[key]; }, forEach: function forEach(callback) { for (var key in params) { if (params.hasOwnProperty(key)) { callback(params[key], key); } } } }; }; var getCookies = function getCookies2(keys) { var parseCookies = function parseCookies2() { try { if (typeof window === "undefined") { return []; } return window.document.cookie.split(";").map(function(cookie) { return cookie.trim(); }); } catch (e) { console.error("Unable to parse cookies", e); return []; } }; var filterCookies = function filterCookies2(cookies, keys2) { var results = {}; for (var _i = 0, cookies_1 = cookies; _i = BatchUploader2.MINIMUM_INTERVAL_MILLIS; if (this.uploadIntervalMillis = rampNumber; }; BatchUploader2.prototype.shouldDebounceAndUpdateLastASTTime = function() { var now = Date.now(); if (now - this.lastASTEventTime = 200 && response.status = 500 || response.status === 429) { logger.error("HTTP error status ".concat(response.status, " received")); return [2, uploads.slice(i, uploads.length)]; } else if (response.status >= 401) { logger.error("HTTP error status ".concat(response.status, " while uploading - please verify your API key.")); return [2, null]; } else { console.error("HTTP error status ".concat(response.status, " while uploading events."), response); throw new Error("Uncaught HTTP Error ".concat(response.status, ". Batch upload will be re-attempted.")); } return [3, 5]; case 4: e_1 = _a2.sent(); logger.error("Error sending event to mParticle servers. ".concat(e_1)); return [2, uploads.slice(i, uploads.length)]; case 5: i++; return [3, 1]; case 6: return [2, null]; } }); }); }; BatchUploader2.CONTENT_TYPE = "text/plain;charset=UTF-8"; BatchUploader2.MINIMUM_INTERVAL_MILLIS = 500; return BatchUploader2; })() ); function APIClient(mpInstance, kitBlocker) { this.uploader = null; var self = this; this.queueEventForBatchUpload = function(event) { if (!this.uploader) { var millis = parseNumber(mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis)); this.uploader = new BatchUploader(mpInstance, millis); } this.uploader.queueEvent(event); mpInstance._Persistence.update(); }; this.processQueuedEvents = function() { var mpid, currentUser = mpInstance.Identity.getCurrentUser(); if (currentUser) { mpid = currentUser.getMPID(); } if (mpInstance._Store.eventQueue.length && mpid) { var localQueueCopy = mpInstance._Store.eventQueue; mpInstance._Store.eventQueue = []; this.appendUserInfoToEvents(currentUser, localQueueCopy); localQueueCopy.forEach(function(event) { self.sendEventToServer(event); }); } }; this.appendUserInfoToEvents = function(user, events) { events.forEach(function(event) { if (!event.MPID) { appendUserInfo(user, event); } }); }; this.sendEventToServer = function(event, _options) { var defaultOptions = { shouldUploadEvent: true }; var options = mpInstance._Helpers.extend(defaultOptions, _options); if (mpInstance._Store.webviewBridgeEnabled) { mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.LogEvent, JSON.stringify(event)); return; } var mpid, currentUser = mpInstance.Identity.getCurrentUser(); if (currentUser) { mpid = currentUser.getMPID(); } mpInstance._Store.requireDelay = mpInstance._Helpers.isDelayedByIntegration(mpInstance._preInit.integrationDelays, mpInstance._Store.integrationDelayTimeoutStart, Date.now()); if (!mpid || mpInstance._Store.requireDelay || !mpInstance._Store.configurationLoaded) { mpInstance.Logger.verbose("Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay."); mpInstance._Store.eventQueue.push(event); return; } this.processQueuedEvents(); if (isEmpty(event)) { return; } if (options.shouldUploadEvent) { this.queueEventForBatchUpload(event); } if (event.EventName !== Types.MessageType.AppStateTransition) { if (kitBlocker && kitBlocker.kitBlockingEnabled) { event = kitBlocker.createBlockedEvent(event); } if (event) { mpInstance._Forwarders.sendEventToForwarders(event); } } }; this.sendBatchForwardingStatsToServer = function(forwardingStatsData, xhr) { var url; var data; try { url = mpInstance._Helpers.createServiceUrl(mpInstance._Store.SDKConfig.v2SecureServiceUrl, mpInstance._Store.devToken); data = { uuid: mpInstance._Helpers.generateUniqueId(), data: forwardingStatsData }; if (xhr) { xhr.open("post", url + "/Forwarding"); xhr.send(JSON.stringify(data)); } } catch (e) { mpInstance.Logger.error("Error sending forwarding stats to mParticle servers."); } }; this.initializeForwarderStatsUploader = function() { var forwardingDomain = mpInstance._Store.SDKConfig.v1SecureServiceUrl; var devToken = mpInstance._Store.devToken; var uploadUrl = "https://".concat(forwardingDomain).concat(devToken, "/Forwarding"); var uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl); return uploader; }; this.prepareForwardingStats = function(forwarder, event) { var forwardingStatsData; var queue = mpInstance._Forwarders.getForwarderStatsQueue(); if (forwarder && forwarder.isVisible) { forwardingStatsData = { mid: forwarder.id, esid: forwarder.eventSubscriptionId, n: event.EventName, attrs: event.EventAttributes, sdk: event.SDKVersion, dt: event.EventDataType, et: event.EventCategory, dbg: event.Debug, ct: event.Timestamp, eec: event.ExpandedEventCount, dp: event.DataPlan }; var _a2 = mpInstance._Forwarders, sendSingleForwardingStatsToServer = _a2.sendSingleForwardingStatsToServer, setForwarderStatsQueue = _a2.setForwarderStatsQueue; if (mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)) { queue.push(forwardingStatsData); setForwarderStatsQueue(queue); } else { sendSingleForwardingStatsToServer(forwardingStatsData); } } }; } var Modify$4 = Constants.IdentityMethods.Modify; var Validators = { // From ./utils // Utility Functions for backwards compatability isNumber, isFunction, isStringOrNumber, // Validator Functions isValidAttributeValue, // Validator Functions // Neither null nor undefined can be a valid Key isValidKeyValue: function isValidKeyValue(key) { return Boolean(key && !isObject(key) && !Array.isArray(key) && !this.isFunction(key)); }, removeFalsyIdentityValues: function removeFalsyIdentityValues(identityApiData, logger) { if (!identityApiData || !identityApiData.userIdentities) { return identityApiData; } var cleanedData = {}; var cleanedUserIdentities = __assign({}, identityApiData.userIdentities); for (var identityType in identityApiData.userIdentities) { if (identityApiData.userIdentities.hasOwnProperty(identityType)) { var value2 = identityApiData.userIdentities[identityType]; if (value2 !== null && !value2) { logger.warning("Identity value for '".concat(identityType, "' is falsy (").concat(value2, "). This value will be removed from the request.")); delete cleanedUserIdentities[identityType]; } } } cleanedData.userIdentities = cleanedUserIdentities; return cleanedData; }, validateIdentities: function validateIdentities(identityApiData, method) { var validIdentityRequestKeys = { userIdentities: 1, onUserAlias: 1, copyUserAttributes: 1 }; if (identityApiData) { if (method === Modify$4) { if (isObject(identityApiData.userIdentities) && !Object.keys(identityApiData.userIdentities).length || !isObject(identityApiData.userIdentities)) { return { valid: false, error: Constants.Messages.ValidationMessages.ModifyIdentityRequestUserIdentitiesPresent }; } } for (var key in identityApiData) { if (identityApiData.hasOwnProperty(key)) { if (!validIdentityRequestKeys[key]) { return { valid: false, error: Constants.Messages.ValidationMessages.IdentityRequesetInvalidKey }; } if (key === "onUserAlias" && !Validators.isFunction(identityApiData[key])) { return { valid: false, error: Constants.Messages.ValidationMessages.OnUserAliasType }; } } } if (Object.keys(identityApiData).length === 0) { return { valid: true }; } else { if (identityApiData.userIdentities === void 0) { return { valid: false, error: Constants.Messages.ValidationMessages.UserIdentities }; } else if (identityApiData.userIdentities !== null && !isObject(identityApiData.userIdentities)) { return { valid: false, error: Constants.Messages.ValidationMessages.UserIdentities }; } if (isObject(identityApiData.userIdentities) && Object.keys(identityApiData.userIdentities).length) { for (var identityType in identityApiData.userIdentities) { if (identityApiData.userIdentities.hasOwnProperty(identityType)) { if (Types.IdentityType.getIdentityType(identityType) === false) { return { valid: false, error: Constants.Messages.ValidationMessages.UserIdentitiesInvalidKey }; } if (!(typeof identityApiData.userIdentities[identityType] === "string" || identityApiData.userIdentities[identityType] === null)) { return { valid: false, error: Constants.Messages.ValidationMessages.UserIdentitiesInvalidValues }; } } } } } } return { valid: true }; } }; var KitFilterHelper = ( /** @class */ (function() { function KitFilterHelper2() { } KitFilterHelper2.hashEventType = function(eventType) { return generateHash(eventType); }; KitFilterHelper2.hashEventName = function(eventName, eventType) { return generateHash(eventType + eventName); }; KitFilterHelper2.hashEventAttributeKey = function(eventType, eventName, customAttributeName) { return generateHash(eventType + eventName + customAttributeName); }; KitFilterHelper2.hashUserAttribute = function(userAttributeKey) { return generateHash(userAttributeKey); }; KitFilterHelper2.hashUserIdentity = function(userIdentity) { return userIdentity; }; KitFilterHelper2.hashConsentPurpose = function(prefix, purpose) { return generateHash(prefix + purpose); }; KitFilterHelper2.hashAttributeConditionalForwarding = function(attribute) { return generateHash(attribute).toString(); }; KitFilterHelper2.hashConsentPurposeConditionalForwarding = function(prefix, purpose) { return this.hashConsentPurpose(prefix, purpose).toString(); }; var _a2; _a2 = KitFilterHelper2; KitFilterHelper2.filterUserAttributes = function(userAttributes, filterList) { return filterDictionaryWithHash(userAttributes, filterList, function(key) { return _a2.hashUserAttribute(key); }); }; KitFilterHelper2.filterUserIdentities = function(userIdentities, filterList) { return filterDictionaryWithHash(userIdentities, filterList, function(key) { return _a2.hashUserIdentity(IdentityType.getIdentityType(key)); }); }; KitFilterHelper2.isFilteredUserAttribute = function(userAttributeKey, filterList) { var hashedUserAttribute = _a2.hashUserAttribute(userAttributeKey); return filterList && inArray(filterList, hashedUserAttribute); }; return KitFilterHelper2; })() ); var StorageNames$1 = Constants.StorageNames; function Helpers(mpInstance) { var self = this; this.canLog = function() { if (mpInstance._Store.isEnabled && (mpInstance._Store.devToken || mpInstance._Store.webviewBridgeEnabled)) { return true; } return false; }; this.getFeatureFlag = function(feature) { if (mpInstance._Store.SDKConfig.flags.hasOwnProperty(feature)) { return mpInstance._Store.SDKConfig.flags[feature]; } return null; }; this.invokeCallback = function(callback, code, body, mParticleUser, previousMpid) { if (!callback) { mpInstance.Logger.warning("There is no callback provided"); } try { if (self.Validators.isFunction(callback)) { callback({ httpCode: code, body, getUser: function getUser() { if (mParticleUser) { return mParticleUser; } else { return mpInstance.Identity.getCurrentUser(); } }, getPreviousUser: function getPreviousUser() { if (!previousMpid) { var users = mpInstance.Identity.getUsers(); var mostRecentUser = users.shift(); var currentUser = mParticleUser || mpInstance.Identity.getCurrentUser(); if (mostRecentUser && currentUser && mostRecentUser.getMPID() === currentUser.getMPID()) { mostRecentUser = users.shift(); } return mostRecentUser || null; } else { return mpInstance.Identity.getUser(previousMpid); } } }); } } catch (e) { mpInstance.Logger.error("There was an error with your callback: " + e); } }; this.invokeAliasCallback = function(callback, code, message) { if (!callback) { mpInstance.Logger.warning("There is no callback provided"); } try { if (self.Validators.isFunction(callback)) { var callbackMessage = { httpCode: code }; if (message) { callbackMessage.message = message; } callback(callbackMessage); } } catch (e) { mpInstance.Logger.error("There was an error with your callback: " + e); } }; this.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, objectHelper = { hasOwn: Object.prototype.hasOwnProperty, class2type: {}, type: function type(obj) { return obj == null ? String(obj) : objectHelper.class2type[Object.prototype.toString.call(obj)] || "object"; }, isPlainObject: function isPlainObject(obj) { if (!obj || objectHelper.type(obj) !== "object" || obj.nodeType || objectHelper.isWindow(obj)) { return false; } try { if (obj.constructor && !objectHelper.hasOwn.call(obj, "constructor") && !objectHelper.hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) { return false; } } catch (e) { return false; } var key; for (key in obj) { } return key === void 0 || objectHelper.hasOwn.call(obj, key); }, isArray: Array.isArray || function(obj) { return objectHelper.type(obj) === "array"; }, isFunction: function isFunction2(obj) { return objectHelper.type(obj) === "function"; }, isWindow: function isWindow(obj) { return obj != null && obj == obj.window; } }; if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; i = 2; } if (_typeof$1(target) !== "object" && !objectHelper.isFunction(target)) { target = {}; } if (length === i) { target = this; --i; } for (; i mpInstance._Store.SDKConfig.integrationDelayTimeout) { return false; } for (var integration in delayedIntegrations) { if (delayedIntegrations[integration] === true) { return true; } else { continue; } } return false; }; this.createMainStorageName = function(workspaceToken) { if (workspaceToken) { return StorageNames$1.currentStorageName + "_" + workspaceToken; } else { return 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; var androidBridgeNameBase = "mParticleAndroid"; var iosBridgeNameBase = "mParticle"; function NativeSdkHelpers(mpInstance) { var self = this; this.initializeSessionAttributes = function(apiKey) { var SetSessionAttribute = Constants.NativeSdkPaths.SetSessionAttribute; var env = JSON.stringify({ key: "$src_env", value: "webview" }); var key = JSON.stringify({ key: "$src_key", value: apiKey }); self.sendToNative(SetSessionAttribute, env); if (apiKey) { self.sendToNative(SetSessionAttribute, key); } }; this.isBridgeV2Available = function(bridgeName) { if (!bridgeName) { return false; } var androidBridgeName = androidBridgeNameBase + "_" + bridgeName + "_v2"; var iosBridgeName = iosBridgeNameBase + "_" + bridgeName + "_v2"; if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.hasOwnProperty(iosBridgeName)) { return true; } if (window.mParticle && window.mParticle.uiwebviewBridgeName && window.mParticle.uiwebviewBridgeName === iosBridgeName) { return true; } if (window.hasOwnProperty(androidBridgeName)) { return true; } return false; }; this.isWebviewEnabled = function(requiredWebviewBridgeName, minWebviewBridgeVersion) { mpInstance._Store.bridgeV2Available = self.isBridgeV2Available(requiredWebviewBridgeName); mpInstance._Store.bridgeV1Available = self.isBridgeV1Available(); if (minWebviewBridgeVersion === 2) { return mpInstance._Store.bridgeV2Available; } if (window.mParticle) { if (window.mParticle.uiwebviewBridgeName && window.mParticle.uiwebviewBridgeName !== iosBridgeNameBase + "_" + requiredWebviewBridgeName + "_v2") { return false; } } if (minWebviewBridgeVersion new Date(lastSyncDate).getTime() + frequencyCap * DAYS_IN_MILLISECONDS; }; var _a = Constants.IdentityMethods, Identify$2 = _a.Identify, Modify$3 = _a.Modify, Login$2 = _a.Login, Logout$2 = _a.Logout; var CACHE_HEADER = "x-mp-max-age"; var cacheOrClearIdCache = function cacheOrClearIdCache2(method, knownIdentities, idCache, identityResponse, parsingCachedResponse) { if (parsingCachedResponse) { return; } var expireTimestamp = getExpireTimestamp(identityResponse === null || identityResponse === void 0 ? void 0 : identityResponse.cacheMaxAge); switch (method) { case Login$2: case Identify$2: cacheIdentityRequest(method, knownIdentities, expireTimestamp, idCache, identityResponse); break; case Modify$3: case Logout$2: idCache.purge(); break; } }; var cacheIdentityRequest = function cacheIdentityRequest2(method, identities, expireTimestamp, idCache, identityResponse) { var responseText = identityResponse.responseText, status = identityResponse.status; var cache = idCache.retrieve() || {}; var cacheKey = concatenateIdentities(method, identities); var hashedKey = generateHash(cacheKey); var mpid = responseText.mpid, is_logged_in = responseText.is_logged_in; var cachedResponseBody = { mpid, is_logged_in }; cache[hashedKey] = { responseText: JSON.stringify(cachedResponseBody), status, expireTimestamp }; idCache.store(cache); }; var concatenateIdentities = function concatenateIdentities2(method, userIdentities) { var DEVICE_APPLICATION_STAMP = "device_application_stamp"; var cacheKey = "".concat(method, ":").concat(DEVICE_APPLICATION_STAMP, "=").concat(userIdentities.device_application_stamp, ";"); var idLength = Object.keys(userIdentities).length; var concatenatedIdentities = ""; if (idLength) { var userIDArray = new Array(); for (var key in userIdentities) { if (key === DEVICE_APPLICATION_STAMP) { continue; } else { userIDArray[Types.IdentityType.getIdentityType(key)] = userIdentities[key]; } } concatenatedIdentities = userIDArray.reduce(function(prevValue, currentValue, index) { var idName = Types.IdentityType.getIdentityName(index); return "".concat(prevValue).concat(idName, "=").concat(currentValue, ";"); }, cacheKey); } return concatenatedIdentities; }; var hasValidCachedIdentity = function hasValidCachedIdentity2(method, proposedUserIdentities, idCache) { var cache = idCache === null || idCache === void 0 ? void 0 : idCache.retrieve(); if (!cache) { return false; } var cacheKey = concatenateIdentities(method, proposedUserIdentities); var hashedKey = generateHash(cacheKey); if (!cache.hasOwnProperty(hashedKey)) { return false; } var expireTimestamp = cache[hashedKey].expireTimestamp; if (expireTimestamp new Date(mpInstance._Store.dateLastEventSent.getTime() + sessionTimeoutInMilliseconds)) { self.endSession(); self.startNewSession(); } else { var currentUser = mpInstance.Identity.getCurrentUser(); var sdkIdentityRequest = mpInstance._Store.SDKConfig.identifyRequest; if (hasIdentityRequestChanged(currentUser, sdkIdentityRequest)) { mpInstance.Identity.identify(mpInstance._Store.SDKConfig.identifyRequest, mpInstance._Store.SDKConfig.identityCallback); mpInstance._Store.identifyCalled = true; mpInstance._Store.SDKConfig.identityCallback = null; } } } else { self.startNewSession(); } }; this.getSession = function() { mpInstance.Logger.warning(generateDeprecationMessage("SessionManager.getSession()", false, "SessionManager.getSessionId()")); return this.getSessionId(); }; this.getSessionId = function() { return mpInstance._Store.sessionId; }; this.startNewSession = function() { mpInstance.Logger.verbose(Messages$6.InformationMessages.StartingNewSession); if (mpInstance._Helpers.canLog()) { mpInstance._Store.sessionId = mpInstance._Helpers.generateUniqueId().toUpperCase(); var currentUser = mpInstance.Identity.getCurrentUser(); var mpid = currentUser ? currentUser.getMPID() : null; if (mpid) { mpInstance._Store.currentSessionMPIDs = [mpid]; } if (!mpInstance._Store.sessionStartDate) { var date = /* @__PURE__ */ new Date(); mpInstance._Store.sessionStartDate = date; mpInstance._Store.dateLastEventSent = date; } self.setSessionTimer(); if (!mpInstance._Store.identifyCalled) { mpInstance.Identity.identify(mpInstance._Store.SDKConfig.identifyRequest, mpInstance._Store.SDKConfig.identityCallback); mpInstance._Store.identifyCalled = true; mpInstance._Store.SDKConfig.identityCallback = null; } mpInstance._Events.logEvent({ messageType: Types.MessageType.SessionStart }); } else { mpInstance.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession); } }; this.endSession = function(override) { var _a2, _b, _c, _d, _e; mpInstance.Logger.verbose(Messages$6.InformationMessages.StartingEndSession); if (override) { mpInstance._Events.logEvent({ messageType: Types.MessageType.SessionEnd }); mpInstance._Store.nullifySession(); (_a2 = mpInstance._timeOnSiteTimer) === null || _a2 === void 0 ? void 0 : _a2.resetTimer(); return; } if (!mpInstance._Helpers.canLog()) { mpInstance.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession); (_b = mpInstance._timeOnSiteTimer) === null || _b === void 0 ? void 0 : _b.resetTimer(); return; } var sessionTimeoutInMilliseconds; var timeSinceLastEventSent; var cookies = mpInstance._Persistence.getPersistence(); if (!cookies || cookies.gs && !cookies.gs.sid) { mpInstance.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd); (_c = mpInstance._timeOnSiteTimer) === null || _c === void 0 ? void 0 : _c.resetTimer(); return; } if (cookies.gs.sid && mpInstance._Store.sessionId !== cookies.gs.sid) { mpInstance._Store.sessionId = cookies.gs.sid; } if ((_d = cookies === null || cookies === void 0 ? void 0 : cookies.gs) === null || _d === void 0 ? void 0 : _d.les) { sessionTimeoutInMilliseconds = mpInstance._Store.SDKConfig.sessionTimeout * 6e4; var newDate = (/* @__PURE__ */ new Date()).getTime(); timeSinceLastEventSent = newDate - cookies.gs.les; if (timeSinceLastEventSent = 0) { _this.currentSessionMPIDs = moveElementToEnd(_this.currentSessionMPIDs, indexOfMPID); } }; this.nullifySession = function() { _this.sessionId = null; _this.dateLastEventSent = null; _this.sessionAttributes = {}; _this.localSessionAttributes = {}; mpInstance._Persistence.update(); }; this.processConfig = function(config2) { var _a2; var workspaceToken = config2.workspaceToken, requiredWebviewBridgeName = config2.requiredWebviewBridgeName; _this.SDKConfig.flags = processFlags(config2); var baseUrls2 = processBaseUrls(config2, _this.SDKConfig.flags, apiKey); for (var baseUrlKeys2 in baseUrls2) { _this.SDKConfig[baseUrlKeys2] = baseUrls2[baseUrlKeys2]; } var _b = (_a2 = config2 === null || config2 === void 0 ? void 0 : config2.launcherOptions) !== null && _a2 !== void 0 ? _a2 : {}, noFunctional = _b.noFunctional, noTargeting = _b.noTargeting; if (noFunctional != null) { _this.setNoFunctional(noFunctional); } if (noTargeting != null) { _this.setNoTargeting(noTargeting); } if (workspaceToken) { _this.SDKConfig.workspaceToken = workspaceToken; if (!_this.getPrivacyFlag("TimeOnSite")) { mpInstance._timeOnSiteTimer = new ForegroundTimeTracker(workspaceToken); } } else { mpInstance.Logger.warning("You should have a workspaceToken on your config object for security purposes."); } _this.storageName = createMainStorageName(workspaceToken); _this.SDKConfig.requiredWebviewBridgeName = requiredWebviewBridgeName || workspaceToken; _this.webviewBridgeEnabled = isWebviewEnabled(_this.SDKConfig.requiredWebviewBridgeName, _this.SDKConfig.minWebviewBridgeVersion); _this.configurationLoaded = true; }; } function processFlags(config) { var flags = {}; var _a2 = Constants.FeatureFlags, ReportBatching2 = _a2.ReportBatching, EventBatchingIntervalMillis = _a2.EventBatchingIntervalMillis, OfflineStorage = _a2.OfflineStorage, DirectUrlRouting = _a2.DirectUrlRouting, CacheIdentity2 = _a2.CacheIdentity, AudienceAPI = _a2.AudienceAPI, CaptureIntegrationSpecificIds2 = _a2.CaptureIntegrationSpecificIds, CaptureIntegrationSpecificIdsV22 = _a2.CaptureIntegrationSpecificIdsV2, AstBackgroundEvents = _a2.AstBackgroundEvents; if (!config.flags) { return {}; } flags[ReportBatching2] = config.flags[ReportBatching2] || false; flags[EventBatchingIntervalMillis] = parseNumber(config.flags[EventBatchingIntervalMillis]) || Constants.DefaultConfig.uploadInterval; flags[OfflineStorage] = config.flags[OfflineStorage] || "0"; flags[DirectUrlRouting] = config.flags[DirectUrlRouting] === "True"; flags[CacheIdentity2] = config.flags[CacheIdentity2] === "True"; flags[AudienceAPI] = config.flags[AudienceAPI] === "True"; flags[CaptureIntegrationSpecificIds2] = config.flags[CaptureIntegrationSpecificIds2] === "True"; flags[CaptureIntegrationSpecificIdsV22] = config.flags[CaptureIntegrationSpecificIdsV22] || "none"; flags[AstBackgroundEvents] = config.flags[AstBackgroundEvents] === "True"; return flags; } function processBaseUrls(config, flags, apiKey) { if (!apiKey) { return {}; } if (flags.directURLRouting) { return processDirectBaseUrls(config, apiKey); } else { return processCustomBaseUrls(config); } } function processCustomBaseUrls(config) { var defaultBaseUrls = Constants.DefaultBaseUrls; var CNAMEUrlPaths = Constants.CNAMEUrlPaths; var newBaseUrls = {}; if (!isEmpty(config.domain)) { for (var pathKey in CNAMEUrlPaths) { newBaseUrls[pathKey] = "".concat(config.domain).concat(CNAMEUrlPaths[pathKey]); } return newBaseUrls; } for (var baseUrlKey in defaultBaseUrls) { newBaseUrls[baseUrlKey] = config[baseUrlKey] || defaultBaseUrls[baseUrlKey]; } return newBaseUrls; } function processDirectBaseUrls(config, apiKey) { var defaultBaseUrls = Constants.DefaultBaseUrls; var directBaseUrls = {}; var DEFAULT_SILO = "us1"; var splitKey = apiKey.split("-"); var routingPrefix = splitKey.length maxCookieSize) { if (!SDKv2NonMPIDCookieKeys[key] && key !== persistence.cu) { delete persistence[key]; } } } } } else { var MPIDsOnCookie = {}; for (var potentialMPID in persistence) { if (persistence.hasOwnProperty(potentialMPID)) { if (!SDKv2NonMPIDCookieKeys[potentialMPID] && potentialMPID !== persistence.cu) { MPIDsOnCookie[potentialMPID] = 1; } } } if (Object.keys(MPIDsOnCookie).length) { for (var mpid in MPIDsOnCookie) { encodedCookiesWithExpirationAndPath = createFullEncodedCookie(persistence, expires, domain); if (encodedCookiesWithExpirationAndPath.length > maxCookieSize) { if (MPIDsOnCookie.hasOwnProperty(mpid)) { if (currentSessionMPIDs.indexOf(mpid) === -1) { delete persistence[mpid]; } } } } } for (var i = 0; i maxCookieSize) { var MPIDtoRemove = currentSessionMPIDs[i]; if (persistence[MPIDtoRemove]) { mpInstance.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of " + maxCookieSize + ". Removing from cookie the earliest logged in MPID containing: " + JSON.stringify(persistence[MPIDtoRemove], 0, 2)); delete persistence[MPIDtoRemove]; } else { mpInstance.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of " + maxCookieSize + ". We recommend using a maxCookieSize of 1500."); } } else { break; } } } return encodedCookiesWithExpirationAndPath; }; function createFullEncodedCookie(persistence, expires, domain) { return self.encodePersistence(JSON.stringify(persistence)) + ";expires=" + expires + ";path=/" + domain; } this.findPrevCookiesBasedOnUI = function(identityApiData) { var persistence = mpInstance._Persistence.getPersistence(); var matchedUser; if (identityApiData) { for (var requestedIdentityType in identityApiData.userIdentities) { if (persistence && Object.keys(persistence).length) { for (var key in persistence) { if (persistence[key].mpid) { var cookieUIs = persistence[key].ui; for (var cookieUIType in cookieUIs) { if (requestedIdentityType === cookieUIType && identityApiData.userIdentities[requestedIdentityType] === cookieUIs[cookieUIType]) { matchedUser = key; break; } } } } } } } if (matchedUser) { self.storeDataInMemory(persistence, matchedUser); } }; this.encodePersistence = function(persistence) { persistence = JSON.parse(persistence); for (var key in persistence.gs) { if (persistence.gs.hasOwnProperty(key)) { if (Base64CookieKeys[key]) { if (persistence.gs[key]) { if (Array.isArray(persistence.gs[key]) && persistence.gs[key].length || mpInstance._Helpers.isObject(persistence.gs[key]) && Object.keys(persistence.gs[key]).length) { persistence.gs[key] = Base64.encode(JSON.stringify(persistence.gs[key])); } else { delete persistence.gs[key]; } } else { delete persistence.gs[key]; } } else if (key === "ie") { persistence.gs[key] = persistence.gs[key] ? 1 : 0; } else if (!persistence.gs[key]) { delete persistence.gs[key]; } } } for (var mpid in persistence) { if (persistence.hasOwnProperty(mpid)) { if (!SDKv2NonMPIDCookieKeys[mpid]) { for (key in persistence[mpid]) { if (persistence[mpid].hasOwnProperty(key)) { if (Base64CookieKeys[key]) { if (mpInstance._Helpers.isObject(persistence[mpid][key]) && Object.keys(persistence[mpid][key]).length) { persistence[mpid][key] = Base64.encode(JSON.stringify(persistence[mpid][key])); } else { delete persistence[mpid][key]; } } } } } } } return createCookieString(JSON.stringify(persistence)); }; this.decodePersistence = function(persistence) { try { if (persistence) { persistence = JSON.parse(revertCookieString(persistence)); if (mpInstance._Helpers.isObject(persistence) && Object.keys(persistence).length) { for (var key in persistence.gs) { if (persistence.gs.hasOwnProperty(key)) { if (Base64CookieKeys[key]) { persistence.gs[key] = JSON.parse(Base64.decode(persistence.gs[key])); } else if (key === "ie") { persistence.gs[key] = Boolean(persistence.gs[key]); } } } for (var mpid in persistence) { if (persistence.hasOwnProperty(mpid)) { if (!SDKv2NonMPIDCookieKeys[mpid]) { for (key in persistence[mpid]) { if (persistence[mpid].hasOwnProperty(key)) { if (Base64CookieKeys[key]) { if (persistence[mpid][key].length) { persistence[mpid][key] = JSON.parse(Base64.decode(persistence[mpid][key])); } } } } } else if (mpid === "l") { persistence[mpid] = Boolean(persistence[mpid]); } } } } return JSON.stringify(persistence); } } catch (e) { mpInstance.Logger.error("Problem with decoding cookie", e); } }; this.getCookieDomain = function() { if (mpInstance._Store.SDKConfig.cookieDomain) { return mpInstance._Store.SDKConfig.cookieDomain; } else { var rootDomain = self.getDomain(document, location.hostname); if (rootDomain === "") { return ""; } else { return "." + rootDomain; } } }; this.getDomain = function(doc, locationHostname) { var i, testParts, mpTest = "mptest=cookie", hostname = locationHostname.split("."); for (i = hostname.length - 1; i >= 0; i--) { testParts = hostname.slice(i).join("."); doc.cookie = mpTest + ";domain=." + testParts + ";"; if (doc.cookie.indexOf(mpTest) > -1) { doc.cookie = mpTest.split("=")[0] + "=;domain=." + testParts + ";expires=Thu, 01 Jan 1970 00:00:01 GMT;"; return testParts; } } return ""; }; this.saveUserCookieSyncDatesToPersistence = function(mpid, csd) { if (csd) { var persistence = self.getPersistence(); if (persistence) { if (persistence[mpid]) { persistence[mpid].csd = csd; } else { persistence[mpid] = { csd }; } } self.savePersistence(persistence); } }; this.swapCurrentUser = function(previousMPID, currentMPID, currentSessionMPIDs) { if (previousMPID && currentMPID && previousMPID !== currentMPID) { var persistence = self.getPersistence(); if (persistence) { persistence.cu = currentMPID; persistence.gs.csm = currentSessionMPIDs; self.savePersistence(persistence); } } }; this.savePersistence = function(persistence) { if (mpInstance._Store.getPrivacyFlag("SDKState")) { return; } var encodedPersistence = self.encodePersistence(JSON.stringify(persistence)), date = /* @__PURE__ */ new Date(), key = mpInstance._Store.storageName, expires = new Date(date.getTime() + mpInstance._Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1e3).toGMTString(), cookieDomain = self.getCookieDomain(), domain; if (cookieDomain === "") { domain = ""; } else { domain = ";domain=" + cookieDomain; } if (mpInstance._Store.SDKConfig.useCookieStorage) { var encodedCookiesWithExpirationAndPath = self.reduceAndEncodePersistence(persistence, expires, domain, mpInstance._Store.SDKConfig.maxCookieSize); window.document.cookie = encodeURIComponent(key) + "=" + encodedCookiesWithExpirationAndPath; } else { if (mpInstance._Store.isLocalStorageAvailable) { localStorage.setItem(mpInstance._Store.storageName, encodedPersistence); } } }; this.getPersistence = function() { if (mpInstance._Store.getPrivacyFlag("SDKState")) { return null; } var persistence = this.useLocalStorage() ? this.getLocalStorage() : this.getCookie(); return persistence; }; this.getFirstSeenTime = function(mpid) { if (!mpid) { return null; } var persistence = self.getPersistence(); if (persistence && persistence[mpid] && persistence[mpid].fst) { return persistence[mpid].fst; } else { return null; } }; this.setFirstSeenTime = function(mpid, time) { if (!mpid) { return; } if (!time) { time = (/* @__PURE__ */ new Date()).getTime(); } var persistence = self.getPersistence(); if (persistence) { if (!persistence[mpid]) { persistence[mpid] = {}; } if (!persistence[mpid].fst) { persistence[mpid].fst = time; self.savePersistence(persistence); } } }; this.getLastSeenTime = function(mpid) { if (!mpid) { return null; } if (mpid === mpInstance.Identity.getCurrentUser().getMPID()) { return (/* @__PURE__ */ new Date()).getTime(); } else { var persistence = self.getPersistence(); if (persistence && persistence[mpid] && persistence[mpid].lst) { return persistence[mpid].lst; } return null; } }; this.setLastSeenTime = function(mpid, time) { if (!mpid) { return; } if (!time) { time = (/* @__PURE__ */ new Date()).getTime(); } var persistence = self.getPersistence(); if (persistence && persistence[mpid]) { persistence[mpid].lst = time; self.savePersistence(persistence); } }; this.getDeviceId = function() { return mpInstance._Store.deviceId; }; this.setDeviceId = function(guid) { mpInstance._Store.deviceId = guid; self.update(); }; this.resetPersistence = function() { removeLocalStorage(StorageNames.localStorageName); removeLocalStorage(StorageNames.localStorageNameV3); removeLocalStorage(StorageNames.localStorageNameV4); removeLocalStorage(mpInstance._Store.storageName); removeLocalStorage(StorageNames.localStorageProductsV4); self.expireCookies(StorageNames.cookieName); self.expireCookies(StorageNames.cookieNameV2); self.expireCookies(StorageNames.cookieNameV3); self.expireCookies(StorageNames.cookieNameV4); self.expireCookies(mpInstance._Store.storageName); if (mParticle._isTestEnv) { var testWorkspaceToken = "abcdef"; removeLocalStorage(mpInstance._Helpers.createMainStorageName(testWorkspaceToken)); self.expireCookies(mpInstance._Helpers.createMainStorageName(testWorkspaceToken)); } }; this.forwardingStatsBatches = { uploadsTable: {}, forwardingStatsEventQueue: [] }; } var Messages$3 = Constants.Messages; function Events(mpInstance) { var self = this; this.logEvent = function(event, options) { mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogEvent + ": " + event.name); if (mpInstance._Helpers.canLog()) { var uploadObject = mpInstance._ServerModel.createEventObject(event); mpInstance._APIClient.sendEventToServer(uploadObject, options); } else { mpInstance.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent); } }; this.startTracking = function(callback) { if (!mpInstance._Store.isTracking) { if ("geolocation" in navigator) { mpInstance._Store.watchPositionId = navigator.geolocation.watchPosition(successTracking, errorTracking); } } else { var position = { coords: { latitude: mpInstance._Store.currentPosition.lat, longitude: mpInstance._Store.currentPosition.lng } }; triggerCallback(callback, position); } function successTracking(position2) { mpInstance._Store.currentPosition = { lat: position2.coords.latitude, lng: position2.coords.longitude }; triggerCallback(callback, position2); callback = null; mpInstance._Store.isTracking = true; } function errorTracking() { triggerCallback(callback); callback = null; mpInstance._Store.isTracking = false; } function triggerCallback(callback2, position2) { if (callback2) { try { if (position2) { callback2(position2); } else { callback2(); } } catch (e) { mpInstance.Logger.error("Error invoking the callback passed to startTrackingLocation."); mpInstance.Logger.error(e); } } } }; this.stopTracking = function() { if (mpInstance._Store.isTracking) { navigator.geolocation.clearWatch(mpInstance._Store.watchPositionId); mpInstance._Store.currentPosition = null; mpInstance._Store.isTracking = false; } }; this.logOptOut = function() { mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogOptOut); var event = mpInstance._ServerModel.createEventObject({ messageType: Types.MessageType.OptOut, eventType: Types.EventType.Other }); mpInstance._APIClient.sendEventToServer(event); }; this.logAST = function() { self.logEvent({ messageType: Types.MessageType.AppStateTransition }); }; this.logCheckoutEvent = function(step, option, attrs, customFlags) { var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); if (event) { event.EventName += mpInstance._Ecommerce.getProductActionEventName(Types.ProductActionType.Checkout); event.EventCategory = Types.CommerceEventType.ProductCheckout; event.ProductAction = { ProductActionType: Types.ProductActionType.Checkout, CheckoutStep: step, CheckoutOptions: option, ProductList: [] }; self.logCommerceEvent(event, attrs); } }; this.logProductActionEvent = function(productActionType, product, customAttrs, customFlags, transactionAttributes, options) { var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags, options); var productList = Array.isArray(product) ? product : [product]; productList.forEach(function(product2) { if (product2.TotalAmount) { product2.TotalAmount = mpInstance._Ecommerce.sanitizeAmount(product2.TotalAmount, "TotalAmount"); } if (product2.Position) { product2.Position = mpInstance._Ecommerce.sanitizeAmount(product2.Position, "Position"); } if (product2.Price) { product2.Price = mpInstance._Ecommerce.sanitizeAmount(product2.Price, "Price"); } if (product2.Quantity) { product2.Quantity = mpInstance._Ecommerce.sanitizeAmount(product2.Quantity, "Quantity"); } }); if (event) { event.EventCategory = mpInstance._Ecommerce.convertProductActionToEventType(productActionType); event.EventName += mpInstance._Ecommerce.getProductActionEventName(productActionType); event.ProductAction = { ProductActionType: productActionType, ProductList: productList }; if (mpInstance._Helpers.isObject(transactionAttributes)) { mpInstance._Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction); } self.logCommerceEvent(event, customAttrs, options); } }; this.logPurchaseEvent = function(transactionAttributes, product, attrs, customFlags) { var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); if (event) { event.EventName += mpInstance._Ecommerce.getProductActionEventName(Types.ProductActionType.Purchase); event.EventCategory = Types.CommerceEventType.ProductPurchase; event.ProductAction = { ProductActionType: Types.ProductActionType.Purchase }; event.ProductAction.ProductList = mpInstance._Ecommerce.buildProductList(event, product); mpInstance._Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction); self.logCommerceEvent(event, attrs); } }; this.logRefundEvent = function(transactionAttributes, product, attrs, customFlags) { if (!transactionAttributes) { mpInstance.Logger.error(Messages$3.ErrorMessages.TransactionRequired); return; } var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); if (event) { event.EventName += mpInstance._Ecommerce.getProductActionEventName(Types.ProductActionType.Refund); event.EventCategory = Types.CommerceEventType.ProductRefund; event.ProductAction = { ProductActionType: Types.ProductActionType.Refund }; event.ProductAction.ProductList = mpInstance._Ecommerce.buildProductList(event, product); mpInstance._Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction); self.logCommerceEvent(event, attrs); } }; this.logPromotionEvent = function(promotionType, promotion, attrs, customFlags, eventOptions) { var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); if (event) { event.EventName += mpInstance._Ecommerce.getPromotionActionEventName(promotionType); event.EventCategory = mpInstance._Ecommerce.convertPromotionActionToEventType(promotionType); event.PromotionAction = { PromotionActionType: promotionType, PromotionList: Array.isArray(promotion) ? promotion : [promotion] }; self.logCommerceEvent(event, attrs, eventOptions); } }; this.logImpressionEvent = function(impression, attrs, customFlags, options) { var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags); if (event) { event.EventName += "Impression"; event.EventCategory = Types.CommerceEventType.ProductImpression; if (!Array.isArray(impression)) { impression = [impression]; } event.ProductImpressions = []; impression.forEach(function(impression2) { event.ProductImpressions.push({ ProductImpressionList: impression2.Name, ProductList: Array.isArray(impression2.Product) ? impression2.Product : [impression2.Product] }); }); self.logCommerceEvent(event, attrs, options); } }; this.logCommerceEvent = function(commerceEvent, attrs, options) { mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogCommerceEvent); if (commerceEvent.ProductAction && commerceEvent.EventCategory === null) { mpInstance.Logger.error("Commerce event not sent. The mParticle.ProductActionType you passed was invalid. Re-check your code."); return; } attrs = mpInstance._Helpers.sanitizeAttributes(attrs, commerceEvent.EventName); if (mpInstance._Helpers.canLog()) { if (mpInstance._Store.webviewBridgeEnabled) { commerceEvent.ShoppingCart = {}; } if (attrs) { commerceEvent.EventAttributes = attrs; } mpInstance._APIClient.sendEventToServer(commerceEvent, options); mpInstance._Persistence.update(); } else { mpInstance.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent); } }; this.addEventHandler = function(domEvent, selector, eventName, data, eventType) { var elements = [], handler = function handler2(e) { var timeoutHandler = function timeoutHandler2() { if (element.href) { window.location.href = element.href; } else if (element.submit) { element.submit(); } }; mpInstance.Logger.verbose("DOM event triggered, handling event"); self.logEvent({ messageType: Types.MessageType.PageEvent, name: typeof eventName === "function" ? eventName(element) : eventName, data: typeof data === "function" ? data(element) : data, eventType: eventType || Types.EventType.Other }); if (element.href && element.target !== "_blank" || element.submit) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } setTimeout(timeoutHandler, mpInstance._Store.SDKConfig.timeout); } }, element, i; if (!selector) { mpInstance.Logger.error("Can't bind event, selector is required"); return; } if (typeof selector === "string") { elements = document.querySelectorAll(selector); } else if (selector.nodeType) { elements = [selector]; } if (elements.length) { mpInstance.Logger.verbose("Found " + elements.length + " element" + (elements.length > 1 ? "s" : "") + ", attaching event handlers"); for (i = 0; i = 0; --o2) { var i2 = this.tryEntries[o2], a2 = i2.completion; if ("root" === i2.tryLoc) return handle("end"); if (i2.tryLoc = 0; --r2) { var o2 = this.tryEntries[r2]; if (o2.tryLoc = 0; --e2) { var r2 = this.tryEntries[e2]; if (r2.finallyLoc === t2) return this.complete(r2.completion, r2.afterLoc), resetTryEntry(r2), y; } }, "catch": function _catch(t2) { for (var e2 = this.tryEntries.length - 1; e2 >= 0; --e2) { var r2 = this.tryEntries[e2]; if (r2.tryLoc === t2) { var n2 = r2.completion; if ("throw" === n2.type) { var o2 = n2.arg; resetTryEntry(r2); } return o2; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e2, r2, n2) { return this.delegate = { iterator: values(e2), resultName: r2, nextLoc: n2 }, "next" === this.method && (this.arg = t), y; } }, e; } module.exports = _regeneratorRuntime2, module.exports.__esModule = true, module.exports["default"] = module.exports; })(regeneratorRuntime$1); var regeneratorRuntimeExports = regeneratorRuntime$1.exports; var runtime = regeneratorRuntimeExports(); var regenerator = runtime; 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(mpid, forwarder, mpInstance, kitBlocker) { var self = this; return { getUserIdentities: function getUserIdentities() { var currentUserIdentities = {}; var identities = mpInstance._Store.getUserIdentities(mpid); for (var identityType in identities) { if (identities.hasOwnProperty(identityType)) { var identityName = Types.IdentityType.getIdentityName(mpInstance._Helpers.parseNumber(identityType)); if (!kitBlocker || kitBlocker && !kitBlocker.isIdentityBlocked(identityName)) currentUserIdentities[identityName] = identities[identityType]; } } currentUserIdentities = mpInstance._Helpers.filterUserIdentitiesForForwarders(currentUserIdentities, forwarder.userIdentityFilters); return { userIdentities: currentUserIdentities }; }, getMPID: function getMPID() { return mpid; }, getUserAttributesLists: function getUserAttributesLists(forwarder2) { var userAttributes, userAttributesLists = {}; userAttributes = self.getAllUserAttributes(); for (var key in userAttributes) { if (userAttributes.hasOwnProperty(key) && Array.isArray(userAttributes[key])) { if (!kitBlocker || kitBlocker && !kitBlocker.isAttributeKeyBlocked(key)) { userAttributesLists[key] = userAttributes[key].slice(); } } } userAttributesLists = mpInstance._Helpers.filterUserAttributes(userAttributesLists, forwarder2.userAttributeFilters); return userAttributesLists; }, getAllUserAttributes: function getAllUserAttributes() { var userAttributesCopy = {}; var userAttributes = mpInstance._Store.getUserAttributes(mpid); if (userAttributes) { for (var prop in userAttributes) { if (userAttributes.hasOwnProperty(prop)) { if (!kitBlocker || kitBlocker && !kitBlocker.isAttributeKeyBlocked(prop)) { if (Array.isArray(userAttributes[prop])) { userAttributesCopy[prop] = userAttributes[prop].slice(); } else { userAttributesCopy[prop] = userAttributes[prop]; } } } } } userAttributesCopy = mpInstance._Helpers.filterUserAttributes(userAttributesCopy, forwarder.userAttributeFilters); return userAttributesCopy; } }; } var _Constants$IdentityMe = Constants.IdentityMethods, Modify$2 = _Constants$IdentityMe.Modify, Identify$1 = _Constants$IdentityMe.Identify, Login$1 = _Constants$IdentityMe.Login, Logout$1 = _Constants$IdentityMe.Logout; function Forwarders(mpInstance, kitBlocker) { var _this = this; var self = this; this.forwarderStatsUploader = new APIClient(mpInstance, kitBlocker).initializeForwarderStatsUploader(); var UserAttributeActionTypes = { setUserAttribute: "setUserAttribute", removeUserAttribute: "removeUserAttribute" }; this.initForwarders = function(userIdentities, forwardingStatsCallback) { var user = mpInstance.Identity.getCurrentUser(); if (!mpInstance._Store.webviewBridgeEnabled && mpInstance._Store.configuredForwarders) { mpInstance._Store.configuredForwarders.sort(function(x, y) { x.settings.PriorityValue = x.settings.PriorityValue || 0; y.settings.PriorityValue = y.settings.PriorityValue || 0; return -1 * (x.settings.PriorityValue - y.settings.PriorityValue); }); mpInstance._Store.activeForwarders = mpInstance._Store.configuredForwarders.filter(function(forwarder) { if (!mpInstance._Consent.isEnabledForUserConsent(forwarder.filteringConsentRuleValues, user)) { return false; } if (!self.isEnabledForUserAttributes(forwarder.filteringUserAttributeValue, user)) { return false; } if (!self.isEnabledForUnknownUser(forwarder.excludeAnonymousUser, user)) { return false; } var filteredUserIdentities = mpInstance._Helpers.filterUserIdentities(userIdentities, forwarder.userIdentityFilters); var filteredUserAttributes = mpInstance._Helpers.filterUserAttributes(user ? user.getAllUserAttributes() : {}, forwarder.userAttributeFilters); if (!forwarder.initialized) { forwarder.logger = mpInstance.Logger; forwarder.init(forwarder.settings, forwardingStatsCallback, false, null, filteredUserAttributes, filteredUserIdentities, mpInstance._Store.SDKConfig.appVersion, mpInstance._Store.SDKConfig.appName, mpInstance._Store.SDKConfig.customFlags, mpInstance._Store.clientId); forwarder.initialized = true; } return true; }); } }; this.isEnabledForUserAttributes = function(filterObject, user) { if (!filterObject || !mpInstance._Helpers.isObject(filterObject) || !Object.keys(filterObject).length) { return true; } var attrHash, valueHash, userAttributes; if (!user) { return false; } else { userAttributes = user.getAllUserAttributes(); } var isMatch = false; try { if (userAttributes && mpInstance._Helpers.isObject(userAttributes) && Object.keys(userAttributes).length) { for (var attrName in userAttributes) { if (userAttributes.hasOwnProperty(attrName)) { attrHash = KitFilterHelper.hashAttributeConditionalForwarding(attrName); valueHash = KitFilterHelper.hashAttributeConditionalForwarding(userAttributes[attrName]); if (attrHash === filterObject.userAttributeName && valueHash === filterObject.userAttributeValue) { isMatch = true; break; } } } } if (filterObject) { return filterObject.includeOnMatch === isMatch; } else { return true; } } catch (e) { return true; } }; this.isEnabledForUnknownUser = function(excludeAnonymousUserBoolean, user) { if (!user || !user.isLoggedIn()) { if (excludeAnonymousUserBoolean) { return false; } } return true; }; this.applyToForwarders = function(functionName, functionArgs) { if (mpInstance._Store.activeForwarders.length) { mpInstance._Store.activeForwarders.forEach(function(forwarder) { var forwarderFunction = forwarder[functionName]; if (forwarderFunction) { try { var result = forwarder[functionName](functionArgs); if (result) { mpInstance.Logger.verbose(result); } } catch (e) { mpInstance.Logger.verbose(e); } } }); } }; this.sendEventToForwarders = function(event) { var clonedEvent, hashedEventName, hashedEventType, filterUserIdentities = function filterUserIdentities2(event2, filterList) { if (event2.UserIdentities && event2.UserIdentities.length) { event2.UserIdentities.forEach(function(userIdentity, i2) { if (mpInstance._Helpers.inArray(filterList, KitFilterHelper.hashUserIdentity(userIdentity.Type))) { event2.UserIdentities.splice(i2, 1); if (i2 > 0) { i2--; } } }); } }, filterAttributes = function filterAttributes2(event2, filterList) { var hash; if (!filterList) { return; } for (var attrName in event2.EventAttributes) { if (event2.EventAttributes.hasOwnProperty(attrName)) { hash = KitFilterHelper.hashEventAttributeKey(event2.EventCategory, event2.EventName, attrName); if (mpInstance._Helpers.inArray(filterList, hash)) { delete event2.EventAttributes[attrName]; } } } }, inFilteredList = function inFilteredList2(filterList, hash) { if (filterList && filterList.length) { if (mpInstance._Helpers.inArray(filterList, hash)) { return true; } } return false; }, forwardingRuleMessageTypes = [Types.MessageType.PageEvent, Types.MessageType.PageView, Types.MessageType.Commerce]; if (!mpInstance._Store.webviewBridgeEnabled && mpInstance._Store.activeForwarders) { hashedEventName = KitFilterHelper.hashEventName(event.EventName, event.EventCategory); hashedEventType = KitFilterHelper.hashEventType(event.EventCategory); for (var i = 0; i -1 && mpInstance._Store.activeForwarders[i].filteringEventAttributeValue && mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeName && mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeValue) { var foundProp = null; if (event.EventAttributes) { for (var prop in event.EventAttributes) { var hashedEventAttributeName; hashedEventAttributeName = KitFilterHelper.hashAttributeConditionalForwarding(prop); if (hashedEventAttributeName === mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeName) { foundProp = { name: hashedEventAttributeName, value: KitFilterHelper.hashAttributeConditionalForwarding(event.EventAttributes[prop]) }; } if (foundProp) { break; } } } var isMatch = foundProp !== null && foundProp.value === mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.eventAttributeValue; var shouldInclude = mpInstance._Store.activeForwarders[i].filteringEventAttributeValue.includeOnMatch === true ? isMatch : !isMatch; if (!shouldInclude) { continue; } } clonedEvent = {}; clonedEvent = mpInstance._Helpers.extend(true, clonedEvent, event); if (event.EventDataType === Types.MessageType.PageEvent && (inFilteredList(mpInstance._Store.activeForwarders[i].eventNameFilters, hashedEventName) || inFilteredList(mpInstance._Store.activeForwarders[i].eventTypeFilters, hashedEventType))) { continue; } else if (event.EventDataType === Types.MessageType.Commerce && inFilteredList(mpInstance._Store.activeForwarders[i].eventTypeFilters, hashedEventType)) { continue; } else if (event.EventDataType === Types.MessageType.PageView && inFilteredList(mpInstance._Store.activeForwarders[i].screenNameFilters, hashedEventName)) { continue; } if (clonedEvent.EventAttributes) { if (event.EventDataType === Types.MessageType.PageEvent) { filterAttributes(clonedEvent, mpInstance._Store.activeForwarders[i].attributeFilters); } else if (event.EventDataType === Types.MessageType.PageView) { filterAttributes(clonedEvent, mpInstance._Store.activeForwarders[i].screenAttributeFilters); } } filterUserIdentities(clonedEvent, mpInstance._Store.activeForwarders[i].userIdentityFilters); clonedEvent.UserAttributes = mpInstance._Helpers.filterUserAttributes(clonedEvent.UserAttributes, mpInstance._Store.activeForwarders[i].userAttributeFilters); if (mpInstance._Store.activeForwarders[i].process) { mpInstance.Logger.verbose("Sending message to forwarder: " + mpInstance._Store.activeForwarders[i].name); var result = mpInstance._Store.activeForwarders[i].process(clonedEvent); if (result) { mpInstance.Logger.verbose(result); } } } } }; this.handleForwarderUserAttributes = function(functionNameKey, key, value2) { if (kitBlocker && kitBlocker.isAttributeKeyBlocked(key) || !mpInstance._Store.activeForwarders.length) { return; } mpInstance._Store.activeForwarders.forEach(function(forwarder) { var forwarderFunction = forwarder[functionNameKey]; if (!forwarderFunction || KitFilterHelper.isFilteredUserAttribute(key, forwarder.userAttributeFilters)) { return; } try { var result; if (functionNameKey === UserAttributeActionTypes.setUserAttribute) { result = forwarder.setUserAttribute(key, value2); } else if (functionNameKey === UserAttributeActionTypes.removeUserAttribute) { result = forwarder.removeUserAttribute(key); } if (result) { mpInstance.Logger.verbose(result); } } catch (e) { mpInstance.Logger.error(e); } }); }; this.setForwarderUserIdentities = function(userIdentities) { mpInstance._Store.activeForwarders.forEach(function(forwarder) { var filteredUserIdentities = mpInstance._Helpers.filterUserIdentities(userIdentities, forwarder.userIdentityFilters); if (forwarder.setUserIdentity) { filteredUserIdentities.forEach(function(identity) { var result = forwarder.setUserIdentity(identity.Identity, identity.Type); if (result) { mpInstance.Logger.verbose(result); } }); } }); }; this.setForwarderOnUserIdentified = function(user) { mpInstance._Store.activeForwarders.forEach(function(forwarder) { var filteredUser = filteredMparticleUser(user.getMPID(), forwarder, mpInstance, kitBlocker); if (forwarder.onUserIdentified) { var result = forwarder.onUserIdentified(filteredUser); if (result) { mpInstance.Logger.verbose(result); } } }); }; this.setForwarderOnIdentityComplete = function(user, identityMethod) { var result; mpInstance._Store.activeForwarders.forEach(function(forwarder) { var filteredUser = filteredMparticleUser(user.getMPID(), forwarder, mpInstance, kitBlocker); var filteredUserIdentities = filteredUser.getUserIdentities(); if (identityMethod === Identify$1) { if (forwarder.onIdentifyComplete) { result = forwarder.onIdentifyComplete(filteredUser, filteredUserIdentities); if (result) { mpInstance.Logger.verbose(result); } } } else if (identityMethod === Login$1) { if (forwarder.onLoginComplete) { result = forwarder.onLoginComplete(filteredUser, filteredUserIdentities); if (result) { mpInstance.Logger.verbose(result); } } } else if (identityMethod === Logout$1) { if (forwarder.onLogoutComplete) { result = forwarder.onLogoutComplete(filteredUser, filteredUserIdentities); if (result) { mpInstance.Logger.verbose(result); } } } else if (identityMethod === Modify$2) { if (forwarder.onModifyComplete) { result = forwarder.onModifyComplete(filteredUser, filteredUserIdentities); if (result) { mpInstance.Logger.verbose(result); } } } }); }; this.getForwarderStatsQueue = function() { return mpInstance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue; }; this.setForwarderStatsQueue = function(queue) { mpInstance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue = queue; }; this.processForwarders = function(config, forwardingStatsCallback) { if (!config) { mpInstance.Logger.warning("No config was passed. Cannot process forwarders"); } else { this.processUIEnabledKits(config); this.processSideloadedKits(config); self.initForwarders(mpInstance._Store.SDKConfig.identifyRequest.userIdentities, forwardingStatsCallback); } }; this.processUIEnabledKits = function(config) { var kits = this.returnKitConstructors(); try { if (Array.isArray(config.kitConfigs) && config.kitConfigs.length) { config.kitConfigs.forEach(function(kitConfig) { self.configureUIEnabledKit(kitConfig, kits); }); } } catch (e) { mpInstance.Logger.error("MP Kits not configured propertly. Kits may not be initialized. " + e); } }; this.returnKitConstructors = function() { var kits = {}; if (!isEmpty(mpInstance._Store.SDKConfig.kits)) { kits = mpInstance._Store.SDKConfig.kits; } else if (!isEmpty(mpInstance._preInit.forwarderConstructors)) { mpInstance._preInit.forwarderConstructors.forEach(function(kitConstructor) { if (kitConstructor.suffix) { var kitNameWithConstructorSuffix = "".concat(kitConstructor.name, "-").concat(kitConstructor.suffix); kits[kitNameWithConstructorSuffix] = kitConstructor; } else { kits[kitConstructor.name] = kitConstructor; } }); } return kits; }; this.configureUIEnabledKit = function(configuration, kits) { var newKit = null; var config = configuration; for (var name in kits) { var kitNameWithConfigSuffix = void 0; if (config.suffix) { kitNameWithConfigSuffix = "".concat(config.name, "-").concat(config.suffix); } if (name === kitNameWithConfigSuffix || name === config.name) { if (config.isDebug === mpInstance._Store.SDKConfig.isDevelopmentMode || config.isSandbox === mpInstance._Store.SDKConfig.isDevelopmentMode) { newKit = this.returnConfiguredKit(kits[name], config); mpInstance._Store.configuredForwarders.push(newKit); break; } } } }; this.processSideloadedKits = function(mpConfig) { try { if (Array.isArray(mpConfig.sideloadedKits)) { var registeredSideloadedKits = { kits: {} }; var unregisteredSideloadedKits = mpConfig.sideloadedKits; unregisteredSideloadedKits.forEach(function(unregisteredKit) { try { unregisteredKit.kitInstance.register(registeredSideloadedKits); var kitName = unregisteredKit.kitInstance.name; registeredSideloadedKits.kits[kitName].filters = unregisteredKit.filterDictionary; } catch (e) { console.error("Error registering sideloaded kit " + unregisteredKit.kitInstance.name); } }); for (var registeredKitKey in registeredSideloadedKits.kits) { var registeredKit = registeredSideloadedKits.kits[registeredKitKey]; self.configureSideloadedKit(registeredKit); } if (!isEmpty(registeredSideloadedKits.kits)) { var kitKeys = Object.keys(registeredSideloadedKits.kits); mpInstance._Store.sideloadedKitsCount = kitKeys.length; } } } catch (e) { mpInstance.Logger.error("Sideloaded Kits not configured propertly. Kits may not be initialized. " + e); } }; this.configureSideloadedKit = function(kitConstructor) { mpInstance._Store.configuredForwarders.push(this.returnConfiguredKit(kitConstructor, kitConstructor.filters)); }; this.returnConfiguredKit = function(forwarder) { var config = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; var newForwarder = new forwarder.constructor(); newForwarder.id = config.moduleId; newForwarder.isSandbox = config.isDebug || config.isSandbox; newForwarder.hasSandbox = config.hasDebugString === "true"; newForwarder.isVisible = config.isVisible || true; newForwarder.settings = config.settings || {}; newForwarder.eventNameFilters = config.eventNameFilters || []; newForwarder.eventTypeFilters = config.eventTypeFilters || []; newForwarder.attributeFilters = config.attributeFilters || []; newForwarder.screenNameFilters = config.screenNameFilters || []; newForwarder.screenAttributeFilters = config.screenAttributeFilters || []; newForwarder.userIdentityFilters = config.userIdentityFilters || []; newForwarder.userAttributeFilters = config.userAttributeFilters || []; newForwarder.filteringEventAttributeValue = config.filteringEventAttributeValue || {}; newForwarder.filteringUserAttributeValue = config.filteringUserAttributeValue || {}; newForwarder.eventSubscriptionId = config.eventSubscriptionId || null; newForwarder.filteringConsentRuleValues = config.filteringConsentRuleValues || {}; newForwarder.excludeAnonymousUser = config.excludeAnonymousUser || false; return newForwarder; }; this.configurePixel = function(settings) { if (settings.isDebug === mpInstance._Store.SDKConfig.isDevelopmentMode || settings.isProduction !== mpInstance._Store.SDKConfig.isDevelopmentMode) { mpInstance._Store.pixelConfigurations.push(settings); } }; this.processPixelConfigs = function(config) { try { if (!isEmpty(config.pixelConfigs)) { config.pixelConfigs.forEach(function(pixelConfig) { self.configurePixel(pixelConfig); }); } } catch (e) { mpInstance.Logger.error("Cookie Sync configs not configured propertly. Cookie Sync may not be initialized. " + e); } }; this.sendSingleForwardingStatsToServer = /* @__PURE__ */ (function() { var _ref = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime.mark(function _callee(forwardingStatsData) { var _mpInstance$Logger; var fetchPayload, response, message; return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: fetchPayload = { method: "post", body: JSON.stringify(forwardingStatsData), headers: { Accept: "text/plain;charset=UTF-8", "Content-Type": "text/plain;charset=UTF-8" } }; _context.next = 3; return _this.forwarderStatsUploader.upload(fetchPayload); case 3: response = _context.sent; if (response.status === 202) { message = "Successfully sent forwarding stats to mParticle Servers"; } else { message = "Issue with forwarding stats to mParticle Servers, received HTTP Code of " + response.statusText; } mpInstance === null || mpInstance === void 0 || (_mpInstance$Logger = mpInstance.Logger) === null || _mpInstance$Logger === void 0 || _mpInstance$Logger.verbose(message); case 6: case "end": return _context.stop(); } }, _callee); })); return function(_x) { return _ref.apply(this, arguments); }; })(); } var MessageType = Types.MessageType; var ApplicationTransitionType = Types.ApplicationTransitionType; function convertCustomFlags(event, dto) { var valueArray = []; dto.flags = {}; for (var prop in event.CustomFlags) { valueArray = []; if (event.CustomFlags.hasOwnProperty(prop)) { if (Array.isArray(event.CustomFlags[prop])) { event.CustomFlags[prop].forEach(function(customFlagProperty) { if (isValidCustomFlagProperty(customFlagProperty)) { valueArray.push(customFlagProperty.toString()); } }); } else if (isValidCustomFlagProperty(event.CustomFlags[prop])) { valueArray.push(event.CustomFlags[prop].toString()); } if (valueArray.length) { dto.flags[prop] = valueArray; } } } } function convertProductToV2DTO(product) { return { id: parseStringOrNumber(product.Sku), nm: parseStringOrNumber(product.Name), pr: parseNumber(product.Price), qt: parseNumber(product.Quantity), br: parseStringOrNumber(product.Brand), va: parseStringOrNumber(product.Variant), ca: parseStringOrNumber(product.Category), ps: parseNumber(product.Position), cc: parseStringOrNumber(product.CouponCode), tpa: parseNumber(product.TotalAmount), attrs: product.Attributes }; } function convertProductListToV2DTO(productList) { if (!productList) { return []; } return productList.map(function(product) { return convertProductToV2DTO(product); }); } function ServerModel(mpInstance) { var self = this; this.convertToConsentStateV2DTO = function(state) { if (!state) { return null; } var jsonObject = {}; var gdprConsentState = state.getGDPRConsentState(); if (gdprConsentState) { var gdpr = {}; jsonObject.gdpr = gdpr; for (var purpose in gdprConsentState) { if (gdprConsentState.hasOwnProperty(purpose)) { var gdprConsent = gdprConsentState[purpose]; jsonObject.gdpr[purpose] = {}; if (typeof gdprConsent.Consented === "boolean") { gdpr[purpose].c = gdprConsent.Consented; } if (typeof gdprConsent.Timestamp === "number") { gdpr[purpose].ts = gdprConsent.Timestamp; } if (typeof gdprConsent.ConsentDocument === "string") { gdpr[purpose].d = gdprConsent.ConsentDocument; } if (typeof gdprConsent.Location === "string") { gdpr[purpose].l = gdprConsent.Location; } if (typeof gdprConsent.HardwareId === "string") { gdpr[purpose].h = gdprConsent.HardwareId; } } } } var ccpaConsentState = state.getCCPAConsentState(); if (ccpaConsentState) { jsonObject.ccpa = { data_sale_opt_out: { c: ccpaConsentState.Consented, ts: ccpaConsentState.Timestamp, d: ccpaConsentState.ConsentDocument, l: ccpaConsentState.Location, h: ccpaConsentState.HardwareId } }; } return jsonObject; }; this.createEventObject = function(event, user) { var _a2; var uploadObject = {}; var eventObject = {}; var optOut = event.messageType === Types.MessageType.OptOut ? !mpInstance._Store.isEnabled : null; if (mpInstance._Store.sessionId || event.messageType === Types.MessageType.OptOut || mpInstance._Store.webviewBridgeEnabled) { var customFlags = __assign({}, event.customFlags); var integrationAttributes = mpInstance._Store.integrationAttributes; var getFeatureFlag = mpInstance._Helpers.getFeatureFlag; var integrationSpecificIds = getFeatureFlag && getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIds); var integrationSpecificIdsV2 = getFeatureFlag && (getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIdsV2) || ""); var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== Constants.CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true; if (isIntegrationCaptureEnabled) { mpInstance._IntegrationCapture.capture(); var transformedClickIDs = mpInstance._IntegrationCapture.getClickIdsAsCustomFlags(); customFlags = __assign(__assign({}, transformedClickIDs), customFlags); var transformedIntegrationAttributes = mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes(); integrationAttributes = __assign(__assign({}, transformedIntegrationAttributes), integrationAttributes); } if (event.hasOwnProperty("toEventAPIObject")) { eventObject = event.toEventAPIObject(); } else { eventObject = { // This is an artifact from v2 events where SessionStart/End and AST event // names are numbers (1, 2, or 10), but going forward with v3, these lifecycle // events do not have names, but are denoted by their `event_type` EventName: event.name || event.messageType, EventCategory: event.eventType, EventAttributes: mpInstance._Helpers.sanitizeAttributes(event.data, event.name), ActiveTimeOnSite: (_a2 = mpInstance._timeOnSiteTimer) === null || _a2 === void 0 ? void 0 : _a2.getTimeInForeground(), SourceMessageId: event.sourceMessageId || mpInstance._Helpers.generateUniqueId(), EventDataType: event.messageType, CustomFlags: customFlags, UserAttributeChanges: event.userAttributeChanges, UserIdentityChanges: event.userIdentityChanges }; } if (event.messageType !== Types.MessageType.SessionEnd) { mpInstance._Store.dateLastEventSent = /* @__PURE__ */ new Date(); } uploadObject = { // FIXME: Deprecate when we get rid of V2 Store: mpInstance._Store.serverSettings, SDKVersion: Constants.sdkVersion, SessionId: mpInstance._Store.sessionId, SessionStartDate: mpInstance._Store.sessionStartDate ? mpInstance._Store.sessionStartDate.getTime() : 0, Debug: mpInstance._Store.SDKConfig.isDevelopmentMode, Location: mpInstance._Store.currentPosition, OptOut: optOut, ExpandedEventCount: 0, AppVersion: mpInstance.getAppVersion(), AppName: mpInstance.getAppName(), Package: mpInstance._Store.SDKConfig["package"], ClientGeneratedId: mpInstance._Store.clientId, DeviceId: mpInstance._Store.deviceId, IntegrationAttributes: integrationAttributes, CurrencyCode: mpInstance._Store.currencyCode, DataPlan: mpInstance._Store.SDKConfig.dataPlan ? mpInstance._Store.SDKConfig.dataPlan : {} }; if (eventObject.EventDataType === MessageType.AppStateTransition) { eventObject.IsFirstRun = mpInstance._Store.isFirstRun; eventObject.LaunchReferral = window.location.href || null; } eventObject.CurrencyCode = mpInstance._Store.currencyCode; var currentUser = user || mpInstance.Identity.getCurrentUser(); appendUserInfo(currentUser, eventObject); if (event.messageType === Types.MessageType.SessionEnd) { eventObject.SessionLength = mpInstance._Store.dateLastEventSent.getTime() - mpInstance._Store.sessionStartDate.getTime(); eventObject.currentSessionMPIDs = mpInstance._Store.currentSessionMPIDs; eventObject.EventAttributes = mpInstance._Store.sessionAttributes; mpInstance._Store.currentSessionMPIDs = []; mpInstance._Store.sessionStartDate = null; } uploadObject.Timestamp = mpInstance._Store.dateLastEventSent.getTime(); return mpInstance._Helpers.extend({}, eventObject, uploadObject); } return null; }; this.convertEventToV2DTO = function(event) { var dto = { n: event.EventName, et: event.EventCategory, ua: event.UserAttributes, ui: event.UserIdentities, ia: event.IntegrationAttributes, str: event.Store, attrs: event.EventAttributes, sdk: event.SDKVersion, sid: event.SessionId, sl: event.SessionLength, ssd: event.SessionStartDate, dt: event.EventDataType, dbg: event.Debug, ct: event.Timestamp, lc: event.Location, o: event.OptOut, eec: event.ExpandedEventCount, av: event.AppVersion, cgid: event.ClientGeneratedId, das: event.DeviceId, mpid: event.MPID, smpids: event.currentSessionMPIDs }; if (event.DataPlan && event.DataPlan.PlanId) { dto.dp_id = event.DataPlan.PlanId; if (event.DataPlan.PlanVersion) { dto.dp_v = event.DataPlan.PlanVersion; } } var consent = self.convertToConsentStateV2DTO(event.ConsentState); if (consent) { dto.con = consent; } if (event.EventDataType === MessageType.AppStateTransition) { dto.fr = event.IsFirstRun; dto.iu = false; dto.at = ApplicationTransitionType.AppInit; dto.lr = event.LaunchReferral; dto.attrs = null; } if (event.CustomFlags) { convertCustomFlags(event, dto); } if (event.EventDataType === MessageType.Commerce) { dto.cu = event.CurrencyCode; if (event.ShoppingCart) { dto.sc = { pl: convertProductListToV2DTO(event.ShoppingCart.ProductList) }; } if (event.ProductAction) { dto.pd = { an: event.ProductAction.ProductActionType, cs: mpInstance._Helpers.parseNumber(event.ProductAction.CheckoutStep), co: event.ProductAction.CheckoutOptions, pl: convertProductListToV2DTO(event.ProductAction.ProductList), ti: event.ProductAction.TransactionId, ta: event.ProductAction.Affiliation, tcc: event.ProductAction.CouponCode, tr: mpInstance._Helpers.parseNumber(event.ProductAction.TotalAmount), ts: mpInstance._Helpers.parseNumber(event.ProductAction.ShippingAmount), tt: mpInstance._Helpers.parseNumber(event.ProductAction.TaxAmount) }; } else if (event.PromotionAction) { dto.pm = { an: event.PromotionAction.PromotionActionType, pl: event.PromotionAction.PromotionList.map(function(promotion) { return { id: promotion.Id, nm: promotion.Name, cr: promotion.Creative, ps: promotion.Position ? promotion.Position : 0 }; }) }; } else if (event.ProductImpressions) { dto.pi = event.ProductImpressions.map(function(impression) { return { pil: impression.ProductImpressionList, pl: convertProductListToV2DTO(impression.ProductList) }; }); } } else if (event.EventDataType === MessageType.Profile) { dto.pet = event.ProfileMessageType; } return dto; }; } function forwardingStatsUploader(mpInstance) { this.startForwardingStatsTimer = function() { mParticle._forwardingStatsTimer = setInterval(function() { prepareAndSendForwardingStatsBatch(); }, mpInstance._Store.SDKConfig.forwarderStatsTimeout); }; function prepareAndSendForwardingStatsBatch() { var forwarderQueue = mpInstance._Forwarders.getForwarderStatsQueue(), uploadsTable = mpInstance._Persistence.forwardingStatsBatches.uploadsTable, now = Date.now(); if (forwarderQueue.length) { uploadsTable[now] = { uploading: false, data: forwarderQueue }; mpInstance._Forwarders.setForwarderStatsQueue([]); } for (var date in uploadsTable) { (function(date2) { if (uploadsTable.hasOwnProperty(date2)) { if (uploadsTable[date2].uploading === false) { var xhrCallback = function xhrCallback2() { if (xhr.readyState === 4) { if (xhr.status === 200 || xhr.status === 202) { mpInstance.Logger.verbose("Successfully sent " + xhr.statusText + " from server"); delete uploadsTable[date2]; } else if (xhr.status.toString()[0] === "4") { if (xhr.status !== 429) { delete uploadsTable[date2]; } } else { uploadsTable[date2].uploading = false; } } }; var xhr = mpInstance._Helpers.createXHR(xhrCallback); var forwardingStatsData = uploadsTable[date2].data; uploadsTable[date2].uploading = true; mpInstance._APIClient.sendBatchForwardingStatsToServer(forwardingStatsData, xhr); } } })(date); } } } var AudienceManager = ( /** @class */ (function() { function AudienceManager2(userAudienceUrl, apiKey, logger) { this.url = ""; this.logger = logger; this.url = "https://".concat(userAudienceUrl).concat(apiKey, "/audience"); this.userAudienceAPI = window.fetch ? new FetchUploader(this.url) : new XHRUploader(this.url); } AudienceManager2.prototype.sendGetUserAudienceRequest = function(mpid, callback) { return __awaiter(this, void 0, void 0, function() { var fetchPayload, audienceURLWithMPID, userAudiencePromise, userAudienceMembershipsServerResponse, parsedUserAudienceMemberships, e_1; return __generator(this, function(_a2) { switch (_a2.label) { case 0: this.logger.verbose("Fetching user audiences from server"); fetchPayload = { method: "GET", headers: { Accept: "*/*" } }; audienceURLWithMPID = "".concat(this.url, "?mpid=").concat(mpid); _a2.label = 1; case 1: _a2.trys.push([1, 6, , 7]); return [4, this.userAudienceAPI.upload(fetchPayload, audienceURLWithMPID)]; case 2: userAudiencePromise = _a2.sent(); if (!(userAudiencePromise.status >= 200 && userAudiencePromise.status = 0) { combinedUIByType[Types.IdentityType.getIdentityType(key)] = combinedUIByName[key]; } } return combinedUIByType; }, createAliasNetworkRequest: function createAliasNetworkRequest(aliasRequest) { return { request_id: mpInstance._Helpers.generateUniqueId(), request_type: "alias", environment: mpInstance._Store.SDKConfig.isDevelopmentMode ? "development" : "production", api_key: mpInstance._Store.devToken, data: { destination_mpid: aliasRequest.destinationMpid, source_mpid: aliasRequest.sourceMpid, start_unixtime_ms: aliasRequest.startTime, end_unixtime_ms: aliasRequest.endTime, scope: aliasRequest.scope, device_application_stamp: mpInstance._Store.deviceId } }; }, convertAliasToNative: function convertAliasToNative(aliasRequest) { return { DestinationMpid: aliasRequest.destinationMpid, SourceMpid: aliasRequest.sourceMpid, StartUnixtimeMs: aliasRequest.startTime, EndUnixtimeMs: aliasRequest.endTime }; }, convertToNative: function convertToNative(identityApiData) { var nativeIdentityRequest = []; if (identityApiData && identityApiData.userIdentities) { for (var key in identityApiData.userIdentities) { if (identityApiData.userIdentities.hasOwnProperty(key)) { nativeIdentityRequest.push({ Type: Types.IdentityType.getIdentityType(key), Identity: identityApiData.userIdentities[key] }); } } return { UserIdentities: nativeIdentityRequest }; } } }; this.IdentityAPI = { HTTPCodes: HTTPCodes$2, /** * Initiate a logout request to the mParticle server * @method identify * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk) * @param {Function} [callback] A callback function that is called when the identify request completes */ identify: function identify(identityApiData, callback) { var mpid, currentUser = mpInstance.Identity.getCurrentUser(), preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Identify); if (currentUser) { mpid = currentUser.getMPID(); } if (preProcessResult.valid) { var identityApiRequest = mpInstance._Identity.IdentityRequest.createIdentityRequest(preProcessResult.cleanedIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.deviceId, mpInstance._Store.context, mpid); if (mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)) { var successfullyCachedIdentity = tryCacheIdentity(identityApiRequest.known_identities, self.idCache, self.parseIdentityResponse, mpid, callback, identityApiData, Identify); if (successfullyCachedIdentity) { return; } } if (mpInstance._Helpers.canLog()) { if (mpInstance._Store.webviewBridgeEnabled) { mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Identify, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData))); mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, "Identify request sent to native sdk"); } else { mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Identify, callback, identityApiData, self.parseIdentityResponse, mpid, identityApiRequest.known_identities); } } else { mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent); mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent); } } else { mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error); mpInstance.Logger.verbose(preProcessResult); } }, /** * Initiate a logout request to the mParticle server * @method logout * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk) * @param {Function} [callback] A callback function that is called when the logout request completes */ logout: function logout(identityApiData, callback) { var mpid, currentUser = mpInstance.Identity.getCurrentUser(), preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Logout); if (currentUser) { mpid = currentUser.getMPID(); } if (preProcessResult.valid) { var evt, identityApiRequest = mpInstance._Identity.IdentityRequest.createIdentityRequest(preProcessResult.cleanedIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.deviceId, mpInstance._Store.context, mpid); if (mpInstance._Helpers.canLog()) { if (mpInstance._Store.webviewBridgeEnabled) { mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Logout, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData))); mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, "Logout request sent to native sdk"); } else { mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Logout, callback, identityApiData, self.parseIdentityResponse, mpid); evt = mpInstance._ServerModel.createEventObject({ messageType: Types.MessageType.Profile }); evt.ProfileMessageType = Types.ProfileMessageType.Logout; if (mpInstance._Store.activeForwarders.length) { mpInstance._Store.activeForwarders.forEach(function(forwarder) { if (forwarder.logOut) { forwarder.logOut(evt); } }); } } } else { mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent); mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent); } } else { mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error); mpInstance.Logger.verbose(preProcessResult); } }, /** * Initiate a login request to the mParticle server * @method login * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk) * @param {Function} [callback] A callback function that is called when the login request completes */ login: function login(identityApiData, callback) { var mpid, currentUser = mpInstance.Identity.getCurrentUser(), preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Login); if (currentUser) { mpid = currentUser.getMPID(); } if (preProcessResult.valid) { var identityApiRequest = mpInstance._Identity.IdentityRequest.createIdentityRequest(preProcessResult.cleanedIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.deviceId, mpInstance._Store.context, mpid); if (mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)) { var successfullyCachedIdentity = tryCacheIdentity(identityApiRequest.known_identities, self.idCache, self.parseIdentityResponse, mpid, callback, identityApiData, Login); if (successfullyCachedIdentity) { return; } } if (mpInstance._Helpers.canLog()) { if (mpInstance._Store.webviewBridgeEnabled) { mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Login, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData))); mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, "Login request sent to native sdk"); } else { mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Login, callback, identityApiData, self.parseIdentityResponse, mpid, identityApiRequest.known_identities); } } else { mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent); mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent); } } else { mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error); mpInstance.Logger.verbose(preProcessResult); } }, /** * Initiate a modify request to the mParticle server * @method modify * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk) * @param {Function} [callback] A callback function that is called when the modify request completes */ modify: function modify(identityApiData, callback) { var mpid, currentUser = mpInstance.Identity.getCurrentUser(), preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Modify$1); if (currentUser) { mpid = currentUser.getMPID(); } if (preProcessResult.valid) { var newUserIdentities = identityApiData && identityApiData.userIdentities ? preProcessResult.cleanedIdentities.userIdentities : {}; var identityApiRequest = mpInstance._Identity.IdentityRequest.createModifyIdentityRequest(currentUser ? currentUser.getUserIdentities().userIdentities : {}, newUserIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.context); if (mpInstance._Helpers.canLog()) { if (mpInstance._Store.webviewBridgeEnabled) { mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Modify, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData))); mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, "Modify request sent to native sdk"); } else { mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Modify$1, callback, identityApiData, self.parseIdentityResponse, mpid, identityApiRequest.known_identities); } } else { mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent); mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent); } } else { mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error); mpInstance.Logger.verbose(preProcessResult); } }, /** * Returns a user object with methods to interact with the current user * @method getCurrentUser * @return {Object} the current user object */ getCurrentUser: function getCurrentUser() { var mpid; if (mpInstance._Store) { mpid = mpInstance._Store.mpid; if (mpid) { mpid = mpInstance._Store.mpid.slice(); return self.mParticleUser(mpid, mpInstance._Store.isLoggedIn); } else if (mpInstance._Store.webviewBridgeEnabled) { return self.mParticleUser(); } else { return null; } } else { return null; } }, /** * Returns a the user object associated with the mpid parameter or 'null' if no such * user exists * @method getUser * @param {String} mpid of the desired user * @return {Object} the user for mpid */ getUser: function getUser(mpid) { var persistence = mpInstance._Persistence.getPersistence(); if (persistence) { if (persistence[mpid] && !Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(mpid)) { return self.mParticleUser(mpid); } else { return null; } } else { return null; } }, /** * Returns all users, including the current user and all previous users that are stored on the device. * @method getUsers * @return {Array} array of users */ getUsers: function getUsers() { var persistence = mpInstance._Persistence.getPersistence(); var users = []; if (persistence) { for (var key in persistence) { if (!Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(key)) { users.push(self.mParticleUser(key)); } } } users.sort(function(a, b) { var aLastSeen = a.getLastSeenTime() || 0; var bLastSeen = b.getLastSeenTime() || 0; if (aLastSeen > bLastSeen) { return -1; } else { return 1; } }); return users; }, /** * 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(aliasRequest, callback) { var message; if (!aliasRequest.destinationMpid || !aliasRequest.sourceMpid) { message = Messages$2.ValidationMessages.AliasMissingMpid; } if (aliasRequest.destinationMpid === aliasRequest.sourceMpid) { message = Messages$2.ValidationMessages.AliasNonUniqueMpid; } if (!aliasRequest.startTime || !aliasRequest.endTime) { message = Messages$2.ValidationMessages.AliasMissingTime; } if (aliasRequest.startTime > aliasRequest.endTime) { message = Messages$2.ValidationMessages.AliasStartBeforeEndTime; } if (message) { mpInstance.Logger.warning(message); mpInstance._Helpers.invokeAliasCallback(callback, HTTPCodes$2.validationIssue, message); return; } if (mpInstance._Helpers.canLog()) { if (mpInstance._Store.webviewBridgeEnabled) { mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias, JSON.stringify(mpInstance._Identity.IdentityRequest.convertAliasToNative(aliasRequest))); mpInstance._Helpers.invokeAliasCallback(callback, HTTPCodes$2.nativeIdentityRequest, "Alias request sent to native sdk"); } else { mpInstance.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest + ": " + aliasRequest.sourceMpid + " -> " + aliasRequest.destinationMpid); var aliasRequestMessage = mpInstance._Identity.IdentityRequest.createAliasNetworkRequest(aliasRequest); mpInstance._IdentityAPIClient.sendAliasRequest(aliasRequestMessage, callback); } } else { mpInstance._Helpers.invokeAliasCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonAliasUsers); mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers); } }, /** 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(sourceUser, destinationUser) { try { if (!destinationUser || !sourceUser) { mpInstance.Logger.error("'destinationUser' and 'sourceUser' must both be present"); return null; } var startTime = sourceUser.getFirstSeenTime(); if (!startTime) { mpInstance.Identity.getUsers().forEach(function(user) { if (user.getFirstSeenTime() && (!startTime || user.getFirstSeenTime() 0) { dataPoints.forEach(function(point) { return _this.addToMatchLookups(point); }); } } catch (e) { this.mpInstance.Logger.error("There was an issue with the data plan: " + e); } } } KitBlocker2.prototype.addToMatchLookups = function(point) { var _a2, _b, _c; if (!point.match || !point.validator) { this.mpInstance.Logger.warning("Data Plan Point is not valid' + ".concat(point)); return; } var matchKey = this.generateMatchKey(point.match); var properties = this.getPlannedProperties(point.match.type, point.validator); this.dataPlanMatchLookups[matchKey] = properties; if (((_a2 = point === null || point === void 0 ? void 0 : point.match) === null || _a2 === void 0 ? void 0 : _a2.type) === DataPlanMatchType.ProductImpression || ((_b = point === null || point === void 0 ? void 0 : point.match) === null || _b === void 0 ? void 0 : _b.type) === DataPlanMatchType.ProductAction || ((_c = point === null || point === void 0 ? void 0 : point.match) === null || _c === void 0 ? void 0 : _c.type) === DataPlanMatchType.PromotionAction) { matchKey = this.generateProductAttributeMatchKey(point.match); properties = this.getProductProperties(point.match.type, point.validator); this.dataPlanMatchLookups[matchKey] = properties; } }; KitBlocker2.prototype.generateMatchKey = function(match) { var criteria = match.criteria || ""; switch (match.type) { case DataPlanMatchType.CustomEvent: var customEventCriteria = criteria; return [DataPlanMatchType.CustomEvent, customEventCriteria.custom_event_type, customEventCriteria.event_name].join(":"); case DataPlanMatchType.ScreenView: var screenViewCriteria = criteria; return [DataPlanMatchType.ScreenView, "", screenViewCriteria.screen_name].join(":"); case DataPlanMatchType.ProductAction: var productActionMatch = criteria; return [match.type, productActionMatch.action].join(":"); case DataPlanMatchType.PromotionAction: var promoActionMatch = criteria; return [match.type, promoActionMatch.action].join(":"); case DataPlanMatchType.ProductImpression: var productImpressionActionMatch = criteria; return [match.type, productImpressionActionMatch.action].join(":"); case DataPlanMatchType.UserIdentities: case DataPlanMatchType.UserAttributes: return [match.type].join(":"); default: return null; } }; KitBlocker2.prototype.generateProductAttributeMatchKey = function(match) { var criteria = match.criteria || ""; switch (match.type) { case DataPlanMatchType.ProductAction: var productActionMatch = criteria; return [match.type, productActionMatch.action, "ProductAttributes"].join(":"); case DataPlanMatchType.PromotionAction: var promoActionMatch = criteria; return [match.type, promoActionMatch.action, "ProductAttributes"].join(":"); case DataPlanMatchType.ProductImpression: return [match.type, "ProductAttributes"].join(":"); default: return null; } }; KitBlocker2.prototype.getPlannedProperties = function(type, validator) { var _a2, _b, _c, _d, _e, _f, _g, _h; var customAttributes; var userAdditionalProperties; switch (type) { case DataPlanMatchType.CustomEvent: case DataPlanMatchType.ScreenView: case DataPlanMatchType.ProductAction: case DataPlanMatchType.PromotionAction: case DataPlanMatchType.ProductImpression: customAttributes = (_d = (_c = (_b = (_a2 = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _a2 === void 0 ? void 0 : _a2.properties) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.properties) === null || _d === void 0 ? void 0 : _d.custom_attributes; if (customAttributes) { if (customAttributes.additionalProperties === true || customAttributes.additionalProperties === void 0) { return true; } else { var properties = {}; for (var _i = 0, _j = Object.keys(customAttributes.properties); _i = 3) { subdomainIndex = 2; } var _timestamp = timestamp || Date.now(); return "fb.".concat(subdomainIndex, ".").concat(_timestamp, ".").concat(clickId); }; var IntegrationOutputs = { CUSTOM_FLAGS: "custom_flags", PARTNER_IDENTITIES: "partner_identities", INTEGRATION_ATTRIBUTES: "integration_attributes" }; var 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 } }; var 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 } }; var IntegrationCapture = ( /** @class */ (function() { function IntegrationCapture2(captureMode) { this.initialTimestamp = Date.now(); this.captureMode = captureMode; this.filteredPartnerIdentityMappings = this.filterMappings(IntegrationOutputs.PARTNER_IDENTITIES); this.filteredCustomFlagMappings = this.filterMappings(IntegrationOutputs.CUSTOM_FLAGS); this.filteredIntegrationAttributeMappings = this.filterMappings(IntegrationOutputs.INTEGRATION_ATTRIBUTES); } IntegrationCapture2.prototype.capture = function() { var queryParams = this.captureQueryParams() || {}; var cookies = this.captureCookies() || {}; var localStorage2 = this.captureLocalStorage() || {}; if (queryParams["fbclid"] && cookies["_fbc"]) { delete cookies["_fbc"]; } var hasQueryParamId = queryParams["rtid"] || queryParams["rclid"]; var hasLocalStorageId = localStorage2["RoktTransactionId"]; var hasCookieId = cookies["RoktTransactionId"]; if (hasQueryParamId) { if (hasLocalStorageId) { delete localStorage2["RoktTransactionId"]; } if (hasCookieId) { delete cookies["RoktTransactionId"]; } } else if (hasLocalStorageId && hasCookieId) { delete cookies["RoktTransactionId"]; } this.clickIds = __assign(__assign(__assign(__assign({}, this.clickIds), queryParams), localStorage2), cookies); }; IntegrationCapture2.prototype.captureCookies = function() { var integrationKeys = this.getAllowedKeysForMode(); var cookies = getCookies(integrationKeys); return this.applyProcessors(cookies, getHref(), this.initialTimestamp); }; IntegrationCapture2.prototype.captureQueryParams = function() { var queryParams = this.getQueryParams(); return this.applyProcessors(queryParams, getHref(), this.initialTimestamp); }; IntegrationCapture2.prototype.captureLocalStorage = function() { var integrationKeys = this.getAllowedKeysForMode(); var localStorageItems = {}; for (var _i = 0, integrationKeys_1 = integrationKeys; _i