diff --git a/build/moesif.amd.js b/build/moesif.amd.js
index e26bb4c..aa04edb 100644
--- a/build/moesif.amd.js
+++ b/build/moesif.amd.js
@@ -2,7 +2,7 @@ define(function () { 'use strict';
var Config = {
DEBUG: false,
- LIB_VERSION: '1.8.12'
+ LIB_VERSION: '1.8.13'
};
// since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file
@@ -2437,8 +2437,8 @@ define(function () { 'use strict';
STORED_COMPANY_ID: 'moesif_stored_company_id',
STORED_SESSION_ID: 'moesif_stored_session_id',
STORED_ANONYMOUS_ID: 'moesif_anonymous_id',
- STORED_CAMPAIGN_DATA: 'moesif_campaign_data',
- STORED_INITIAL_CAMPAIGN_DATA: 'moesif_initial_campaign'
+ STORED_CAMPAIGN_DATA_USER: 'moesif_campaign_data',
+ STORED_CAMPAIGN_DATA_COMPANY: 'moesif_campaign_company'
};
function replacePrefix(key, prefix) {
@@ -2530,7 +2530,10 @@ define(function () { 'use strict';
_.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_ANONYMOUS_ID, prefix));
_.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_SESSION_ID, prefix));
_.cookie.remove(
- replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, prefix)
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, prefix)
+ );
+ _.cookie.remove(
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, prefix)
);
}
@@ -2549,7 +2552,10 @@ define(function () { 'use strict';
replacePrefix(STORAGE_CONSTANTS.STORED_SESSION_ID, prefix)
);
_.localStorage.remove(
- replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, prefix)
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, prefix)
+ );
+ _.localStorage.remove(
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, prefix)
);
}
@@ -2591,87 +2597,83 @@ define(function () { 'use strict';
}
}
- // since identify company can happen a lot later
- // than initial anonymous users
- // persist the very initial campaign data for
- // companies until company is identified.
- function getStoredInitialCampaignData(opt) {
- var storedCampaignData = null;
- var storedCampaignString = null;
- try {
- storedCampaignString = getFromPersistence(STORAGE_CONSTANTS.STORED_INITIAL_CAMPAIGN_DATA, opt);
- if (storedCampaignString) {
- storedCampaignData = _.JSONDecode(storedCampaignString);
- }
- } catch (err) {
- logger$4.error('failed to decode company campaign data ' + storedCampaignString);
- logger$4.error(err);
+ function hasData(data) {
+ if (data && !_.isEmptyObject(data)) {
+ return true;
}
-
- return storedCampaignData;
+ return false;
}
- function mergeCampaignData(saved, current) {
- if (!current) {
- return saved;
- }
-
- if (!saved) {
- return current;
- }
-
- var result = _.extend({}, saved, current);
-
- // if utm source exists.
- // every field of UTM will be override to be
- // consistent.
- if (current && current[UTMConstants.UTM_SOURCE]) {
- for (var prop in UTMConstants) {
- result[UTMConstants[prop]] = current[UTMConstants[prop]];
+ function saveEncodeIfHasData(persist, storageKey, data) {
+ try {
+ if (hasData(data)) {
+ var dataString = _.JSONEncode(data);
+ persist(storageKey, dataString);
}
+ } catch (err) {
+ logger$4.error('failed to decode campaign data');
+ logger$4.error(err);
}
-
- return result;
}
- function getCampaignData(persist, opt) {
- var storedCampaignData = null;
- var storedCampaignString = null;
+ function getAndDecode(storageKey, opt) {
try {
- storedCampaignString = getFromPersistence(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, opt);
- if (storedCampaignString && storedCampaignString !== 'null') {
- storedCampaignData = _.JSONDecode(storedCampaignString);
+ var stringVal = getFromPersistence(storageKey, opt);
+ if (stringVal && stringVal !== 'null') {
+ var data = _.JSONDecode(stringVal);
+ if (hasData(data)) {
+ return data;
+ }
+ return null;
}
} catch (err) {
- logger$4.error('failed to decode campaign data ' + storedCampaignString);
+ logger$4.error('failed to persist campaign data');
logger$4.error(err);
+ return null;
}
+ }
- var currentCampaignData = getCampaignDataFromUrlOrCookie(opt);
- logger$4.log('current campaignData');
- logger$4.log(_.JSONEncode(currentCampaignData));
+ function storeForOneEntityIfNotSavedYet(
+ persist,
+ opt,
+ entityStorageKey,
+ currentCampaignData
+ ) {
+ var storedData = getAndDecode(entityStorageKey, opt);
+ if (!storedData && persist) {
+ // no stored data thus store current.
+ saveEncodeIfHasData(persist, entityStorageKey, currentCampaignData);
+ }
+ }
- var merged = mergeCampaignData(storedCampaignData, currentCampaignData);
- logger$4.log('merged campaignData');
- logger$4.log(_.JSONEncode(merged));
+ // this stores Campaign data if not saved yet.
+ function storeCampaignDataIfNeeded(persist, opt, currentCampaignData) {
+ storeForOneEntityIfNotSavedYet(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, currentCampaignData);
+ storeForOneEntityIfNotSavedYet(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, currentCampaignData);
+ }
- try {
- if (persist && merged && !_.isEmptyObject(merged)) {
- var mergedString = _.JSONEncode(merged);
- persist(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, mergedString);
-
- // UTM_SOURCE exists means that merged campaign info have data.
- if (!storedCampaignData && merged[UTMConstants.UTM_SOURCE]) {
- // first time we persist campaign data, and thus persis the initial data until identifyCompany is called
- persist(STORAGE_CONSTANTS.STORED_INITIAL_CAMPAIGN_DATA, mergedString);
- }
+ function popStoredCampaignData(persist, opt, storageKey) {
+ var storedCampaignData = getAndDecode(storageKey, opt);
+
+ if (storedCampaignData) {
+ // let's delete it
+ // we know we will use it.
+ // so next one can overridee
+ try {
+ persist(storageKey, '');
+ } catch (err) {
+ logger$4.error('failed to clear campaign data');
}
- } catch (err) {
- logger$4.error('failed to persist campaign data');
- logger$4.error(err);
}
+ return storedCampaignData;
+ }
- return merged;
+ function popStoredCampaignDataForUser(persist, opt) {
+ return popStoredCampaignData(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER);
+ }
+
+ function popStoredCampaignDataForCompany(persist, opt) {
+ return popStoredCampaignData(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY);
}
// eslint-disable-line
@@ -3434,16 +3436,22 @@ define(function () { 'use strict';
this._session = getFromPersistence(STORAGE_CONSTANTS.STORED_SESSION_ID, ops);
this._companyId = getFromPersistence(STORAGE_CONSTANTS.STORED_COMPANY_ID, ops);
this._anonymousId = getAnonymousId(this._persist, ops);
- this._campaign = getCampaignData(this._persist, ops);
+ this._currentCampaign = getCampaignDataFromUrlOrCookie(ops);
+
+ if (this._currentCampaign) {
+ storeCampaignDataIfNeeded(this._persist, ops, this._currentCampaign);
+ }
+
+ // this._campaign = getCampaignData(this._persist, ops);
// try to save campaign data on anonymous id
// if there is no userId saved, means it is still anonymous.
// later on, when identifyUser is called with real user id,
// the campaigne data will be resent with that again.
- if (this._campaign && !this._userId) {
+ if (this._currentCampaign && !this._userId) {
var anonUserObject = {};
anonUserObject['anonymous_id'] = this._anonymousId;
- anonUserObject['campaign'] = this._campaign;
+ anonUserObject['campaign'] = this._currentCampaign;
this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback);
}
} catch(err) {
@@ -3701,8 +3709,10 @@ define(function () { 'use strict';
userObject['session_token'] = this._session;
}
- if (this._campaign) {
- userObject['campaign'] = this._campaign;
+ var campaignData = popStoredCampaignDataForUser(this._persist, this._options) || this._currentCampaign;
+
+ if (campaignData) {
+ userObject['campaign'] = campaignData;
}
if (this._companyId) {
@@ -3734,8 +3744,6 @@ define(function () { 'use strict';
return;
}
- var hasCompanyIdentifiedBefore = !!this._companyId;
-
this._companyId = companyId;
if (!(this._options && this._options.applicationId)) {
throw new Error('Init needs to be called with a valid application Id before calling identify User.');
@@ -3755,9 +3763,7 @@ define(function () { 'use strict';
companyObject['session_token'] = this._session;
}
- var campaignData = hasCompanyIdentifiedBefore
- ? this._campaign
- : getStoredInitialCampaignData(this._options) || this._campaign;
+ var campaignData = popStoredCampaignDataForCompany(this._persist, this._options) || this._currentCampaign;
if (campaignData) {
companyObject['campaign'] = campaignData;
@@ -3934,7 +3940,7 @@ define(function () { 'use strict';
this._companyId = null;
this._userId = null;
this._session = null;
- this._campaign = null;
+ this._currentCampaign = null;
}
};
}
diff --git a/build/moesif.cjs.js b/build/moesif.cjs.js
index a686e88..fa1d810 100644
--- a/build/moesif.cjs.js
+++ b/build/moesif.cjs.js
@@ -2,7 +2,7 @@
var Config = {
DEBUG: false,
- LIB_VERSION: '1.8.12'
+ LIB_VERSION: '1.8.13'
};
// since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file
@@ -2437,8 +2437,8 @@ var STORAGE_CONSTANTS = {
STORED_COMPANY_ID: 'moesif_stored_company_id',
STORED_SESSION_ID: 'moesif_stored_session_id',
STORED_ANONYMOUS_ID: 'moesif_anonymous_id',
- STORED_CAMPAIGN_DATA: 'moesif_campaign_data',
- STORED_INITIAL_CAMPAIGN_DATA: 'moesif_initial_campaign'
+ STORED_CAMPAIGN_DATA_USER: 'moesif_campaign_data',
+ STORED_CAMPAIGN_DATA_COMPANY: 'moesif_campaign_company'
};
function replacePrefix(key, prefix) {
@@ -2530,7 +2530,10 @@ function clearCookies(opt) {
_.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_ANONYMOUS_ID, prefix));
_.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_SESSION_ID, prefix));
_.cookie.remove(
- replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, prefix)
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, prefix)
+ );
+ _.cookie.remove(
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, prefix)
);
}
@@ -2549,7 +2552,10 @@ function clearLocalStorage(opt) {
replacePrefix(STORAGE_CONSTANTS.STORED_SESSION_ID, prefix)
);
_.localStorage.remove(
- replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, prefix)
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, prefix)
+ );
+ _.localStorage.remove(
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, prefix)
);
}
@@ -2591,87 +2597,83 @@ function getCampaignDataFromUrlOrCookie(opt) {
}
}
-// since identify company can happen a lot later
-// than initial anonymous users
-// persist the very initial campaign data for
-// companies until company is identified.
-function getStoredInitialCampaignData(opt) {
- var storedCampaignData = null;
- var storedCampaignString = null;
- try {
- storedCampaignString = getFromPersistence(STORAGE_CONSTANTS.STORED_INITIAL_CAMPAIGN_DATA, opt);
- if (storedCampaignString) {
- storedCampaignData = _.JSONDecode(storedCampaignString);
- }
- } catch (err) {
- logger$4.error('failed to decode company campaign data ' + storedCampaignString);
- logger$4.error(err);
+function hasData(data) {
+ if (data && !_.isEmptyObject(data)) {
+ return true;
}
-
- return storedCampaignData;
+ return false;
}
-function mergeCampaignData(saved, current) {
- if (!current) {
- return saved;
- }
-
- if (!saved) {
- return current;
- }
-
- var result = _.extend({}, saved, current);
-
- // if utm source exists.
- // every field of UTM will be override to be
- // consistent.
- if (current && current[UTMConstants.UTM_SOURCE]) {
- for (var prop in UTMConstants) {
- result[UTMConstants[prop]] = current[UTMConstants[prop]];
+function saveEncodeIfHasData(persist, storageKey, data) {
+ try {
+ if (hasData(data)) {
+ var dataString = _.JSONEncode(data);
+ persist(storageKey, dataString);
}
+ } catch (err) {
+ logger$4.error('failed to decode campaign data');
+ logger$4.error(err);
}
-
- return result;
}
-function getCampaignData(persist, opt) {
- var storedCampaignData = null;
- var storedCampaignString = null;
+function getAndDecode(storageKey, opt) {
try {
- storedCampaignString = getFromPersistence(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, opt);
- if (storedCampaignString && storedCampaignString !== 'null') {
- storedCampaignData = _.JSONDecode(storedCampaignString);
+ var stringVal = getFromPersistence(storageKey, opt);
+ if (stringVal && stringVal !== 'null') {
+ var data = _.JSONDecode(stringVal);
+ if (hasData(data)) {
+ return data;
+ }
+ return null;
}
} catch (err) {
- logger$4.error('failed to decode campaign data ' + storedCampaignString);
+ logger$4.error('failed to persist campaign data');
logger$4.error(err);
+ return null;
}
+}
- var currentCampaignData = getCampaignDataFromUrlOrCookie(opt);
- logger$4.log('current campaignData');
- logger$4.log(_.JSONEncode(currentCampaignData));
+function storeForOneEntityIfNotSavedYet(
+ persist,
+ opt,
+ entityStorageKey,
+ currentCampaignData
+) {
+ var storedData = getAndDecode(entityStorageKey, opt);
+ if (!storedData && persist) {
+ // no stored data thus store current.
+ saveEncodeIfHasData(persist, entityStorageKey, currentCampaignData);
+ }
+}
- var merged = mergeCampaignData(storedCampaignData, currentCampaignData);
- logger$4.log('merged campaignData');
- logger$4.log(_.JSONEncode(merged));
+// this stores Campaign data if not saved yet.
+function storeCampaignDataIfNeeded(persist, opt, currentCampaignData) {
+ storeForOneEntityIfNotSavedYet(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, currentCampaignData);
+ storeForOneEntityIfNotSavedYet(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, currentCampaignData);
+}
- try {
- if (persist && merged && !_.isEmptyObject(merged)) {
- var mergedString = _.JSONEncode(merged);
- persist(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, mergedString);
-
- // UTM_SOURCE exists means that merged campaign info have data.
- if (!storedCampaignData && merged[UTMConstants.UTM_SOURCE]) {
- // first time we persist campaign data, and thus persis the initial data until identifyCompany is called
- persist(STORAGE_CONSTANTS.STORED_INITIAL_CAMPAIGN_DATA, mergedString);
- }
+function popStoredCampaignData(persist, opt, storageKey) {
+ var storedCampaignData = getAndDecode(storageKey, opt);
+
+ if (storedCampaignData) {
+ // let's delete it
+ // we know we will use it.
+ // so next one can overridee
+ try {
+ persist(storageKey, '');
+ } catch (err) {
+ logger$4.error('failed to clear campaign data');
}
- } catch (err) {
- logger$4.error('failed to persist campaign data');
- logger$4.error(err);
}
+ return storedCampaignData;
+}
- return merged;
+function popStoredCampaignDataForUser(persist, opt) {
+ return popStoredCampaignData(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER);
+}
+
+function popStoredCampaignDataForCompany(persist, opt) {
+ return popStoredCampaignData(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY);
}
// eslint-disable-line
@@ -3434,16 +3436,22 @@ function moesifCreator () {
this._session = getFromPersistence(STORAGE_CONSTANTS.STORED_SESSION_ID, ops);
this._companyId = getFromPersistence(STORAGE_CONSTANTS.STORED_COMPANY_ID, ops);
this._anonymousId = getAnonymousId(this._persist, ops);
- this._campaign = getCampaignData(this._persist, ops);
+ this._currentCampaign = getCampaignDataFromUrlOrCookie(ops);
+
+ if (this._currentCampaign) {
+ storeCampaignDataIfNeeded(this._persist, ops, this._currentCampaign);
+ }
+
+ // this._campaign = getCampaignData(this._persist, ops);
// try to save campaign data on anonymous id
// if there is no userId saved, means it is still anonymous.
// later on, when identifyUser is called with real user id,
// the campaigne data will be resent with that again.
- if (this._campaign && !this._userId) {
+ if (this._currentCampaign && !this._userId) {
var anonUserObject = {};
anonUserObject['anonymous_id'] = this._anonymousId;
- anonUserObject['campaign'] = this._campaign;
+ anonUserObject['campaign'] = this._currentCampaign;
this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback);
}
} catch(err) {
@@ -3701,8 +3709,10 @@ function moesifCreator () {
userObject['session_token'] = this._session;
}
- if (this._campaign) {
- userObject['campaign'] = this._campaign;
+ var campaignData = popStoredCampaignDataForUser(this._persist, this._options) || this._currentCampaign;
+
+ if (campaignData) {
+ userObject['campaign'] = campaignData;
}
if (this._companyId) {
@@ -3734,8 +3744,6 @@ function moesifCreator () {
return;
}
- var hasCompanyIdentifiedBefore = !!this._companyId;
-
this._companyId = companyId;
if (!(this._options && this._options.applicationId)) {
throw new Error('Init needs to be called with a valid application Id before calling identify User.');
@@ -3755,9 +3763,7 @@ function moesifCreator () {
companyObject['session_token'] = this._session;
}
- var campaignData = hasCompanyIdentifiedBefore
- ? this._campaign
- : getStoredInitialCampaignData(this._options) || this._campaign;
+ var campaignData = popStoredCampaignDataForCompany(this._persist, this._options) || this._currentCampaign;
if (campaignData) {
companyObject['campaign'] = campaignData;
@@ -3934,7 +3940,7 @@ function moesifCreator () {
this._companyId = null;
this._userId = null;
this._session = null;
- this._campaign = null;
+ this._currentCampaign = null;
}
};
}
diff --git a/build/moesif.globals.js b/build/moesif.globals.js
index c98ea66..c84cbbe 100644
--- a/build/moesif.globals.js
+++ b/build/moesif.globals.js
@@ -3,7 +3,7 @@
var Config = {
DEBUG: false,
- LIB_VERSION: '1.8.12'
+ LIB_VERSION: '1.8.13'
};
// since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file
@@ -2438,8 +2438,8 @@
STORED_COMPANY_ID: 'moesif_stored_company_id',
STORED_SESSION_ID: 'moesif_stored_session_id',
STORED_ANONYMOUS_ID: 'moesif_anonymous_id',
- STORED_CAMPAIGN_DATA: 'moesif_campaign_data',
- STORED_INITIAL_CAMPAIGN_DATA: 'moesif_initial_campaign'
+ STORED_CAMPAIGN_DATA_USER: 'moesif_campaign_data',
+ STORED_CAMPAIGN_DATA_COMPANY: 'moesif_campaign_company'
};
function replacePrefix(key, prefix) {
@@ -2531,7 +2531,10 @@
_.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_ANONYMOUS_ID, prefix));
_.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_SESSION_ID, prefix));
_.cookie.remove(
- replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, prefix)
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, prefix)
+ );
+ _.cookie.remove(
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, prefix)
);
}
@@ -2550,7 +2553,10 @@
replacePrefix(STORAGE_CONSTANTS.STORED_SESSION_ID, prefix)
);
_.localStorage.remove(
- replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, prefix)
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, prefix)
+ );
+ _.localStorage.remove(
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, prefix)
);
}
@@ -2592,87 +2598,83 @@
}
}
- // since identify company can happen a lot later
- // than initial anonymous users
- // persist the very initial campaign data for
- // companies until company is identified.
- function getStoredInitialCampaignData(opt) {
- var storedCampaignData = null;
- var storedCampaignString = null;
- try {
- storedCampaignString = getFromPersistence(STORAGE_CONSTANTS.STORED_INITIAL_CAMPAIGN_DATA, opt);
- if (storedCampaignString) {
- storedCampaignData = _.JSONDecode(storedCampaignString);
- }
- } catch (err) {
- logger$4.error('failed to decode company campaign data ' + storedCampaignString);
- logger$4.error(err);
+ function hasData(data) {
+ if (data && !_.isEmptyObject(data)) {
+ return true;
}
-
- return storedCampaignData;
+ return false;
}
- function mergeCampaignData(saved, current) {
- if (!current) {
- return saved;
- }
-
- if (!saved) {
- return current;
- }
-
- var result = _.extend({}, saved, current);
-
- // if utm source exists.
- // every field of UTM will be override to be
- // consistent.
- if (current && current[UTMConstants.UTM_SOURCE]) {
- for (var prop in UTMConstants) {
- result[UTMConstants[prop]] = current[UTMConstants[prop]];
+ function saveEncodeIfHasData(persist, storageKey, data) {
+ try {
+ if (hasData(data)) {
+ var dataString = _.JSONEncode(data);
+ persist(storageKey, dataString);
}
+ } catch (err) {
+ logger$4.error('failed to decode campaign data');
+ logger$4.error(err);
}
-
- return result;
}
- function getCampaignData(persist, opt) {
- var storedCampaignData = null;
- var storedCampaignString = null;
+ function getAndDecode(storageKey, opt) {
try {
- storedCampaignString = getFromPersistence(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, opt);
- if (storedCampaignString && storedCampaignString !== 'null') {
- storedCampaignData = _.JSONDecode(storedCampaignString);
+ var stringVal = getFromPersistence(storageKey, opt);
+ if (stringVal && stringVal !== 'null') {
+ var data = _.JSONDecode(stringVal);
+ if (hasData(data)) {
+ return data;
+ }
+ return null;
}
} catch (err) {
- logger$4.error('failed to decode campaign data ' + storedCampaignString);
+ logger$4.error('failed to persist campaign data');
logger$4.error(err);
+ return null;
}
+ }
- var currentCampaignData = getCampaignDataFromUrlOrCookie(opt);
- logger$4.log('current campaignData');
- logger$4.log(_.JSONEncode(currentCampaignData));
+ function storeForOneEntityIfNotSavedYet(
+ persist,
+ opt,
+ entityStorageKey,
+ currentCampaignData
+ ) {
+ var storedData = getAndDecode(entityStorageKey, opt);
+ if (!storedData && persist) {
+ // no stored data thus store current.
+ saveEncodeIfHasData(persist, entityStorageKey, currentCampaignData);
+ }
+ }
- var merged = mergeCampaignData(storedCampaignData, currentCampaignData);
- logger$4.log('merged campaignData');
- logger$4.log(_.JSONEncode(merged));
+ // this stores Campaign data if not saved yet.
+ function storeCampaignDataIfNeeded(persist, opt, currentCampaignData) {
+ storeForOneEntityIfNotSavedYet(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, currentCampaignData);
+ storeForOneEntityIfNotSavedYet(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, currentCampaignData);
+ }
- try {
- if (persist && merged && !_.isEmptyObject(merged)) {
- var mergedString = _.JSONEncode(merged);
- persist(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, mergedString);
-
- // UTM_SOURCE exists means that merged campaign info have data.
- if (!storedCampaignData && merged[UTMConstants.UTM_SOURCE]) {
- // first time we persist campaign data, and thus persis the initial data until identifyCompany is called
- persist(STORAGE_CONSTANTS.STORED_INITIAL_CAMPAIGN_DATA, mergedString);
- }
+ function popStoredCampaignData(persist, opt, storageKey) {
+ var storedCampaignData = getAndDecode(storageKey, opt);
+
+ if (storedCampaignData) {
+ // let's delete it
+ // we know we will use it.
+ // so next one can overridee
+ try {
+ persist(storageKey, '');
+ } catch (err) {
+ logger$4.error('failed to clear campaign data');
}
- } catch (err) {
- logger$4.error('failed to persist campaign data');
- logger$4.error(err);
}
+ return storedCampaignData;
+ }
- return merged;
+ function popStoredCampaignDataForUser(persist, opt) {
+ return popStoredCampaignData(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER);
+ }
+
+ function popStoredCampaignDataForCompany(persist, opt) {
+ return popStoredCampaignData(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY);
}
// eslint-disable-line
@@ -3435,16 +3437,22 @@
this._session = getFromPersistence(STORAGE_CONSTANTS.STORED_SESSION_ID, ops);
this._companyId = getFromPersistence(STORAGE_CONSTANTS.STORED_COMPANY_ID, ops);
this._anonymousId = getAnonymousId(this._persist, ops);
- this._campaign = getCampaignData(this._persist, ops);
+ this._currentCampaign = getCampaignDataFromUrlOrCookie(ops);
+
+ if (this._currentCampaign) {
+ storeCampaignDataIfNeeded(this._persist, ops, this._currentCampaign);
+ }
+
+ // this._campaign = getCampaignData(this._persist, ops);
// try to save campaign data on anonymous id
// if there is no userId saved, means it is still anonymous.
// later on, when identifyUser is called with real user id,
// the campaigne data will be resent with that again.
- if (this._campaign && !this._userId) {
+ if (this._currentCampaign && !this._userId) {
var anonUserObject = {};
anonUserObject['anonymous_id'] = this._anonymousId;
- anonUserObject['campaign'] = this._campaign;
+ anonUserObject['campaign'] = this._currentCampaign;
this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback);
}
} catch(err) {
@@ -3702,8 +3710,10 @@
userObject['session_token'] = this._session;
}
- if (this._campaign) {
- userObject['campaign'] = this._campaign;
+ var campaignData = popStoredCampaignDataForUser(this._persist, this._options) || this._currentCampaign;
+
+ if (campaignData) {
+ userObject['campaign'] = campaignData;
}
if (this._companyId) {
@@ -3735,8 +3745,6 @@
return;
}
- var hasCompanyIdentifiedBefore = !!this._companyId;
-
this._companyId = companyId;
if (!(this._options && this._options.applicationId)) {
throw new Error('Init needs to be called with a valid application Id before calling identify User.');
@@ -3756,9 +3764,7 @@
companyObject['session_token'] = this._session;
}
- var campaignData = hasCompanyIdentifiedBefore
- ? this._campaign
- : getStoredInitialCampaignData(this._options) || this._campaign;
+ var campaignData = popStoredCampaignDataForCompany(this._persist, this._options) || this._currentCampaign;
if (campaignData) {
companyObject['campaign'] = campaignData;
@@ -3935,7 +3941,7 @@
this._companyId = null;
this._userId = null;
this._session = null;
- this._campaign = null;
+ this._currentCampaign = null;
}
};
}
diff --git a/build/moesif.umd.js b/build/moesif.umd.js
index 0ddd9d0..6e003c0 100644
--- a/build/moesif.umd.js
+++ b/build/moesif.umd.js
@@ -6,7 +6,7 @@
var Config = {
DEBUG: false,
- LIB_VERSION: '1.8.12'
+ LIB_VERSION: '1.8.13'
};
// since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file
@@ -2441,8 +2441,8 @@
STORED_COMPANY_ID: 'moesif_stored_company_id',
STORED_SESSION_ID: 'moesif_stored_session_id',
STORED_ANONYMOUS_ID: 'moesif_anonymous_id',
- STORED_CAMPAIGN_DATA: 'moesif_campaign_data',
- STORED_INITIAL_CAMPAIGN_DATA: 'moesif_initial_campaign'
+ STORED_CAMPAIGN_DATA_USER: 'moesif_campaign_data',
+ STORED_CAMPAIGN_DATA_COMPANY: 'moesif_campaign_company'
};
function replacePrefix(key, prefix) {
@@ -2534,7 +2534,10 @@
_.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_ANONYMOUS_ID, prefix));
_.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_SESSION_ID, prefix));
_.cookie.remove(
- replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, prefix)
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, prefix)
+ );
+ _.cookie.remove(
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, prefix)
);
}
@@ -2553,7 +2556,10 @@
replacePrefix(STORAGE_CONSTANTS.STORED_SESSION_ID, prefix)
);
_.localStorage.remove(
- replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, prefix)
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, prefix)
+ );
+ _.localStorage.remove(
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, prefix)
);
}
@@ -2595,87 +2601,83 @@
}
}
- // since identify company can happen a lot later
- // than initial anonymous users
- // persist the very initial campaign data for
- // companies until company is identified.
- function getStoredInitialCampaignData(opt) {
- var storedCampaignData = null;
- var storedCampaignString = null;
- try {
- storedCampaignString = getFromPersistence(STORAGE_CONSTANTS.STORED_INITIAL_CAMPAIGN_DATA, opt);
- if (storedCampaignString) {
- storedCampaignData = _.JSONDecode(storedCampaignString);
- }
- } catch (err) {
- logger$4.error('failed to decode company campaign data ' + storedCampaignString);
- logger$4.error(err);
+ function hasData(data) {
+ if (data && !_.isEmptyObject(data)) {
+ return true;
}
-
- return storedCampaignData;
+ return false;
}
- function mergeCampaignData(saved, current) {
- if (!current) {
- return saved;
- }
-
- if (!saved) {
- return current;
- }
-
- var result = _.extend({}, saved, current);
-
- // if utm source exists.
- // every field of UTM will be override to be
- // consistent.
- if (current && current[UTMConstants.UTM_SOURCE]) {
- for (var prop in UTMConstants) {
- result[UTMConstants[prop]] = current[UTMConstants[prop]];
+ function saveEncodeIfHasData(persist, storageKey, data) {
+ try {
+ if (hasData(data)) {
+ var dataString = _.JSONEncode(data);
+ persist(storageKey, dataString);
}
+ } catch (err) {
+ logger$4.error('failed to decode campaign data');
+ logger$4.error(err);
}
-
- return result;
}
- function getCampaignData(persist, opt) {
- var storedCampaignData = null;
- var storedCampaignString = null;
+ function getAndDecode(storageKey, opt) {
try {
- storedCampaignString = getFromPersistence(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, opt);
- if (storedCampaignString && storedCampaignString !== 'null') {
- storedCampaignData = _.JSONDecode(storedCampaignString);
+ var stringVal = getFromPersistence(storageKey, opt);
+ if (stringVal && stringVal !== 'null') {
+ var data = _.JSONDecode(stringVal);
+ if (hasData(data)) {
+ return data;
+ }
+ return null;
}
} catch (err) {
- logger$4.error('failed to decode campaign data ' + storedCampaignString);
+ logger$4.error('failed to persist campaign data');
logger$4.error(err);
+ return null;
}
+ }
- var currentCampaignData = getCampaignDataFromUrlOrCookie(opt);
- logger$4.log('current campaignData');
- logger$4.log(_.JSONEncode(currentCampaignData));
+ function storeForOneEntityIfNotSavedYet(
+ persist,
+ opt,
+ entityStorageKey,
+ currentCampaignData
+ ) {
+ var storedData = getAndDecode(entityStorageKey, opt);
+ if (!storedData && persist) {
+ // no stored data thus store current.
+ saveEncodeIfHasData(persist, entityStorageKey, currentCampaignData);
+ }
+ }
- var merged = mergeCampaignData(storedCampaignData, currentCampaignData);
- logger$4.log('merged campaignData');
- logger$4.log(_.JSONEncode(merged));
+ // this stores Campaign data if not saved yet.
+ function storeCampaignDataIfNeeded(persist, opt, currentCampaignData) {
+ storeForOneEntityIfNotSavedYet(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, currentCampaignData);
+ storeForOneEntityIfNotSavedYet(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, currentCampaignData);
+ }
- try {
- if (persist && merged && !_.isEmptyObject(merged)) {
- var mergedString = _.JSONEncode(merged);
- persist(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, mergedString);
-
- // UTM_SOURCE exists means that merged campaign info have data.
- if (!storedCampaignData && merged[UTMConstants.UTM_SOURCE]) {
- // first time we persist campaign data, and thus persis the initial data until identifyCompany is called
- persist(STORAGE_CONSTANTS.STORED_INITIAL_CAMPAIGN_DATA, mergedString);
- }
+ function popStoredCampaignData(persist, opt, storageKey) {
+ var storedCampaignData = getAndDecode(storageKey, opt);
+
+ if (storedCampaignData) {
+ // let's delete it
+ // we know we will use it.
+ // so next one can overridee
+ try {
+ persist(storageKey, '');
+ } catch (err) {
+ logger$4.error('failed to clear campaign data');
}
- } catch (err) {
- logger$4.error('failed to persist campaign data');
- logger$4.error(err);
}
+ return storedCampaignData;
+ }
- return merged;
+ function popStoredCampaignDataForUser(persist, opt) {
+ return popStoredCampaignData(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER);
+ }
+
+ function popStoredCampaignDataForCompany(persist, opt) {
+ return popStoredCampaignData(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY);
}
// eslint-disable-line
@@ -3438,16 +3440,22 @@
this._session = getFromPersistence(STORAGE_CONSTANTS.STORED_SESSION_ID, ops);
this._companyId = getFromPersistence(STORAGE_CONSTANTS.STORED_COMPANY_ID, ops);
this._anonymousId = getAnonymousId(this._persist, ops);
- this._campaign = getCampaignData(this._persist, ops);
+ this._currentCampaign = getCampaignDataFromUrlOrCookie(ops);
+
+ if (this._currentCampaign) {
+ storeCampaignDataIfNeeded(this._persist, ops, this._currentCampaign);
+ }
+
+ // this._campaign = getCampaignData(this._persist, ops);
// try to save campaign data on anonymous id
// if there is no userId saved, means it is still anonymous.
// later on, when identifyUser is called with real user id,
// the campaigne data will be resent with that again.
- if (this._campaign && !this._userId) {
+ if (this._currentCampaign && !this._userId) {
var anonUserObject = {};
anonUserObject['anonymous_id'] = this._anonymousId;
- anonUserObject['campaign'] = this._campaign;
+ anonUserObject['campaign'] = this._currentCampaign;
this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback);
}
} catch(err) {
@@ -3705,8 +3713,10 @@
userObject['session_token'] = this._session;
}
- if (this._campaign) {
- userObject['campaign'] = this._campaign;
+ var campaignData = popStoredCampaignDataForUser(this._persist, this._options) || this._currentCampaign;
+
+ if (campaignData) {
+ userObject['campaign'] = campaignData;
}
if (this._companyId) {
@@ -3738,8 +3748,6 @@
return;
}
- var hasCompanyIdentifiedBefore = !!this._companyId;
-
this._companyId = companyId;
if (!(this._options && this._options.applicationId)) {
throw new Error('Init needs to be called with a valid application Id before calling identify User.');
@@ -3759,9 +3767,7 @@
companyObject['session_token'] = this._session;
}
- var campaignData = hasCompanyIdentifiedBefore
- ? this._campaign
- : getStoredInitialCampaignData(this._options) || this._campaign;
+ var campaignData = popStoredCampaignDataForCompany(this._persist, this._options) || this._currentCampaign;
if (campaignData) {
companyObject['campaign'] = campaignData;
@@ -3938,7 +3944,7 @@
this._companyId = null;
this._userId = null;
this._session = null;
- this._campaign = null;
+ this._currentCampaign = null;
}
};
}
diff --git a/examples/commonjs-browserify/bundle.js b/examples/commonjs-browserify/bundle.js
index 9b62d42..6e2e6cd 100644
--- a/examples/commonjs-browserify/bundle.js
+++ b/examples/commonjs-browserify/bundle.js
@@ -3,7 +3,7 @@
var Config = {
DEBUG: false,
- LIB_VERSION: '1.8.12'
+ LIB_VERSION: '1.8.13'
};
// since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file
@@ -2438,8 +2438,8 @@ var STORAGE_CONSTANTS = {
STORED_COMPANY_ID: 'moesif_stored_company_id',
STORED_SESSION_ID: 'moesif_stored_session_id',
STORED_ANONYMOUS_ID: 'moesif_anonymous_id',
- STORED_CAMPAIGN_DATA: 'moesif_campaign_data',
- STORED_INITIAL_CAMPAIGN_DATA: 'moesif_initial_campaign'
+ STORED_CAMPAIGN_DATA_USER: 'moesif_campaign_data',
+ STORED_CAMPAIGN_DATA_COMPANY: 'moesif_campaign_company'
};
function replacePrefix(key, prefix) {
@@ -2531,7 +2531,10 @@ function clearCookies(opt) {
_.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_ANONYMOUS_ID, prefix));
_.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_SESSION_ID, prefix));
_.cookie.remove(
- replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, prefix)
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, prefix)
+ );
+ _.cookie.remove(
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, prefix)
);
}
@@ -2550,7 +2553,10 @@ function clearLocalStorage(opt) {
replacePrefix(STORAGE_CONSTANTS.STORED_SESSION_ID, prefix)
);
_.localStorage.remove(
- replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, prefix)
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, prefix)
+ );
+ _.localStorage.remove(
+ replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, prefix)
);
}
@@ -2592,87 +2598,83 @@ function getCampaignDataFromUrlOrCookie(opt) {
}
}
-// since identify company can happen a lot later
-// than initial anonymous users
-// persist the very initial campaign data for
-// companies until company is identified.
-function getStoredInitialCampaignData(opt) {
- var storedCampaignData = null;
- var storedCampaignString = null;
- try {
- storedCampaignString = getFromPersistence(STORAGE_CONSTANTS.STORED_INITIAL_CAMPAIGN_DATA, opt);
- if (storedCampaignString) {
- storedCampaignData = _.JSONDecode(storedCampaignString);
- }
- } catch (err) {
- logger$4.error('failed to decode company campaign data ' + storedCampaignString);
- logger$4.error(err);
+function hasData(data) {
+ if (data && !_.isEmptyObject(data)) {
+ return true;
}
-
- return storedCampaignData;
+ return false;
}
-function mergeCampaignData(saved, current) {
- if (!current) {
- return saved;
- }
-
- if (!saved) {
- return current;
- }
-
- var result = _.extend({}, saved, current);
-
- // if utm source exists.
- // every field of UTM will be override to be
- // consistent.
- if (current && current[UTMConstants.UTM_SOURCE]) {
- for (var prop in UTMConstants) {
- result[UTMConstants[prop]] = current[UTMConstants[prop]];
+function saveEncodeIfHasData(persist, storageKey, data) {
+ try {
+ if (hasData(data)) {
+ var dataString = _.JSONEncode(data);
+ persist(storageKey, dataString);
}
+ } catch (err) {
+ logger$4.error('failed to decode campaign data');
+ logger$4.error(err);
}
-
- return result;
}
-function getCampaignData(persist, opt) {
- var storedCampaignData = null;
- var storedCampaignString = null;
+function getAndDecode(storageKey, opt) {
try {
- storedCampaignString = getFromPersistence(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, opt);
- if (storedCampaignString && storedCampaignString !== 'null') {
- storedCampaignData = _.JSONDecode(storedCampaignString);
+ var stringVal = getFromPersistence(storageKey, opt);
+ if (stringVal && stringVal !== 'null') {
+ var data = _.JSONDecode(stringVal);
+ if (hasData(data)) {
+ return data;
+ }
+ return null;
}
} catch (err) {
- logger$4.error('failed to decode campaign data ' + storedCampaignString);
+ logger$4.error('failed to persist campaign data');
logger$4.error(err);
+ return null;
}
+}
- var currentCampaignData = getCampaignDataFromUrlOrCookie(opt);
- logger$4.log('current campaignData');
- logger$4.log(_.JSONEncode(currentCampaignData));
+function storeForOneEntityIfNotSavedYet(
+ persist,
+ opt,
+ entityStorageKey,
+ currentCampaignData
+) {
+ var storedData = getAndDecode(entityStorageKey, opt);
+ if (!storedData && persist) {
+ // no stored data thus store current.
+ saveEncodeIfHasData(persist, entityStorageKey, currentCampaignData);
+ }
+}
- var merged = mergeCampaignData(storedCampaignData, currentCampaignData);
- logger$4.log('merged campaignData');
- logger$4.log(_.JSONEncode(merged));
+// this stores Campaign data if not saved yet.
+function storeCampaignDataIfNeeded(persist, opt, currentCampaignData) {
+ storeForOneEntityIfNotSavedYet(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, currentCampaignData);
+ storeForOneEntityIfNotSavedYet(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, currentCampaignData);
+}
- try {
- if (persist && merged && !_.isEmptyObject(merged)) {
- var mergedString = _.JSONEncode(merged);
- persist(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, mergedString);
-
- // UTM_SOURCE exists means that merged campaign info have data.
- if (!storedCampaignData && merged[UTMConstants.UTM_SOURCE]) {
- // first time we persist campaign data, and thus persis the initial data until identifyCompany is called
- persist(STORAGE_CONSTANTS.STORED_INITIAL_CAMPAIGN_DATA, mergedString);
- }
+function popStoredCampaignData(persist, opt, storageKey) {
+ var storedCampaignData = getAndDecode(storageKey, opt);
+
+ if (storedCampaignData) {
+ // let's delete it
+ // we know we will use it.
+ // so next one can overridee
+ try {
+ persist(storageKey, '');
+ } catch (err) {
+ logger$4.error('failed to clear campaign data');
}
- } catch (err) {
- logger$4.error('failed to persist campaign data');
- logger$4.error(err);
}
+ return storedCampaignData;
+}
- return merged;
+function popStoredCampaignDataForUser(persist, opt) {
+ return popStoredCampaignData(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER);
+}
+
+function popStoredCampaignDataForCompany(persist, opt) {
+ return popStoredCampaignData(persist, opt, STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY);
}
// eslint-disable-line
@@ -3435,16 +3437,22 @@ function moesifCreator () {
this._session = getFromPersistence(STORAGE_CONSTANTS.STORED_SESSION_ID, ops);
this._companyId = getFromPersistence(STORAGE_CONSTANTS.STORED_COMPANY_ID, ops);
this._anonymousId = getAnonymousId(this._persist, ops);
- this._campaign = getCampaignData(this._persist, ops);
+ this._currentCampaign = getCampaignDataFromUrlOrCookie(ops);
+
+ if (this._currentCampaign) {
+ storeCampaignDataIfNeeded(this._persist, ops, this._currentCampaign);
+ }
+
+ // this._campaign = getCampaignData(this._persist, ops);
// try to save campaign data on anonymous id
// if there is no userId saved, means it is still anonymous.
// later on, when identifyUser is called with real user id,
// the campaigne data will be resent with that again.
- if (this._campaign && !this._userId) {
+ if (this._currentCampaign && !this._userId) {
var anonUserObject = {};
anonUserObject['anonymous_id'] = this._anonymousId;
- anonUserObject['campaign'] = this._campaign;
+ anonUserObject['campaign'] = this._currentCampaign;
this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback);
}
} catch(err) {
@@ -3702,8 +3710,10 @@ function moesifCreator () {
userObject['session_token'] = this._session;
}
- if (this._campaign) {
- userObject['campaign'] = this._campaign;
+ var campaignData = popStoredCampaignDataForUser(this._persist, this._options) || this._currentCampaign;
+
+ if (campaignData) {
+ userObject['campaign'] = campaignData;
}
if (this._companyId) {
@@ -3735,8 +3745,6 @@ function moesifCreator () {
return;
}
- var hasCompanyIdentifiedBefore = !!this._companyId;
-
this._companyId = companyId;
if (!(this._options && this._options.applicationId)) {
throw new Error('Init needs to be called with a valid application Id before calling identify User.');
@@ -3756,9 +3764,7 @@ function moesifCreator () {
companyObject['session_token'] = this._session;
}
- var campaignData = hasCompanyIdentifiedBefore
- ? this._campaign
- : getStoredInitialCampaignData(this._options) || this._campaign;
+ var campaignData = popStoredCampaignDataForCompany(this._persist, this._options) || this._currentCampaign;
if (campaignData) {
companyObject['campaign'] = campaignData;
@@ -3935,7 +3941,7 @@ function moesifCreator () {
this._companyId = null;
this._userId = null;
this._session = null;
- this._campaign = null;
+ this._currentCampaign = null;
}
};
}
diff --git a/examples/es2015-babelify/bundle.js b/examples/es2015-babelify/bundle.js
index 0ae40cc..ecfb61e 100644
--- a/examples/es2015-babelify/bundle.js
+++ b/examples/es2015-babelify/bundle.js
@@ -103,26 +103,6 @@ function getCampaignDataFromUrlOrCookie(opt) {
}
}
-// since identify company can happen a lot later
-// than initial anonymous users
-// persist the very initial campaign data for
-// companies until company is identified.
-function getStoredInitialCampaignData(opt) {
- var storedCampaignData = null;
- var storedCampaignString = null;
- try {
- storedCampaignString = (0, _persistence.getFromPersistence)(_persistence.STORAGE_CONSTANTS.STORED_INITIAL_CAMPAIGN_DATA, opt);
- if (storedCampaignString) {
- storedCampaignData = _utils._.JSONDecode(storedCampaignString);
- }
- } catch (err) {
- logger.error('failed to decode company campaign data ' + storedCampaignString);
- logger.error(err);
- }
-
- return storedCampaignData;
-}
-
function mergeCampaignData(saved, current) {
if (!current) {
return saved;
@@ -146,48 +126,84 @@ function mergeCampaignData(saved, current) {
return result;
}
-function getCampaignData(persist, opt) {
- var storedCampaignData = null;
- var storedCampaignString = null;
+function hasData(data) {
+ if (data && !_utils._.isEmptyObject(data)) {
+ return true;
+ }
+ return false;
+}
+
+function saveEncodeIfHasData(persist, storageKey, data) {
try {
- storedCampaignString = (0, _persistence.getFromPersistence)(_persistence.STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, opt);
- if (storedCampaignString && storedCampaignString !== 'null') {
- storedCampaignData = _utils._.JSONDecode(storedCampaignString);
+ if (hasData(data)) {
+ var dataString = _utils._.JSONEncode(data);
+ persist(storageKey, dataString);
}
} catch (err) {
- logger.error('failed to decode campaign data ' + storedCampaignString);
+ logger.error('failed to decode campaign data');
logger.error(err);
}
+}
- var currentCampaignData = getCampaignDataFromUrlOrCookie(opt);
- logger.log('current campaignData');
- logger.log(_utils._.JSONEncode(currentCampaignData));
-
- var merged = mergeCampaignData(storedCampaignData, currentCampaignData);
- logger.log('merged campaignData');
- logger.log(_utils._.JSONEncode(merged));
-
+function getAndDecode(storageKey, opt) {
try {
- if (persist && merged && !_utils._.isEmptyObject(merged)) {
- var mergedString = _utils._.JSONEncode(merged);
- persist(_persistence.STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, mergedString);
-
- // UTM_SOURCE exists means that merged campaign info have data.
- if (!storedCampaignData && merged[_utm.UTMConstants.UTM_SOURCE]) {
- // first time we persist campaign data, and thus persis the initial data until identifyCompany is called
- persist(_persistence.STORAGE_CONSTANTS.STORED_INITIAL_CAMPAIGN_DATA, mergedString);
+ var stringVal = (0, _persistence.getFromPersistence)(storageKey, opt);
+ if (stringVal && stringVal !== 'null') {
+ var data = _utils._.JSONDecode(stringVal);
+ if (hasData(data)) {
+ return data;
}
+ return null;
}
} catch (err) {
logger.error('failed to persist campaign data');
logger.error(err);
+ return null;
}
+}
- return merged;
+function storeForOneEntityIfNotSavedYet(persist, opt, entityStorageKey, currentCampaignData) {
+ var storedData = getAndDecode(entityStorageKey, opt);
+ if (!storedData && persist) {
+ // no stored data thus store current.
+ saveEncodeIfHasData(persist, entityStorageKey, currentCampaignData);
+ }
}
-exports.getCampaignData = getCampaignData;
-exports.getStoredInitialCampaignData = getStoredInitialCampaignData;
+// this stores Campaign data if not saved yet.
+function storeCampaignDataIfNeeded(persist, opt, currentCampaignData) {
+ storeForOneEntityIfNotSavedYet(persist, opt, _persistence.STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, currentCampaignData);
+ storeForOneEntityIfNotSavedYet(persist, opt, _persistence.STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, currentCampaignData);
+}
+
+function popStoredCampaignData(persist, opt, storageKey) {
+ var storedCampaignData = getAndDecode(storageKey, opt);
+
+ if (storedCampaignData) {
+ // let's delete it
+ // we know we will use it.
+ // so next one can overridee
+ try {
+ persist(storageKey, '');
+ } catch (err) {
+ logger.error('failed to clear campaign data');
+ }
+ }
+ return storedCampaignData;
+}
+
+function popStoredCampaignDataForUser(persist, opt) {
+ return popStoredCampaignData(persist, opt, _persistence.STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER);
+}
+
+function popStoredCampaignDataForCompany(persist, opt) {
+ return popStoredCampaignData(persist, opt, _persistence.STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY);
+}
+
+exports.getCampaignDataFromUrlOrCookie = getCampaignDataFromUrlOrCookie;
+exports.storeCampaignDataIfNeeded = storeCampaignDataIfNeeded;
+exports.popStoredCampaignDataForUser = popStoredCampaignDataForUser;
+exports.popStoredCampaignDataForCompany = popStoredCampaignDataForCompany;
},{"./persistence":11,"./referrer":12,"./utils":16,"./utm":17}],4:[function(require,module,exports){
'use strict';
@@ -602,7 +618,7 @@ Object.defineProperty(exports, '__esModule', {
});
var Config = {
DEBUG: false,
- LIB_VERSION: '1.8.12'
+ LIB_VERSION: '1.8.13'
};
exports['default'] = Config;
@@ -860,16 +876,22 @@ exports['default'] = function () {
this._session = (0, _persistence.getFromPersistence)(_persistence.STORAGE_CONSTANTS.STORED_SESSION_ID, ops);
this._companyId = (0, _persistence.getFromPersistence)(_persistence.STORAGE_CONSTANTS.STORED_COMPANY_ID, ops);
this._anonymousId = (0, _anonymousId.getAnonymousId)(this._persist, ops);
- this._campaign = (0, _campaign.getCampaignData)(this._persist, ops);
+ this._currentCampaign = (0, _campaign.getCampaignDataFromUrlOrCookie)(ops);
+
+ if (this._currentCampaign) {
+ (0, _campaign.storeCampaignDataIfNeeded)(this._persist, ops, this._currentCampaign);
+ }
+
+ // this._campaign = getCampaignData(this._persist, ops);
// try to save campaign data on anonymous id
// if there is no userId saved, means it is still anonymous.
// later on, when identifyUser is called with real user id,
// the campaigne data will be resent with that again.
- if (this._campaign && !this._userId) {
+ if (this._currentCampaign && !this._userId) {
var anonUserObject = {};
anonUserObject['anonymous_id'] = this._anonymousId;
- anonUserObject['campaign'] = this._campaign;
+ anonUserObject['campaign'] = this._currentCampaign;
this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback);
}
} catch (err) {
@@ -1114,8 +1136,10 @@ exports['default'] = function () {
userObject['session_token'] = this._session;
}
- if (this._campaign) {
- userObject['campaign'] = this._campaign;
+ var campaignData = (0, _campaign.popStoredCampaignDataForUser)(this._persist, this._options) || this._currentCampaign;
+
+ if (campaignData) {
+ userObject['campaign'] = campaignData;
}
if (this._companyId) {
@@ -1142,8 +1166,6 @@ exports['default'] = function () {
return;
}
- var hasCompanyIdentifiedBefore = !!this._companyId;
-
this._companyId = companyId;
if (!(this._options && this._options.applicationId)) {
throw new Error('Init needs to be called with a valid application Id before calling identify User.');
@@ -1163,7 +1185,7 @@ exports['default'] = function () {
companyObject['session_token'] = this._session;
}
- var campaignData = hasCompanyIdentifiedBefore ? this._campaign : (0, _campaign.getStoredInitialCampaignData)(this._options) || this._campaign;
+ var campaignData = (0, _campaign.popStoredCampaignDataForCompany)(this._persist, this._options) || this._currentCampaign;
if (campaignData) {
companyObject['campaign'] = campaignData;
@@ -1328,7 +1350,7 @@ exports['default'] = function () {
this._companyId = null;
this._userId = null;
this._session = null;
- this._campaign = null;
+ this._currentCampaign = null;
}
};
};
@@ -1424,8 +1446,8 @@ var STORAGE_CONSTANTS = {
STORED_COMPANY_ID: 'moesif_stored_company_id',
STORED_SESSION_ID: 'moesif_stored_session_id',
STORED_ANONYMOUS_ID: 'moesif_anonymous_id',
- STORED_CAMPAIGN_DATA: 'moesif_campaign_data',
- STORED_INITIAL_CAMPAIGN_DATA: 'moesif_initial_campaign'
+ STORED_CAMPAIGN_DATA_USER: 'moesif_campaign_data',
+ STORED_CAMPAIGN_DATA_COMPANY: 'moesif_campaign_company'
};
function replacePrefix(key, prefix) {
@@ -1500,7 +1522,8 @@ function clearCookies(opt) {
_utils._.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_COMPANY_ID, prefix));
_utils._.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_ANONYMOUS_ID, prefix));
_utils._.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_SESSION_ID, prefix));
- _utils._.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, prefix));
+ _utils._.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, prefix));
+ _utils._.cookie.remove(replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, prefix));
}
function clearLocalStorage(opt) {
@@ -1509,7 +1532,8 @@ function clearLocalStorage(opt) {
_utils._.localStorage.remove(replacePrefix(STORAGE_CONSTANTS.STORED_COMPANY_ID, prefix));
_utils._.localStorage.remove(replacePrefix(STORAGE_CONSTANTS.STORED_ANONYMOUS_ID, prefix));
_utils._.localStorage.remove(replacePrefix(STORAGE_CONSTANTS.STORED_SESSION_ID, prefix));
- _utils._.localStorage.remove(replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA, prefix));
+ _utils._.localStorage.remove(replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_USER, prefix));
+ _utils._.localStorage.remove(replacePrefix(STORAGE_CONSTANTS.STORED_CAMPAIGN_DATA_COMPANY, prefix));
}
exports.getFromPersistence = getFromPersistence;
diff --git a/examples/umd-webpack/dist/main.js b/examples/umd-webpack/dist/main.js
index 264e128..4cce390 100644
--- a/examples/umd-webpack/dist/main.js
+++ b/examples/umd-webpack/dist/main.js
@@ -1 +1 @@
-!function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t,r){r(1),e.exports=r(3)},function(e,t,r){var n=r(2);n.init({applicationId:"Your Application ID"}),n.start()},function(e,t,r){e.exports=function(){"use strict";var e,t={DEBUG:!1,LIB_VERSION:"1.8.12"};if("undefined"==typeof window){var r={hostname:""};e={navigator:{userAgent:""},document:{location:r,referrer:""},screen:{width:0,height:0},location:r}}else e=window;var n,i,o,s,a,c,u,l,f,d,h=Array.prototype,p=Function.prototype,g=Object.prototype,m=h.slice,v=g.toString,y=g.hasOwnProperty,b=e.console,_=e.navigator,w=e.document,S=e.opera,I=e.screen,k=_.userAgent,E=p.bind,O=h.forEach,x=h.indexOf,q=h.map,B=Array.isArray,A={},T={trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},M={log:function(){if(t.DEBUG&&!T.isUndefined(b)&&b)try{b.log.apply(b,arguments)}catch(e){T.each(arguments,(function(e){b.log(e)}))}},error:function(){if(t.DEBUG&&!T.isUndefined(b)&&b){var e=["Moesif error:"].concat(T.toArray(arguments));try{b.error.apply(b,e)}catch(t){T.each(e,(function(e){b.error(e)}))}}},critical:function(){if(!T.isUndefined(b)&&b){var e=["Moesif error:"].concat(T.toArray(arguments));try{b.error.apply(b,e)}catch(t){T.each(e,(function(e){b.error(e)}))}}}},R=function(e,t){return function(){return arguments[0]="["+t+"] "+arguments[0],e.apply(M,arguments)}},C=function(e){return{log:R(M.log,e),error:R(M.error,e),critical:R(M.critical,e)}};T.bind=function(e,t){var r,n;if(E&&e.bind===E)return E.apply(e,m.call(arguments,1));if(!T.isFunction(e))throw new TypeError;return r=m.call(arguments,2),n=function(){if(!(this instanceof n))return e.apply(t,r.concat(m.call(arguments)));var i={};i.prototype=e.prototype;var o=new i;i.prototype=null;var s=e.apply(o,r.concat(m.call(arguments)));return Object(s)===s?s:o}},T.bind_instance_methods=function(e){for(var t in e)"function"==typeof e[t]&&(e[t]=T.bind(e[t],e))},T.each=function(e,t,r){if(null!=e)if(O&&e.forEach===O)e.forEach(t,r);else if(e.length===+e.length){for(var n=0,i=e.length;n/g,">").replace(/"/g,""").replace(/'/g,"'")),t},T.extend=function(e){return T.each(m.call(arguments,1),(function(t){for(var r in t)void 0!==t[r]&&(e[r]=t[r])})),e},T.isArray=B||function(e){return"[object Array]"===v.call(e)},T.isFunction=function(e){try{return/^\s*\bfunction\b/.test(e)}catch(e){return!1}},T.isArguments=function(e){return!(!e||!y.call(e,"callee"))},T.toArray=function(e){return e?e.toArray?e.toArray():T.isArray(e)||T.isArguments(e)?m.call(e):T.values(e):[]},T.map=function(e,t){if(q&&e.map===q)return e.map(t);var r=[];return T.each(e,(function(e){r.push(t(e))})),r},T.keys=function(e){var t=[];return null===e||T.each(e,(function(e,r){t[t.length]=r})),t},T.values=function(e){var t=[];return null===e||T.each(e,(function(e){t[t.length]=e})),t},T.identity=function(e){return e},T.include=function(e,t){var r=!1;return null===e?r:x&&e.indexOf===x?-1!=e.indexOf(t):(T.each(e,(function(e){if(r||(r=e===t))return A})),r)},T.includes=function(e,t){return-1!==e.indexOf(t)},T.inherit=function(e,t){return e.prototype=new t,e.prototype.constructor=e,e.superclass=t.prototype,e},T.isArrayBuffer=function(e){var t=Object.prototype.toString;return"function"==typeof ArrayBuffer&&(e instanceof ArrayBuffer||"[object ArrayBuffer]"===t.call(e))},T.isObject=function(e){return e===Object(e)&&!T.isArray(e)},T.isEmptyObject=function(e){if(T.isObject(e)){for(var t in e)if(y.call(e,t))return!1;return!0}return!1},T.isEmptyString=function(e){return!e||0===e.length},T.isUndefined=function(e){return void 0===e},T.isString=function(e){return"[object String]"==v.call(e)},T.isDate=function(e){return"[object Date]"==v.call(e)},T.isNumber=function(e){return"[object Number]"==v.call(e)},T.isElement=function(e){return!(!e||1!==e.nodeType)},T.isNil=function(e){return T.isUndefined(e)||null===e},T.encodeDates=function(e){return T.each(e,(function(t,r){T.isDate(t)?e[r]=T.formatDate(t):T.isObject(t)&&(e[r]=T.encodeDates(t))})),e},T.timestamp=function(){return Date.now=Date.now||function(){return+new Date},Date.now()},T.formatDate=function(e){function t(e){return e<10?"0"+e:e}return e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())},T.safewrap=function(e){return function(){try{return e.apply(this,arguments)}catch(e){M.critical("Implementation error. Please turn on debug and contact support@Moesif.com."),t.DEBUG&&M.critical(e)}}},T.safewrap_class=function(e,t){for(var r=0;r0&&(t[r]=e)})),t},T.truncate=function(e,t){var r;return"string"==typeof e?r=e.slice(0,t):T.isArray(e)?(r=[],T.each(e,(function(e){r.push(T.truncate(e,t))}))):T.isObject(e)?(r={},T.each(e,(function(e,n){r[n]=T.truncate(e,t)}))):r=e,r},T.JSONEncode=function(e){var t=function(e){var t=/[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};return t.lastIndex=0,t.test(e)?'"'+e.replace(t,(function(e){var t=r[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)}))+'"':'"'+e+'"'},r=function(e,n){var i="",o=0,s="",a="",c=0,u=i,l=[],f=n[e];switch(f&&"object"==typeof f&&"function"==typeof f.toJSON&&(f=f.toJSON(e)),typeof f){case"string":return t(f);case"number":return isFinite(f)?String(f):"null";case"boolean":case"null":return String(f);case"object":if(!f)return"null";if(i+=" ",l=[],"[object Array]"===v.apply(f)){for(c=f.length,o=0;o="0"&&i<="9";)t+=i,u();if("."===i)for(t+=".";u()&&i>="0"&&i<="9";)t+=i;if("e"===i||"E"===i)for(t+=i,u(),"-"!==i&&"+"!==i||(t+=i,u());i>="0"&&i<="9";)t+=i,u();if(e=+t,isFinite(e))return e;c("Bad number")},f=function(){var e,t,r,n="";if('"'===i)for(;u();){if('"'===i)return u(),n;if("\\"===i)if(u(),"u"===i){for(r=0,t=0;t<4&&(e=parseInt(u(),16),isFinite(e));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else{if("string"!=typeof a[i])break;n+=a[i]}else n+=i}c("Bad string")},d=function(){for(;i&&i<=" ";)u()},s=function(){switch(d(),i){case"{":return function(){var e,t={};if("{"===i){if(u("{"),d(),"}"===i)return u("}"),t;for(;i;){if(e=f(),d(),u(":"),Object.hasOwnProperty.call(t,e)&&c('Duplicate key "'+e+'"'),t[e]=s(),d(),"}"===i)return u("}"),t;u(","),d()}}c("Bad object")}();case"[":return function(){var e=[];if("["===i){if(u("["),d(),"]"===i)return u("]"),e;for(;i;){if(e.push(s()),d(),"]"===i)return u("]"),e;u(","),d()}}c("Bad array")}();case'"':return f();case"-":return l();default:return i>="0"&&i<="9"?l():function(){switch(i){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}c('Unexpected "'+i+'"')}()}},function(e){var t;return o=e,n=0,i=" ",t=s(),d(),i&&c("Syntax error"),t}),T.base64Encode=function(e){var t,r,n,i,o,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,c=0,u="",l=[];if(!e)return e;e=T.utf8Encode(e);do{t=(o=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,r=o>>12&63,n=o>>6&63,i=63&o,l[c++]=s.charAt(t)+s.charAt(r)+s.charAt(n)+s.charAt(i)}while(a127&&s<2048?String.fromCharCode(s>>6|192,63&s|128):String.fromCharCode(s>>12|224,s>>6&63|128,63&s|128),null!==a&&(r>t&&(o+=e.substring(t,r)),o+=a,t=r=i+1)}return r>t&&(o+=e.substring(t,e.length)),o},T.UUID=function(){var e=(I.height*I.width).toString(16);return function(){for(var e=1*new Date,t=0;e==1*new Date;)t++;return e.toString(16)+t.toString(16)}()+"-"+Math.random().toString(16).replace(".","")+"-"+function(){var e,t,r=k,n=[],i=0;function o(e,t){var r,i=0;for(r=0;r=4&&(i=o(i,n),n=[]);return n.length>0&&(i=o(i,n)),i.toString(16)}()+"-"+e},T.uuid4=function(){var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.split(/[:\/]/g).pop().toLowerCase()},T.isBlockedUA=function(e){return!!/(google web preview|baiduspider|yandexbot|bingbot|googlebot|yahoo! slurp)/i.test(e)},T.HTTPBuildQuery=function(e,t){var r,n,i=[];return T.isUndefined(t)&&(t="&"),T.each(e,(function(e,t){r=encodeURIComponent(e.toString()),n=encodeURIComponent(t),i[i.length]=n+"="+r})),i.join(t)},T.getUrlParams=function(){return location&&(location.search||function(e){if(e){var t=e.indexOf("?");if(t>=0)return e.substring(t)}return""}(location.href))},T.getQueryParamByName=function(e,t){e=e.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var r=new RegExp("[\\?&]"+e+"=([^]*)").exec(t);return null===r?void 0:decodeURIComponent(r[1].replace(/\+/g," "))},T.getQueryParam=function(e,t){t=t.replace(/[[]/,"\\[").replace(/[\]]/,"\\]");var r=new RegExp("[\\?&]"+t+"=([^]*)").exec(e);if(null===r||r&&"string"!=typeof r[1]&&r[1].length)return"";var n=r[1];try{n=decodeURIComponent(n)}catch(e){M.error("Skipping decoding for malformed query param: "+n)}return n.replace(/\+/g," ")},T.getHashParam=function(e,t){var r=e.match(new RegExp(t+"=([^&]*)"));return r?r[1]:null},T.cookie={get:function(e){for(var t=e+"=",r=w.cookie.split(";"),n=0;n=0}function n(t){if(!w.getElementsByTagName)return[];var n,i,o,s,a,c,u,l,f,d,h=t.split(" "),p=[w];for(c=0;c-1){o=(i=n.split("#"))[0];var g=i[1],m=w.getElementById(g);if(!m||o&&m.nodeName.toLowerCase()!=o)return[];p=[m]}else if(n.indexOf(".")>-1){o=(i=n.split("."))[0];var v=i[1];for(o||(o="*"),s=[],a=0,u=0;u-1};break;default:b=function(e){return e.getAttribute(_)}}for(p=[],d=0,u=0;u=3?t[2]:""},properties:function(){return T.extend(T.strip_empty_properties({$os:T.info.os(),$browser:T.info.browser(k,_.vendor,S),$referrer:w.referrer,$referring_domain:T.info.referringDomain(w.referrer),$device:T.info.device(k)}),{$current_url:e.location.href,$browser_version:T.info.browserVersion(k,_.vendor,S),$screen_height:I.height,$screen_width:I.width,mp_lib:"web",$lib_version:t.LIB_VERSION,$insert_id:P(),time:T.timestamp()/1e3})},people_properties:function(){return T.extend(T.strip_empty_properties({$os:T.info.os(),$browser:T.info.browser(k,_.vendor,S)}),{$browser_version:T.info.browserVersion(k,_.vendor,S)})},pageviewInfo:function(e){return T.strip_empty_properties({mp_page:e,mp_referrer:w.referrer,mp_browser:T.info.browser(k,_.vendor,S),mp_platform:T.info.os()})}};var P=function(e){var t=Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10);return e?t.substring(0,e):t},N=function(e){var t=5381;if(0==e.length)return t;for(var r=0;r>>0)%1004||"com"===n||"org"===n)&&(t=j);var i=e.match(t);return i?i[0]:""},H=null,J=null;"undefined"!=typeof JSON&&(H=JSON.stringify,J=JSON.parse),H=H||T.JSONEncode,J=J||T.JSONDecode,T.toArray=T.toArray,T.isObject=T.isObject,T.JSONEncode=T.JSONEncode,T.JSONDecode=T.JSONDecode,T.isBlockedUA=T.isBlockedUA,T.isEmptyObject=T.isEmptyObject,T.isEmptyString=T.isEmptyString,T.info=T.info,T.info.device=T.info.device,T.info.browser=T.info.browser,T.info.browserVersion=T.info.browserVersion,T.info.properties=T.info.properties;var W=C("parsers"),$=function(e){try{return{body:T.JSONDecode(e)}}catch(t){return W.log("JSON decode failed"),W.log(t),{transfer_encoding:"base64",body:T.base64Encode(e)}}},Q=function(e){if(!e)return{};if(W.log("about to decode buffer"),W.log(e),W.log(e.byteLength),e.byteLength<=0)return{};try{var t=new TextDecoder("utf-8").decode(e);try{return{body:T.JSONDecode(t)}}catch(e){return W.error(e),{transfer_encoding:"base64",body:T.base64Encode(t)}}}catch(t){return W.error(t),W.log(e),{transfer_encoding:"base64",body:"can not be decoded"}}},K=C("capture"),V="http:"===(document&&document.location.protocol)?"http://":"https://";function X(e,t,r){K.log("processResponse for"+e._url);var n=(new Date).toISOString();if(r){var i=e._url?e._url.toLowerCase():e._url;if(i&&i.indexOf("moesif.com")<0&&i.indexOf("apirequest.io")<0){var o={uri:G(e._url),verb:e._method,time:e._startTime,headers:e._requestHeaders};if(t)if("string"==typeof t){K.log("request post data is string"),K.log(t);var s=$(t);o.transfer_encoding=s.transfer_encoding,o.body=s.body}else("object"==typeof t||Array.isArray(t)||"number"==typeof t||"boolean"==typeof t)&&(o.body=t);var a=e.getAllResponseHeaders();K.log("rawResponseHeaders are "+a);var c=function(e){var t={};if(!e)return t;for(var r=e.split("\r\n"),n=0;n0){var s=i.substring(0,o);t[s]=i.substring(o+2)}}return t}(a),u=e.status;1223===u&&(u=204);var l={status:u,time:n,headers:c};K.log("responseType: "+e.responseType),K.log("responseText: "+e.responseText),K.log("response: "+e.response);var f=e.responseText,d={};f?(d=$(f),l.body=d.body,l.transfer_encoding=d.transfer_encoding):e.response&&(K.log("no responseText trying with xhr.response"),T.isString(e.response)?(K.log("response is string. attempt to parse"),d=$(e.response),l.body=d.body,l.transfer_encoding=d.transfer_encoding):T.isArrayBuffer(e.response)?(K.log("response is arraybuffer. attempt to parse"),d=Q(e.response),l.body=d.body,l.transfer_encoding=d.transfer_encoding):(T.isArray(e.response)||T.isObject(e.response))&&(l.body=e.response)),r({request:o,response:l})}}}function G(e){if(e&&"string"==typeof e){var t=T.trim(e);return 0!==t.indexOf("http")?V+window.location.host+"/"+t.replace(/^\./,"").replace(/^\//,""):e}return e}var Y=C("web3capture");function Z(e){return e&&e.host?e.host:"/"}function ee(e,t,r,n,i,o){var s={uri:Z(e),verb:"POST",time:t,headers:{}};if(e.headers){var a={};T.each(e.headers,(function(e){a[e.name]=e.value})),s.headers=a}if(n)if("string"==typeof n){Y.log("request post data is string"),Y.log(n);try{s.body=T.JSONDecode(n)}catch(e){Y.log("JSON decode failed"),Y.log(e),s.transfer_encoding="base64",s.body=T.base64Encode(n)}}else("object"==typeof n||Array.isArray(n)||"number"==typeof n||"boolean"==typeof postData)&&(s.body=n);var c={status:200,time:r,headers:{}};i?c.body=i:o&&(c.body={error:o});var u={request:s,response:c,metadata:{_web3:{via_web3_provider:!0,path:e.path,host:e.host}}};return e.isMetaMask&&(u.metadata._web3.is_metamask=!0),u}function te(e,t,r){if(e.currentProvider){Y.log("found my currentProvider, patching it");var n=e.currentProvider,i=n.send,o=n.sendAsync;return n.send=function(e){Y.log("patched send is called"),Y.log(e);var r=(new Date).toISOString(),o=i.apply(n,arguments);Y.log("patch send result is back"),Y.log(o);var s=(new Date).toISOString();return t&&t(ee(n,r,s,e,o)),o},n.sendAsync=function(e,r){Y.log("patched sendAsync is called"),Y.log(e);var i=(new Date).toISOString(),s=n;o.apply(n,[e,function(n,o){var a=(new Date).toISOString();Y.log("inside patched callback"),Y.log(o),t&&t(ee(s,i,a,e,o,n)),r&&r(n,o)}])},function(){n.send=i,n.sendAsync=o}}return null}var re=C("capture fetch");function ne(e){var t={};re.log("parseheaders is called");for(var r=e.entries(),n=r.next();!n.done;)re.log(n.value),t[n.value[0]]=n.value[1],n=r.next();return t}function ie(e,t,r,n){var i=null;try{i=new Request(r,n)}catch(e){}var o=(new Date).toISOString(),s=null,a=null;a=t(r,n);var c=null;return a=a.then((function(t){return c=t.clone(),s=(new Date).toISOString(),function(e,t,r,n,i){try{setTimeout((function(){if(re.log("interception is here."),re.log(e),re.log(t),e&&t)try{Promise.all([e.arrayBuffer(),t.arrayBuffer()]).then((function(o){var s=o.map(Q),a=Object.assign(s[0],{uri:e.url,verb:e.method,time:r,headers:ne(e.headers)}),c=Object.assign(s[1],{status:t.status,time:n,headers:ne(t.headers)});re.log(a),re.log(c),i({request:a,response:c})}))}catch(e){re.error("error processing body")}else re.log("savedRequest")}),50)}catch(e){re.error("error processing saved fetch request and response, but move on anyways."),re.log(e)}}(i,c,o,s,e),t}))}var oe=C("referrer");function se(e){if(T.isEmptyString(e))return null;var t=e.split("/");return t.length>=3?t[2]:null}function ae(){var e=document&&document.referrer;if(oe.log(e),!T.isEmptyString(e)){if(0!==e.indexOf(location.protocol+"//"+location.host))return{referrer:e,referring_domain:se(e)};oe.log("referrer is the same so skipping")}}var ce=C("utm"),ue={UTM_SOURCE:"utm_source",UTM_MEDIUM:"utm_medium",UTM_CAMPAIGN:"utm_campaign",UTM_TERM:"utm_term",UTM_CONTENT:"utm_content"};function le(e,t){return e=T.getUrlParams(),function(e,t){var r=e?"?"+e.split(".").slice(-1)[0].replace(/\|/g,"&"):"";ce.log("cookie"),ce.log(r);var n=function(e,t,r,n){return T.getQueryParamByName(e,t)||T.getQueryParamByName(r,n)},i=n(ue.UTM_SOURCE,t,"utmcsr",r),o=n(ue.UTM_MEDIUM,t,"utmcmd",r),s=n(ue.UTM_CAMPAIGN,t,"utmccn",r),a=n(ue.UTM_TERM,t,"utmctr",r),c=n(ue.UTM_CONTENT,t,"utmcct",r),u={},l=function(e,t){T.isEmptyString(t)||(u[e]=t)};return l(ue.UTM_SOURCE,i),l(ue.UTM_MEDIUM,o),l(ue.UTM_CAMPAIGN,s),l(ue.UTM_TERM,a),l(ue.UTM_CONTENT,c),u}(T.cookie.get("__utmz"),e)}var fe="moesif_stored_user_id",de="moesif_stored_company_id",he="moesif_stored_session_id",pe="moesif_anonymous_id",ge="moesif_campaign_data",me="moesif_initial_campaign";function ve(e,t){return t&&0===e.indexOf("moesif_")?e.replace("moesif_",t):e}function ye(e){return"null"===e||"undefined"===e||""===e?null:e}function be(e,t){var r=t&&t.persistence,n=ve(e,t&&t.persistence_key_prefix);if(T.localStorage.is_supported()){var i=ye(T.localStorage.get(n)),o=ye(T.cookie.get(n));return!i&&o&&"localStorage"===r&&T.localStorage.set(n,o),i||o}return ye(T.cookie.get(n))}function _e(e){var t=e&&e.persistence_key_prefix;T.cookie.remove(ve(fe,t)),T.cookie.remove(ve(de,t)),T.cookie.remove(ve(pe,t)),T.cookie.remove(ve(he,t)),T.cookie.remove(ve(ge,t))}function we(e){var t=e&&e.persistence_key_prefix;T.localStorage.remove(ve(fe,t)),T.localStorage.remove(ve(de,t)),T.localStorage.remove(ve(pe,t)),T.localStorage.remove(ve(he,t)),T.localStorage.remove(ve(ge,t))}var Se=C("campaign");function Ie(e){try{var t={};if(e.disableUtm||(t=le()||{}),!e.disableReferer){var r=ae();r&&(t.referrer=r.referrer,t.referring_domain=r.referring_domain)}if(!e.disableRGclid){var n=function(e){var t=T.getQueryParamByName("gclid",e);if(!T.isEmptyString(t))return t}(T.getUrlParams());n&&(t.gclid=n)}return t}catch(e){Se.log(e)}}function ke(e,t){var r=null,n=null;try{(n=be(ge,t))&&"null"!==n&&(r=T.JSONDecode(n))}catch(e){Se.error("failed to decode campaign data "+n),Se.error(e)}var i=Ie(t);Se.log("current campaignData"),Se.log(T.JSONEncode(i));var o=function(e,t){if(!t)return e;if(!e)return t;var r=T.extend({},e,t);if(t&&t[ue.UTM_SOURCE])for(var n in ue)r[ue[n]]=t[ue[n]];return r}(r,i);Se.log("merged campaignData"),Se.log(T.JSONEncode(o));try{if(e&&o&&!T.isEmptyObject(o)){var s=T.JSONEncode(o);e(ge,s),!r&&o[ue.UTM_SOURCE]&&e(me,s)}}catch(e){Se.error("failed to persist campaign data"),Se.error(e)}return o}var Ee=C("lock"),Oe=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||window.localStorage,this.pollIntervalMS=t.pollIntervalMS||100,this.timeoutMS=t.timeoutMS||2e3};Oe.prototype.withLock=function(e,t,r){r||"function"==typeof t||(r=t,t=null);var n=r||(new Date).getTime()+"|"+Math.random(),i=(new Date).getTime(),o=this.storageKey,s=this.pollIntervalMS,a=this.timeoutMS,c=this.storage,u=o+":X",l=o+":Y",f=o+":Z",d=function(e){t&&t(e)},h=function(e){if((new Date).getTime()-i>a)return Ee.error("Timeout waiting for mutex on "+o+"; clearing lock. ["+n+"]"),c.removeItem(f),c.removeItem(l),void m();setTimeout((function(){try{e()}catch(e){d(e)}}),s*(Math.random()+.1))},p=function(e,t){e()?t():h((function(){p(e,t)}))},g=function(){var e=c.getItem(l);if(e&&e!==n)return!1;if(c.setItem(l,n),c.getItem(l)===n)return!0;if(!U(c,!0))throw new Error("localStorage support dropped while acquiring lock");return!1},m=function(){c.setItem(u,n),p(g,(function(){c.getItem(u)!==n?h((function(){c.getItem(l)===n?p((function(){return!c.getItem(f)}),v):m()})):v()}))},v=function(){c.setItem(f,"1");try{e()}finally{c.removeItem(f),c.getItem(l)===n&&c.removeItem(l),c.getItem(u)===n&&c.removeItem(u)}};try{if(!U(c,!0))throw new Error("localStorage support check failed");m()}catch(e){d(e)}};var xe=C("batch"),qe=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||window.localStorage,this.lock=new Oe(e,{storage:this.storage}),this.storageExpiration=t.storageExpiration||216e5,this.pid=t.pid||null,this.memQueue=[]};qe.prototype.enqueue=function(e,t,r){var n={id:P(),flushAfter:(new Date).getTime()+2*t,payload:e};this.lock.withLock(T.bind((function(){var t;try{var i=this.readFromStorage();i.push(n),(t=this.saveToStorage(i))&&(xe.log("succeeded saving to storage"),this.memQueue.push(n))}catch(r){xe.error("Error enqueueing item",e),t=!1}r&&r(t)}),this),(function(e){xe.error("Error acquiring storage lock",e),r&&r(!1)}),this.pid)},qe.prototype.fillBatch=function(e){this.memQueue=Be(this.memQueue,{},this.storageExpiration);var t=this.memQueue.slice(0,e);if(t.lengtho.flushAfter&&o.flushAfter>=a&&!n[o.id]){if(t.push(o),t.length>=e)break}else xe.log("fill batch filtered item because invalid or expired"+H(o))}}}return t};var Be=function(e,t,r){var n=[],i=(new Date).getTime()-r;return xe.log("expiration time is "+i),T.each(e,(function(e){e.id&&!t[e.id]?e.flushAfter&&e.flushAfter>=i&&n.push(e):xe.log("filtered out item because invalid or expired"+H(e))})),n};qe.prototype.removeItemsByID=function(e,t){var r={};T.each(e,(function(e){r[e]=!0})),this.memQueue=Be(this.memQueue,r,this.storageExpiration);var n=T.bind((function(){var t;try{var n=this.readFromStorage();n=Be(n,r,this.storageExpiration),t=this.saveToStorage(n)}catch(r){xe.error("Error removing items",e),t=!1}return t}),this);this.lock.withLock(T.bind((function(){var e=n();t&&(xe.log("triggering callback of removalItems"),t(e))}),this),T.bind((function(e){var r=!1;if(xe.error("Error acquiring storage lock",e),!U(this.storage,!0)&&!(r=n())){xe.error("still can not remove from storage, thus stop using storage");try{this.storage.removeItem(this.storageKey)}catch(e){xe.error("error clearing queue",e)}}t&&t(r)}),this),this.pid)},qe.prototype.readFromStorage=function(){var e;try{xe.log("trying to get storage with storage key "+this.storageKey),(e=this.storage.getItem(this.storageKey))?(e=J(e),T.isArray(e)||(xe.error("Invalid storage entry:",e),e=null)):xe.log("storageEntry is empty")}catch(t){xe.error("Error retrieving queue",t),e=null}return e||[]},qe.prototype.saveToStorage=function(e){try{return this.storage.setItem(this.storageKey,H(e)),!0}catch(e){return xe.error("Error saving queue",e),!1}},qe.prototype.clear=function(){this.memQueue=[];try{this.storage.removeItem(this.storageKey)}catch(e){xe.error("Failed to clear storage",e)}};var Ae=C("batch"),Te=function(e,t,r){var n=r.libConfig.batch_storage_expiration;this.queue=new qe(e,{storage:r.storage,storageExpiration:n}),this.endpoint=t,this.libConfig=r.libConfig,this.sendRequest=r.sendRequestFunc,this.batchSize=this.libConfig.batch_size,this.flushInterval=this.libConfig.batch_flush_interval_ms,this.stopAllBatching=r.stopAllBatching,this.stopped=!1,this.removalFailures=0};function Me(e){var t=T.UUID();return e&&e(pe,t),t}Te.prototype.enqueue=function(e,t){this.queue.enqueue(e,this.flushInterval,t)},Te.prototype.start=function(){this.stopped=!1,this.removalFailures=0,this.flush()},Te.prototype.stop=function(){this.stopped=!0,this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null)},Te.prototype.clear=function(){this.queue.clear()},Te.prototype.resetBatchSize=function(){this.batchSize=this.libConfig.batch_size},Te.prototype.resetFlush=function(){this.scheduleFlush(this.libConfig.batch_flush_interval_ms)},Te.prototype.scheduleFlush=function(e){this.flushInterval=e,this.stopped||(this.timeoutID=setTimeout(T.bind(this.flush,this),this.flushInterval))},Te.prototype.flush=function(e){try{if(this.requestInProgress)return void Ae.log("Flush: Request already in progress");e=e||{};var t=this.batchSize,r=this.queue.fillBatch(t);if(Ae.log("current batch size is "+r.length),r.length<1)return void this.resetFlush();this.requestInProgress=!0;var n=this.libConfig.batch_request_timeout_ms,i=(new Date).getTime(),o=T.map(r,(function(e){return e.payload})),s=T.bind((function(e){this.requestInProgress=!1;try{var o=!1;if(T.isObject(e)&&"timeout"===e.error&&(new Date).getTime()-i>=n)Ae.error("Network timeout; retrying"),this.flush();else if(T.isObject(e)&&e.xhr_req&&(e.xhr_req.status>=500||e.xhr_req.status<=0)){var s=2*this.flushInterval,a=e.xhr_req.responseHeaders;if(a){var c=a["Retry-After"];c&&(s=1e3*parseInt(c,10)||s)}s=Math.min(6e5,s),Ae.error("Error; retry in "+s+" ms"),this.scheduleFlush(s)}else if(T.isObject(e)&&e.xhr_req&&413===e.xhr_req.status)if(r.length>1){var u=Math.max(1,Math.floor(t/2));this.batchSize=Math.min(this.batchSize,u,r.length-1),Ae.error("413 response; reducing batch size to "+this.batchSize),this.resetFlush()}else Ae.error("Single-event request too large; dropping",r),this.resetBatchSize(),o=!0;else o=!0;o&&this.queue.removeItemsByID(T.map(r,(function(e){return e.id})),T.bind((function(e){e?(this.removalFailures=0,this.flush()):(this.removalFailures=this.removalFailures+1,Ae.error("failed to remove items from batched queue "+this.removalFailures+" times."),this.removalFailures>5?(Ae.error("stop batching because too m any errors remove from storage"),this.stopAllBatching()):this.resetFlush())}),this))}catch(e){Ae.error("Error handling API response",e),this.resetFlush()}}),this),a={method:"POST",verbose:!0,ignore_json_errors:!0,timeout_ms:n};e.sendBeacon&&(a.transport="sendBeacon"),Ae.log("Moesif Request:",this.endpoint,o),this.sendRequest(this.endpoint,o,a,s)}catch(e){Ae.error("Error flushing request queue",e),this.resetFlush()}};var Re="api.moesif.net",Ce="/v1/events",De="/v1/events/batch",Ue="/v1/actions",Fe="/v1/actions/batch",Pe="/v1/users",Ne="/v1/companies",je=window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,ze=(!je&&-1===k.indexOf("MSIE")&&k.indexOf("Mozilla"),function(){}),Le=null;navigator.sendBeacon&&(Le=function(){return navigator.sendBeacon.apply(navigator,arguments)});var He,Je="http:"===(document&&document.location.protocol)?"http://":"https://";function We(e){try{return e.request.headers["X-Moesif-SDK"]}catch(e){return!1}}function $e(){return M.log("moesif object creator is called"),{init:function(e){window||M.critical("Warning, this library need to be initiated on the client side"),function(e){if(!e)throw new Error("options are required by moesif-browser-js middleware");if(!e.applicationId)throw new Error("A moesif application id is required. Please obtain it through your settings at www.moesif.com");if(e.getTags&&!T.isFunction(e.getTags))throw new Error("getTags should be a function");if(e.getMetadata&&!T.isFunction(e.getMetadata))throw new Error("getMetadata should be a function");if(e.getApiVersion&&!T.isFunction(e.getApiVersion))throw new Error("identifyUser should be a function");if(e.maskContent&&!T.isFunction(e.maskContent))throw new Error("maskContent should be a function");if(e.skip&&!T.isFunction(e.skip))throw new Error("skip should be a function")}(e);var r,n={};n.getTags=e.getTags||ze,n.maskContent=e.maskContent||function(e){return e},n.getMetadata=e.getMetadata||ze,n.skip=e.skip||function(){return!1},n.debug=e.debug,n.callback=e.callback||ze,n.applicationId=e.applicationId,n.apiVersion=e.apiVersion,n.disableFetch=e.disableFetch,n.disableReferrer=e.disableReferrer,n.disableGclid=e.disableGclid,n.disableUtm=e.disableUtm,n.eagerBodyLogging=e.eagerBodyLogging,n.host=e.host||Re,n.batchEnabled=e.batchEnabled||!1,n.batch_size=e.batchSize||25,n.batch_flush_interval_ms=e.batchMaxTime||2500,n.batch_request_timeout_ms=e.batchTimeout||9e4,n.batch_storage_expiration=e.batchStorageExpiration,n.persistence=e.persistence||"localStorage",n.cross_site_cookie=e.crossSiteCookie||!1,n.cross_subdomain_cookie=!1!==e.crossSubdomainCookie,n.cookie_expiration=e.cookieExpiration||365,n.secure_cookie=e.secureCookie||!1,n.cookie_domain=e.cookieDomain||"",n.persistence_key_prefix=e.persistenceKeyPrefix,this.requestBatchers={},this._options=n,this._persist=function(e){var r=e.persistence;"cookie"!==r&&"localStorage"!==r&&(M.critical("Unknown persistence type "+r+"; falling back to cookie"),r=t.persistence="localStorage");var n=e.persistence_key_prefix,i=function(t,r){var i=ve(t,n);T.localStorage.set(i,r),T.cookie.set(i,r,e.cookie_expiration,e.cross_subdomain_cookie,e.secure_cookie,e.cross_site_cookie,e.cookie_domain)};return"cookie"!==r&&T.localStorage.is_supported()||(i=function(t,r){var i=ve(t,n);T.cookie.set(i,r,e.cookie_expiration,e.cross_subdomain_cookie,e.secure_cookie,e.cross_site_cookie,e.cookie_domain)}),"none"===r&&(i=function(){}),i}(n);try{if(this._userId=be(fe,n),this._session=be(he,n),this._companyId=be(de,n),this._anonymousId=(r=this._persist,be(pe,n)||Me(r)),this._campaign=ke(this._persist,n),this._campaign&&!this._userId){var i={};i.anonymous_id=this._anonymousId,i.campaign=this._campaign,this.updateUser(i,this._options.applicationId,this._options.host,this._options.callback)}}catch(e){M.error("error loading saved data from local storage but continue")}if(n.batchEnabled)if(U()&&je){if(this.initBatching(),Le&&window.addEventListener){var o=T.bind((function(){T.each(this.requestBatchers,(function(e){e.stopped||e.flush({sendBeacon:!0})}))}),this);window.addEventListener("pagehide",(function(e){o()})),window.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&o()}))}}else n.batchEnabled=!1,M.log("Turning off batch processing because it needs XHR and localStorage");return M.log("moesif initiated"),this},_executeRequest:function(e,r,n,i){var o=n&&n.applicationId||this._options.applicationId,s=n&&n.method||"POST";try{var a=new XMLHttpRequest;if(a.open(s,e),a.setRequestHeader("Content-Type","application/json"),a.setRequestHeader("X-Moesif-Application-Id",o),a.setRequestHeader("X-Moesif-SDK","moesif-browser-js/"+t.LIB_VERSION),n.timeout_ms&&void 0!==a.timeout){a.timeout=n.timeout_ms;var c=(new Date).getTime()}a.onreadystatechange=function(){var e;if(4===a.readyState)if(a.status>=200&&a.status<=300){if(i){var t=XMLHttpRequest.responseText;i(t)}}else e=a.timeout&&!a.status&&(new Date).getTime()-c>=a.timeout?"timeout":"Bad HTTP status: "+a.status+" "+a.statusText,M.error(e),i&&i({status:0,error:e,xhr_req:a})},a.send(H(r))}catch(e){M.error("failed to send to moesif "+(r&&r.request&&r.request.uri)),M.error(e),i&&i({status:0,error:e})}},initBatching:function(){var e=this._options.applicationId,t=this._options.host;if(M.log("does requestBatch.events exists? "+this.requestBatchers.events),!this.requestBatchers.events){var r={libConfig:this._options,sendRequestFunc:T.bind((function(e,t,r,n){this._executeRequest(e,t,r,n)}),this),stopAllBatching:T.bind((function(){this.stopAllBatching()}),this)},n=N(e),i=new Te("__mf_"+n+"_ev",Je+t+De,r),o=new Te("__mf_"+n+"_ac",Je+t+Fe,r);this.requestBatchers={events:i,actions:o}}T.each(this.requestBatchers,(function(e){e.start()}))},stopAllBatching:function(){this._options.batchEnabled=!1,T.each(this.requestBatchers,(function(e){e.stop(),e.clear()}))},_sendOrBatch:function(e,t,r,n,i){var o=this,s=function(){var n={applicationId:t};return o._executeRequest(r,e,n,i)};if(!this._options.batchEnabled||!n)return s();M.log("current batcher storage key is "+n.queue.storageKey);var a=T.bind((function(e){e||(M.log("enqueue failed, send immediately"),s())}),this);return n.enqueue(e,a),!0},start:function(e){var t=this;if(this._stopRecording||this._stopWeb3Recording)return M.log("recording has already started, please call stop first."),!1;function r(e){t.recordEvent(e)}return M.log("moesif starting"),this._stopRecording=function(e,t){var r=XMLHttpRequest.prototype,n=t&&t.eagerBodyLogging,i=r.open,o=r.send,s=r.setRequestHeader;return r.open=function(e,t){return K.log("XHR open triggered"),this._method=e,this._url=t,this._requestHeaders={},this._startTime=(new Date).toISOString(),i.apply(this,arguments)},r.setRequestHeader=function(e,t){return this._requestHeaders[e]=t,s.apply(this,arguments)},r.send=function(t){K.log("XHR send started for "+this._url);var r=this;if(n||!this.addEventListener){var i=this.onreadystatechange;this.onreadystatechange=function(){var n=r.readyState;if(K.log("readyState "+n),n===XMLHttpRequest.DONE&&(K.log("XHR onreadystatechange DONE triggered for "+r._url),X(r,t,e)),i&&T.isFunction(i))return K.log("trigger old onreadystatechange"),i.apply(this,arguments)}}else this.addEventListener("loadend",(function(){K.log("XHR loadend triggered for "+r._url),X(r,t,e)}));return o.apply(this,arguments)},function(){r.open=i,r.send=o,r.setRequestHeader=s}}(r,this._options),this._options.disableFetch||(M.log("also instrumenting fetch API"),this._stopFetchRecording=function(e,t){var r,n=t||window||self;if(n.fetch){if(re.log("found fetch method."),n.fetch.polyfill)return re.log("skip patching fetch since it is polyfilled"),null;var i=n.fetch;return re.log("fetch is not polyfilled so instrumenting it"),n.fetch=(r=n.fetch,function(t,n){return ie(e,r,t,n)}),function(){n.fetch=i}}re.log("there is no fetch found, so skipping instrumentation.")}(r)),this.useWeb3(e),!0},useWeb3:function(e){var t=this;function r(e){t.recordEvent(e)}try{if(this._stopWeb3Recording&&(this._stopWeb3Recording(),this._stopWeb3Recording=null),e?this._stopWeb3Recording=te(e,r,this._options):window.web3&&(M.log("found global web3, will capture from it"),this._stopWeb3Recording=te(window.web3,r,this._options)),this._stopWeb3Recording)return!0}catch(e){M.log("error patching web3, moving forward anyways"),this._options.callback&&this._options.callback({status:0,error:e,message:"failed to instrument web3, but moving forward with other instrumentation"})}return!1},updateUser:function(e,t,r,n){this._executeRequest(Je+r+Pe,e,{applicationId:t},n)},identifyUser:function(e,t){if(T.isNil(e))M.critical("identifyUser called with nil userId");else{if(this._userId=e,!this._options||!this._options.applicationId)throw new Error("Init needs to be called with a valid application Id before calling identify User.");var r={user_id:e};t&&(r.metadata=t),this._session&&(r.session_token=this._session),this._campaign&&(r.campaign=this._campaign),this._companyId&&(r.company_id=this._companyId),r.anonymous_id=this._anonymousId,this.updateUser(r,this._options.applicationId,this._options.host,this._options.callback);try{e&&this._persist(fe,e)}catch(e){M.error("error saving to local storage")}}},updateCompany:function(e,t,r,n){this._executeRequest(Je+r+Ne,e,{applicationId:t},n)},identifyCompany:function(e,t,r){if(T.isNil(e))M.critical("identifyCompany called with nil companyId.");else{var n=!!this._companyId;if(this._companyId=e,!this._options||!this._options.applicationId)throw new Error("Init needs to be called with a valid application Id before calling identify User.");var i={company_id:e};r&&(i.company_domain=r),t&&(i.metadata=t),this._session&&(i.session_token=this._session);var o=n?this._campaign:function(e){var t=null,r=null;try{(r=be(me,e))&&(t=T.JSONDecode(r))}catch(e){Se.error("failed to decode company campaign data "+r),Se.error(e)}return t}(this._options)||this._campaign;o&&(i.campaign=o),this.updateCompany(i,this._options.applicationId,this._options.host,this._options.callback);try{e&&this._persist(de,e)}catch(e){M.error("error saving to local storage")}}},identifySession:function(e){if(T.isNil(e))M.critical("identifySession called with nil");else if(this._session=e,e)try{this._persist(he,e)}catch(e){M.error("local storage error")}},track:function(e,t){if(!e)throw new Error("track name must have action Name defined");var r={action_name:e};this._companyId&&(r.company_id=this._companyId),this._userId?r.user_id=this._userId:r.anonymous_id=this._anonymousId,this._session&&(r.session_token=this._session),r.request={uri:document.location.href,verb:"GET",user_agent_string:navigator.userAgent},r.transaction_id=T.uuid4(),t&&(r.metadata=t);var n=Je+this._options.host+Ue;return M.log("sending or queuing: "+e),this._sendOrBatch(r,this._options.applicationId,n,this.requestBatchers.actions,this._options.callback)},recordEvent:function(e){if(We(e))M.log("skipped logging for requests to moesif");else{M.log("determining if should log: "+e.request.uri);var t=Object.assign({},e);if(this._getUserId()?t.user_id=this._getUserId():t.anonymous_id=this._anonymousId,this._getCompanyId()&&(t.company_id=this._getCompanyId()),this._getSession()&&(t.session_token=this._getSession()),t.tags=this._options.getTags(e)||"",this._options.apiVersion&&(t.request.api_version=this._options.apiVersion),t.request.headers["User-Agent"]||(t.request.headers["User-Agent"]=window.navigator.userAgent),t.transaction_id=T.uuid4(),this._options.maskContent&&(t=this._options.maskContent(t)),this._options.getMetadata)if(t.metadata){var r=this._options.getMetadata(t);t.metadata=Object.assign(t.metadata,r)}else t.metadata=this._options.getMetadata(t);if(this._options.skip(e)||We(e))M.log("skipped logging for "+e.request.uri);else{M.log("sending or queuing: "+e.request.uri);var n=Je+this._options.host+Ce;this._sendOrBatch(t,this._options.applicationId,n,this.requestBatchers.events,this._options.callback)}}},_getUserId:function(){return this._userId},_getCompanyId:function(){return this._companyId},_getSession:function(){return this._session},stop:function(){this._stopRecording&&(this._stopRecording(),this._stopRecording=null),this._stopWeb3Recording&&(this._stopWeb3Recording(),this._stopWeb3Recording=null),this._stopFetchRecording&&(this._stopFetchRecording(),this._stopFetchRecording=null)},clearCookies:function(){_e(this._options)},clearStorage:function(){we(this._options)},resetAnonymousId:function(){return this._anonymousId=Me(this._persist),this._anonymousId},reset:function(){_e(this._options),we(this._options),this._anonymousId=Me(this._persist),this._companyId=null,this._userId=null,this._session=null,this._campaign=null}}}return(He=$e()).new=$e,He}()},function(e,t,r){!function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={exports:{},id:n,loaded:!1};return e[n].call(i.exports,i,i.exports,r),i.loaded=!0,i.exports}r.m=e,r.c=t,r.p="",r(0)}([function(e,t,r){var n=r(1);n.init({applicationId:"Your Application ID",debug:!0}),n.start()},function(e,t,r){e.exports=function(){"use strict";var e,t=!1,r="1.5.9";e="undefined"==typeof window?{navigator:{}}:window;var n,i,o,s,a,c,u,l,f,d,h,p=Array.prototype,g=Function.prototype,m=Object.prototype,v=p.slice,y=m.toString,b=m.hasOwnProperty,_=e.console,w=e.navigator,S=e.document,I=w.userAgent,k=g.bind,E=p.forEach,O=p.indexOf,x=p.map,q=Array.isArray,B={},A={trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},T={log:function(){if(t&&!A.isUndefined(_)&&_)try{_.log.apply(_,arguments)}catch(e){A.each(arguments,(function(e){_.log(e)}))}},error:function(){if(t&&!A.isUndefined(_)&&_){var e=["Moesif error:"].concat(A.toArray(arguments));try{_.error.apply(_,e)}catch(t){A.each(e,(function(e){_.error(e)}))}}},critical:function(){if(!A.isUndefined(_)&&_){var e=["Moesif error:"].concat(A.toArray(arguments));try{_.error.apply(_,e)}catch(t){A.each(e,(function(e){_.error(e)}))}}}};A.bind=function(e,t){var r,n;if(k&&e.bind===k)return k.apply(e,v.call(arguments,1));if(!A.isFunction(e))throw new TypeError;return r=v.call(arguments,2),n=function(){if(!(this instanceof n))return e.apply(t,r.concat(v.call(arguments)));var i={};i.prototype=e.prototype;var o=new i;i.prototype=null;var s=e.apply(o,r.concat(v.call(arguments)));return Object(s)===s?s:o}},A.bind_instance_methods=function(e){for(var t in e)"function"==typeof e[t]&&(e[t]=A.bind(e[t],e))},A.isEmptyString=function(e){return!e||0===e.length},A.each=function(e,t,r){if(null!=e)if(E&&e.forEach===E)e.forEach(t,r);else if(e.length===+e.length){for(var n=0,i=e.length;n/g,">").replace(/"/g,""").replace(/'/g,"'")),t},A.extend=function(e){return A.each(v.call(arguments,1),(function(t){for(var r in t)void 0!==t[r]&&(e[r]=t[r])})),e},A.isArray=q||function(e){return"[object Array]"===y.call(e)},A.isFunction=function(e){try{return/^\s*\bfunction\b/.test(e)}catch(e){return!1}},A.isArguments=function(e){return!(!e||!b.call(e,"callee"))},A.toArray=function(e){return e?e.toArray?e.toArray():A.isArray(e)||A.isArguments(e)?v.call(e):A.values(e):[]},A.map=function(e,t){if(x&&e.map===x)return e.map(t);var r=[];return A.each(e,(function(e){r.push(t(e))})),r},A.values=function(e){var t=[];return null===e||A.each(e,(function(e){t[t.length]=e})),t},A.identity=function(e){return e},A.include=function(e,t){var r=!1;return null===e?r:O&&e.indexOf===O?-1!=e.indexOf(t):(A.each(e,(function(e){if(r||(r=e===t))return B})),r)},A.includes=function(e,t){return-1!==e.indexOf(t)},A.inherit=function(e,t){return e.prototype=new t,e.prototype.constructor=e,e.superclass=t.prototype,e},A.isObject=function(e){return e===Object(e)&&!A.isArray(e)},A.isEmptyObject=function(e){if(A.isObject(e)){for(var t in e)if(b.call(e,t))return!1;return!0}return!1},A.isUndefined=function(e){return void 0===e},A.isString=function(e){return"[object String]"==y.call(e)},A.isDate=function(e){return"[object Date]"==y.call(e)},A.isNumber=function(e){return"[object Number]"==y.call(e)},A.isElement=function(e){return!(!e||1!==e.nodeType)},A.encodeDates=function(e){return A.each(e,(function(t,r){A.isDate(t)?e[r]=A.formatDate(t):A.isObject(t)&&(e[r]=A.encodeDates(t))})),e},A.timestamp=function(){return Date.now=Date.now||function(){return+new Date},Date.now()},A.formatDate=function(e){function t(e){return e<10?"0"+e:e}return e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())},A.safewrap=function(e){return function(){try{return e.apply(this,arguments)}catch(e){T.critical("Implementation error. Please contact support@moesif.com.")}}},A.safewrap_class=function(e,t){for(var r=0;r0&&(t[r]=e)})),t},A.truncate=function(e,t){var r;return"string"==typeof e?r=e.slice(0,t):A.isArray(e)?(r=[],A.each(e,(function(e){r.push(A.truncate(e,t))}))):A.isObject(e)?(r={},A.each(e,(function(e,n){r[n]=A.truncate(e,t)}))):r=e,r},A.JSONEncode=function(e){var t=function(e){var t=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};return t.lastIndex=0,t.test(e)?'"'+e.replace(t,(function(e){var t=r[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)}))+'"':'"'+e+'"'},r=function(e,n){var i="",o=0,s="",a="",c=0,u=i,l=[],f=n[e];switch(f&&"object"==typeof f&&"function"==typeof f.toJSON&&(f=f.toJSON(e)),typeof f){case"string":return t(f);case"number":return isFinite(f)?String(f):"null";case"boolean":case"null":return String(f);case"object":if(!f)return"null";if(i+=" ",l=[],"[object Array]"===y.apply(f)){for(c=f.length,o=0;o="0"&&o<="9";)t+=o,l();if("."===o)for(t+=".";l()&&o>="0"&&o<="9";)t+=o;if("e"===o||"E"===o)for(t+=o,l(),"-"!==o&&"+"!==o||(t+=o,l());o>="0"&&o<="9";)t+=o,l();if(e=+t,isFinite(e))return e;u("Bad number")},d=function(){var e,t,r,n="";if('"'===o)for(;l();){if('"'===o)return l(),n;if("\\"===o)if(l(),"u"===o){for(r=0,t=0;t<4&&(e=parseInt(l(),16),isFinite(e));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else{if("string"!=typeof c[o])break;n+=c[o]}else n+=o}u("Bad string")},h=function(){for(;o&&o<=" ";)l()},a=function(){switch(h(),o){case"{":return function(){var e,t={};if("{"===o){if(l("{"),h(),"}"===o)return l("}"),t;for(;o;){if(e=d(),h(),l(":"),Object.hasOwnProperty.call(t,e)&&u('Duplicate key "'+e+'"'),t[e]=a(),h(),"}"===o)return l("}"),t;l(","),h()}}u("Bad object")}();case"[":return function(){var e=[];if("["===o){if(l("["),h(),"]"===o)return l("]"),e;for(;o;){if(e.push(a()),h(),"]"===o)return l("]"),e;l(","),h()}}u("Bad array")}();case'"':return d();case"-":return f();default:return o>="0"&&o<="9"?f():function(){switch(o){case"t":return l("t"),l("r"),l("u"),l("e"),!0;case"f":return l("f"),l("a"),l("l"),l("s"),l("e"),!1;case"n":return l("n"),l("u"),l("l"),l("l"),null}u('Unexpected "'+o+'"')}()}},function(e){var t;return s=e,i=0,o=" ",t=a(),h(),o&&u("Syntax error"),t}),A.base64Encode=function(e){var t,r,n,i,o,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,c=0,u="",l=[];if(!e)return e;e=A.utf8Encode(e);do{t=(o=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,r=o>>12&63,n=o>>6&63,i=63&o,l[c++]=s.charAt(t)+s.charAt(r)+s.charAt(n)+s.charAt(i)}while(a127&&s<2048?String.fromCharCode(s>>6|192,63&s|128):String.fromCharCode(s>>12|224,s>>6&63|128,63&s|128),null!==a&&(r>t&&(o+=e.substring(t,r)),o+=a,t=r=i+1)}return r>t&&(o+=e.substring(t,e.length)),o},A.UUID=(n=function(){for(var e=1*new Date,t=0;e==1*new Date;)t++;return e.toString(16)+t.toString(16)},function(){var e=(screen.height*screen.width).toString(16);return n()+"-"+Math.random().toString(16).replace(".","")+"-"+function(){var e,t,r=I,n=[],i=0;function o(e,t){var r,i=0;for(r=0;r=4&&(i=o(i,n),n=[]);return n.length>0&&(i=o(i,n)),i.toString(16)}()+"-"+e+"-"+n()}),A.isBlockedUA=function(e){return!!/(google web preview|baiduspider|yandexbot|bingbot|googlebot|yahoo! slurp)/i.test(e)},A.HTTPBuildQuery=function(e,t){var r,n,i=[];return A.isUndefined(t)&&(t="&"),A.each(e,(function(e,t){r=encodeURIComponent(e.toString()),n=encodeURIComponent(t),i[i.length]=n+"="+r})),i.join(t)},A.getQueryParamByName=function(e,t){e=e.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var r=new RegExp("[\\?&]"+e+"=([^]*)").exec(t);return null===r?void 0:decodeURIComponent(r[1].replace(/\+/g," "))},A.getQueryParam=function(e,t){t=t.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var r=new RegExp("[\\?&]"+t+"=([^]*)").exec(e);return null===r||r&&"string"!=typeof r[1]&&r[1].length?"":decodeURIComponent(r[1]).replace(/\+/g," ")},A.getHashParam=function(e,t){var r=e.match(new RegExp(t+"=([^&]*)"));return r?r[1]:null},A.cookie={get:function(e){for(var t=e+"=",r=S.cookie.split(";"),n=0;n=0}function n(t){if(!S.getElementsByTagName)return[];var n,i,o,s,a,c,u,l,f,d,h=t.split(" "),p=[S];for(c=0;c-1){o=(i=n.split("#"))[0];var g=i[1],m=S.getElementById(g);if(!m||o&&m.nodeName.toLowerCase()!=o)return[];p=[m]}else if(n.indexOf(".")>-1){o=(i=n.split("."))[0];var v=i[1];for(o||(o="*"),s=[],a=0,u=0;u-1};break;default:b=function(e){return e.getAttribute(_)}}for(p=[],d=0,u=0;u=3?t[2]:""},properties:function(){return A.extend(A.strip_empty_properties({$os:A.info.os(),$browser:A.info.browser(I,w.vendor,window.opera),$referrer:S.referrer,$referring_domain:A.info.referringDomain(S.referrer),$device:A.info.device(I)}),{$current_url:window.location.href,$browser_version:A.info.browserVersion(I,w.vendor,window.opera),$screen_height:screen.height,$screen_width:screen.width,mp_lib:"web",$lib_version:r})},people_properties:function(){return A.extend(A.strip_empty_properties({$os:A.info.os(),$browser:A.info.browser(I,w.vendor,window.opera)}),{$browser_version:A.info.browserVersion(I,w.vendor,window.opera)})},pageviewInfo:function(e){return A.strip_empty_properties({mp_page:e,mp_referrer:S.referrer,mp_browser:A.info.browser(I,w.vendor,window.opera),mp_platform:A.info.os()})}};var C=function(e){var t=Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10);return e?t.substring(0,e):t},D=function(e,t){return function(){return arguments[0]="["+t+"] "+arguments[0],e.apply(T,arguments)}},U=function(e){return{log:D(T.log,e),error:D(T.error,e),critical:D(T.critical,e)}},F=null,P=null;"undefined"!=typeof JSON&&(F=JSON.stringify,P=JSON.parse),F=F||A.JSONEncode,P=P||A.JSONDecode,A.toArray=A.toArray,A.isObject=A.isObject,A.JSONEncode=A.JSONEncode,A.JSONDecode=A.JSONDecode,A.isBlockedUA=A.isBlockedUA,A.isEmptyObject=A.isEmptyObject,A.isEmptyString=A.isEmptyString,A.each=A.each,A.info=A.info,A.info.device=A.info.device,A.info.browser=A.info.browser,A.info.properties=A.info.properties;var N=U("capture"),j="http:"===(document&&document.location.protocol)?"http://":"https://";function z(e){var t={};if(!e)return t;for(var r=e.split("\r\n"),n=0;n0&&(t[i.substring(0,o)]=i.substring(o+2))}return t}function L(e){if(e&&"string"==typeof e){var t=A.trim(e);return 0!==t.indexOf("http")?j+window.location.host+"/"+t.replace(/^\./,"").replace(/^\//,""):e}return e}var H=U("web3capture");function J(e){return e&&e.host?e.host:"/"}function W(e,t,r,n,i,o){var s={uri:J(e),verb:"POST",time:t,headers:{}};if(e.headers){var a={};A.each(e.headers,(function(e){a[e.name]=e.value})),s.headers=a}if(n)if("string"==typeof n){H.log("request post data is string"),H.log(n);try{s.body=A.JSONDecode(n)}catch(e){H.log("JSON decode failed"),H.log(e),s.transfer_encoding="base64",s.body=A.base64Encode(n)}}else("object"==typeof n||Array.isArray(n)||"number"==typeof n||"boolean"==typeof postData)&&(s.body=n);var c={status:200,time:r,headers:{}};i?c.body=i:o&&(c.body={error:o});var u={request:s,response:c,metadata:{_web3:{via_web3_provider:!0,path:e.path,host:e.host}}};return e.isMetaMask&&(u.metadata._web3.is_metamask=!0),u}function $(e,t,r){if(e.currentProvider){H.log("found my currentProvider, patching it");var n=e.currentProvider,i=n.send,o=n.sendAsync;return n.send=function(e){H.log("patched send is called"),H.log(e);var r=(new Date).toISOString(),o=i.apply(n,arguments);H.log("patch send result is back"),H.log(o);var s=(new Date).toISOString();return t&&t(W(n,r,s,e,o)),o},n.sendAsync=function(e,r){H.log("patched sendAsync is called"),H.log(e);var i=(new Date).toISOString(),s=n;o.apply(n,[e,function(n,o){var a=(new Date).toISOString();H.log("inside patched callback"),H.log(o),t&&t(W(s,i,a,e,o,n)),r&&r(n,o)}])},function(){n.send=i,n.sendAsync=o}}return null}var Q=U("captureFetch");function K(e){if(!e)return{};if(Q.log("about to decode buffer"),Q.log(e),Q.log(e.byteLength),e.byteLength<=0)return{};try{var t=new TextDecoder("utf-8").decode(e);try{return{body:A.JSONDecode(t)}}catch(e){return Q.error(e),{transfer_encoding:"base64",body:A.base64Encode(t)}}}catch(t){return Q.error(t),Q.log(e),{transfer_encoding:"base64",body:"can not be decoded"}}}function V(e){var t={};Q.log("parseheaders is called");for(var r=e.entries(),n=r.next();!n.done;)Q.log(n.value),t[n.value[0]]=n.value[1],n=r.next();return t}function X(e,t,r,n){var i=null;try{i=new Request(r,n)}catch(e){}var o=(new Date).toISOString(),s=null,a=null;a=t(r,n);var c=null;return a=a.then((function(t){return c=t.clone(),s=(new Date).toISOString(),function(e,t,r,n,i){try{setTimeout((function(){if(Q.log("interception is here."),Q.log(e),Q.log(t),e&&t)try{Promise.all([e.arrayBuffer(),t.arrayBuffer()]).then((function(o){var s=o.map(K),a=Object.assign(s[0],{uri:e.url,verb:e.method,time:r,headers:V(e.headers)}),c=Object.assign(s[1],{status:t.status,time:n,headers:V(t.headers)});Q.log(a),Q.log(c),i({request:a,response:c})}))}catch(e){Q.error("error processing body")}else Q.log("savedRequest")}),50)}catch(e){Q.error("error processing saved fetch request and response, but move on anyways."),Q.log(e)}}(i,c,o,s,e),t}))}function G(e){if(A.isEmptyString(e))return null;var t=e.split("/");return t.length>=3?t[2]:null}function Y(){var e=document&&document.referrer;if(!A.isEmptyString(e))return{referrer:e,referring_domain:G(e)}}var Z=U("utm"),ee="utm_source",te="utm_medium",re="utm_campaign",ne="utm_term",ie="utm_content";function oe(e,t){return e=location&&location.search,function(e,t){var r=e?"?"+e.split(".").slice(-1)[0].replace(/\|/g,"&"):"";Z.log("cookie"),Z.log(r);var n=function(e,t,r,n){return A.getQueryParamByName(e,t)||A.getQueryParamByName(r,n)},i=n(ee,t,"utmcsr",r),o=n(te,t,"utmcmd",r),s=n(re,t,"utmccn",r),a=n(ne,t,"utmctr",r),c=n(ie,t,"utmcct",r),u={},l=function(e,t){A.isEmptyString(t)||(u[e]=t)};return l(ee,i),l(te,o),l(re,s),l(ne,a),l(ie,c),u}(A.cookie.get("__utmz"),e)}var se=U("campaign");function ae(e){try{var t={};if(e.disableUtm||(t=oe()||{}),!e.disableReferer){var r=Y();r&&(t.referrer=r.referrer,t.referring_domain=r.referring_domain)}if(!e.disableRGclid){var n=function(e){var t=A.getQueryParamByName("gclid",e);if(!A.isEmptyString(t))return t}(location&&location.search);n&&(t.gclid=n)}return t}catch(e){se.log(e)}}var ce=U("lock"),ue=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||window.localStorage,this.pollIntervalMS=t.pollIntervalMS||100,this.timeoutMS=t.timeoutMS||2e3};ue.prototype.withLock=function(e,t,r){r||"function"==typeof t||(r=t,t=null);var n=r||(new Date).getTime()+"|"+Math.random(),i=(new Date).getTime(),o=this.storageKey,s=this.pollIntervalMS,a=this.timeoutMS,c=this.storage,u=o+":X",l=o+":Y",f=o+":Z",d=function(e){t&&t(e)},h=function(e){if((new Date).getTime()-i>a)return ce.error("Timeout waiting for mutex on "+o+"; clearing lock. ["+n+"]"),c.removeItem(f),c.removeItem(l),void m();setTimeout((function(){try{e()}catch(e){d(e)}}),s*(Math.random()+.1))},p=function(e,t){e()?t():h((function(){p(e,t)}))},g=function(){var e=c.getItem(l);if(e&&e!==n)return!1;if(c.setItem(l,n),c.getItem(l)===n)return!0;if(!R(c,!0))throw new Error("localStorage support dropped while acquiring lock");return!1},m=function(){c.setItem(u,n),p(g,(function(){c.getItem(u)!==n?h((function(){c.getItem(l)===n?p((function(){return!c.getItem(f)}),v):m()})):v()}))},v=function(){c.setItem(f,"1");try{e()}finally{c.removeItem(f),c.getItem(l)===n&&c.removeItem(l),c.getItem(u)===n&&c.removeItem(u)}};try{if(!R(c,!0))throw new Error("localStorage support check failed");m()}catch(e){d(e)}};var le=U("batch"),fe=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||window.localStorage,this.lock=new ue(e,{storage:this.storage}),this.pid=t.pid||null,this.memQueue=[]};fe.prototype.enqueue=function(e,t,r){var n={id:C(),flushAfter:(new Date).getTime()+2*t,payload:e};this.lock.withLock(A.bind((function(){var t;try{var i=this.readFromStorage();i.push(n),(t=this.saveToStorage(i))&&(le.log("succeeded saving to storage"),this.memQueue.push(n))}catch(r){le.error("Error enqueueing item",e),t=!1}r&&r(t)}),this),(function(e){le.error("Error acquiring storage lock",e),r&&r(!1)}),this.pid)},fe.prototype.fillBatch=function(e){var t=this.memQueue.slice(0,e);if(t.lengtho.flushAfter&&!n[o.id]&&(t.push(o),t.length>=e))break}}}return t};var de=function(e,t){var r=[];return A.each(e,(function(e){e.id&&!t[e.id]&&r.push(e)})),r};fe.prototype.removeItemsByID=function(e,t){var r={};A.each(e,(function(e){r[e]=!0})),this.memQueue=de(this.memQueue,r),this.lock.withLock(A.bind((function(){var n;try{var i=this.readFromStorage();i=de(i,r),le.log(i.length),n=this.saveToStorage(i)}catch(t){le.error("Error removing items",e),n=!1}t&&(le.log("triggering callback of removalItems"),t(n))}),this),(function(e){le.error("Error acquiring storage lock",e),t&&t(!1)}),this.pid)},fe.prototype.readFromStorage=function(){var e;try{le.log("trying to get storage with storage key "+this.storageKey),(e=this.storage.getItem(this.storageKey))?(e=P(e),A.isArray(e)||(le.error("Invalid storage entry:",e),e=null)):le.log("storageEntry is empty")}catch(t){le.error("Error retrieving queue",t),e=null}return e||[]},fe.prototype.saveToStorage=function(e){try{return this.storage.setItem(this.storageKey,F(e)),!0}catch(e){return le.error("Error saving queue",e),!1}},fe.prototype.clear=function(){this.memQueue=[],this.storage.removeItem(this.storageKey)};var he=U("batch"),pe=function(e,t,r){this.queue=new fe(e,{storage:r.storage}),this.endpoint=t,this.libConfig=r.libConfig,this.sendRequest=r.sendRequestFunc,this.batchSize=this.libConfig.batch_size,this.flushInterval=this.libConfig.batch_flush_interval_ms,this.stopped=!1};pe.prototype.enqueue=function(e,t){this.queue.enqueue(e,this.flushInterval,t)},pe.prototype.start=function(){this.stopped=!1,this.flush()},pe.prototype.stop=function(){this.stopped=!0,this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null)},pe.prototype.clear=function(){this.queue.clear()},pe.prototype.resetBatchSize=function(){this.batchSize=this.libConfig.batch_size},pe.prototype.resetFlush=function(){this.scheduleFlush(this.libConfig.batch_flush_interval_ms)},pe.prototype.scheduleFlush=function(e){this.flushInterval=e,this.stopped||(this.timeoutID=setTimeout(A.bind(this.flush,this),this.flushInterval))},pe.prototype.flush=function(e){try{if(this.requestInProgress)return void he.log("Flush: Request already in progress");e=e||{};var t=this.batchSize,r=this.queue.fillBatch(t);if(he.log("current batch size is "+r.length),r.length<1)return void this.resetFlush();this.requestInProgress=!0;var n=this.libConfig.batch_request_timeout_ms,i=(new Date).getTime(),o=A.map(r,(function(e){return e.payload})),s=A.bind((function(e){this.requestInProgress=!1;try{var o=!1;if(A.isObject(e)&&"timeout"===e.error&&(new Date).getTime()-i>=n)he.error("Network timeout; retrying"),this.flush();else if(A.isObject(e)&&e.xhr_req&&(e.xhr_req.status>=500||e.xhr_req.status<=0)){var s=2*this.flushInterval,a=e.xhr_req.responseHeaders;if(a){var c=a["Retry-After"];c&&(s=1e3*parseInt(c,10)||s)}s=Math.min(6e5,s),he.error("Error; retry in "+s+" ms"),this.scheduleFlush(s)}else if(A.isObject(e)&&e.xhr_req&&413===e.xhr_req.status)if(r.length>1){var u=Math.max(1,Math.floor(t/2));this.batchSize=Math.min(this.batchSize,u,r.length-1),he.error("413 response; reducing batch size to "+this.batchSize),this.resetFlush()}else he.error("Single-event request too large; dropping",r),this.resetBatchSize(),o=!0;else o=!0;o&&this.queue.removeItemsByID(A.map(r,(function(e){return e.id})),A.bind(this.flush,this))}catch(e){he.error("Error handling API response",e),this.resetFlush()}}),this),a={method:"POST",verbose:!0,ignore_json_errors:!0,timeout_ms:n};e.sendBeacon&&(a.transport="sendBeacon"),he.log("Moesif Request:",this.endpoint,o),this.sendRequest(this.endpoint,o,a,s)}catch(e){he.error("Error flushing request queue",e),this.resetFlush()}};var ge="api.moesif.net",me="/v1/events",ve="/v1/events/batch",ye="/v1/actions",be="/v1/actions/batch",_e="/v1/users",we="/v1/companies",Se="moesif_stored_user_id",Ie="moesif_stored_company_id",ke="moesif_stored_session_id",Ee=window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,Oe=(!Ee&&-1===I.indexOf("MSIE")&&I.indexOf("Mozilla"),null);navigator.sendBeacon&&(Oe=function(){return navigator.sendBeacon.apply(navigator,arguments)});var xe="http:"===(document&&document.location.protocol)?"http://":"https://";function qe(e){try{return e.request.headers["X-Moesif-SDK"]}catch(e){return!1}}function Be(){return T.log("moesif object creator is called"),{init:function(e){window||T.critical("Warning, this library need to be initiated on the client side"),function(e){if(!e)throw new Error("options are required by moesif-express middleware");if(!e.applicationId)throw new Error("A moesif application id is required. Please obtain it through your settings at www.moesif.com");if(e.getTags&&!A.isFunction(e.getTags))throw new Error("getTags should be a function");if(e.getMetadata&&!A.isFunction(e.getMetadata))throw new Error("getMetadata should be a function");if(e.getApiVersion&&!A.isFunction(e.getApiVersion))throw new Error("identifyUser should be a function");if(e.maskContent&&!A.isFunction(e.maskContent))throw new Error("maskContent should be a function");if(e.skip&&!A.isFunction(e.skip))throw new Error("skip should be a function")}(e);var t={};t.getTags=e.getTags||function(){},t.maskContent=e.maskContent||function(e){return e},t.getMetadata=e.getMetadata||function(){},t.skip=e.skip||function(){return!1},t.debug=e.debug,t.callback=e.callback,t.applicationId=e.applicationId,t.apiVersion=e.apiVersion,t.disableFetch=e.disableFetch,t.disableReferrer=e.disableReferrer,t.disableGclid=e.disableGclid,t.disableUtm=e.disableUtm,t.batch=e.batch||!1,t.batch_size=e.batchSize||50,t.batch_flush_interval_ms=e.batchIntervalMs||5e3,t.batch_request_timeout_ms=e.batchTimeoutMs||9e4,this.requestBatchers={},this._options=t;try{this._userId=localStorage.getItem(Se),this._session=localStorage.getItem(ke),this._companyId=localStorage.getItem(Ie),this._campaign=ae(t)}catch(e){T.error("error loading saved data from local storage but continue")}return t.batch&&(R&&Ee?(this.initBatching(),Oe&&window.addEventListener&&window.addEventListener("unload",A.bind((function(){this.requestBatchers.events.flush({sendBeacon:!0})}),this))):(t.batch=!1,T.log("Turning off batch processing because it needs XHR and localStorage"))),T.log("moesif initiated"),this},_executeRequest:function(e,t,n,i){var o=n&&n.applicationId||this._options.applicationId,s=n&&n.method||"POST";try{var a=new XMLHttpRequest;if(a.open(s,e),a.setRequestHeader("Content-Type","application/json"),a.setRequestHeader("X-Moesif-Application-Id",o),a.setRequestHeader("X-Moesif-SDK","moesif-browser-js/"+r),n.timeout_ms&&void 0!==a.timeout){a.timeout=n.timeout_ms;var c=(new Date).getTime()}a.onreadystatechange=function(){var e;if(4===a.readyState)if(a.status>=200&&a.status<=300){if(i){var t=XMLHttpRequest.responseText;i(t)}}else e=a.timeout&&!a.status&&(new Date).getTime()-c>=a.timeout?"timeout":"Bad HTTP status: "+a.status+" "+a.statusText,T.error(e),i&&i({status:0,error:e,xhr_req:a})},a.send(F(t))}catch(e){T.error("failed to send event to moesif"+event.request.uri),T.error(e),i&&i({status:0,error:e})}},initBatching:function(){var e=this._options.applicationId;if(T.log("does requestBatch.events exists? "+this.requestBatchers.events),!this.requestBatchers.events){var t={libConfig:this._options,sendRequestFunc:A.bind((function(e,t,r,n){this._executeRequest(e,t,r,n)}),this)},r=new pe("__mf_"+e+"_ev",xe+ge+ve,t),n=new pe("__mf_"+e+"_ac",xe+ge+be,t);this.requestBatchers={events:r,actions:n}}A.each(this.requestBatchers,(function(e){e.start()}))},_sendOrBatch:function(e,t,r,n,i){var o=!0;if(this._options.batch&&n)T.log("current batcher storage key is "+n.queue.storageKey),n.enqueue(e);else{var s={applicationId:t};o=this._executeRequest(r,e,s,i)}return o},start:function(e){var t=this;if(this._stopRecording||this._stopWeb3Recording)return T.log("recording has already started, please call stop first."),!1;function r(e){t.recordEvent(e)}return T.log("moesif starting"),this._stopRecording=function(e){var t=XMLHttpRequest.prototype,r=t.open,n=t.send,i=t.setRequestHeader;return t.open=function(e,t){return this._method=e,this._url=t,this._requestHeaders={},this._startTime=(new Date).toISOString(),r.apply(this,arguments)},t.setRequestHeader=function(e,t){return this._requestHeaders[e]=t,i.apply(this,arguments)},t.send=function(t){return this.addEventListener("load",(function(){var r=(new Date).toISOString();if(e){var n=this._url?this._url.toLowerCase():this._url;if(n&&n.indexOf("moesif.com")<0&&n.indexOf("apirequest.io")<0){var i={uri:L(this._url),verb:this._method,time:this._startTime,headers:this._requestHeaders};if(t)if("string"==typeof t){N.log("request post data is string"),N.log(t);try{i.body=A.JSONDecode(t)}catch(e){N.log("JSON decode failed"),N.log(e),i.transfer_encoding="base64",i.body=A.base64Encode(t)}}else("object"==typeof t||Array.isArray(t)||"number"==typeof t||"boolean"==typeof t)&&(i.body=t);var o=z(this.getAllResponseHeaders()),s={status:this.status,time:r,headers:o};if(this.responseText)try{s.body=A.JSONDecode(this.responseText)}catch(e){s.transfer_encoding="base64",s.body=A.base64Encode(this.responseText)}e({request:i,response:s})}}})),n.apply(this,arguments)},function(){t.open=r,t.send=n,t.setRequestHeader=i}}(r),this._options.disableFetch||(T.log("also instrumenting fetch API"),this._stopFetchRecording=function(e,t){var r,n=t||window||self;if(n.fetch){if(Q.log("found fetch method."),n.fetch.polyfill)return Q.log("skip patching fetch since it is polyfilled"),null;var i=n.fetch;return Q.log("fetch is not polyfilled so instrumenting it"),n.fetch=(r=n.fetch,function(t,n){return X(e,r,t,n)}),function(){n.fetch=i}}Q.log("there is no fetch found, so skipping instrumentation.")}(r)),this.useWeb3(e),!0},useWeb3:function(e){var t=this;function r(e){t.recordEvent(e)}return this._stopWeb3Recording&&(this._stopWeb3Recording(),this._stopWeb3Recording=null),e?this._stopWeb3Recording=$(e,r,this._options):window.web3&&(T.log("found global web3, will capture from it"),this._stopWeb3Recording=$(window.web3,r,this._options)),!!this._stopWeb3Recording},updateUser:function(e,t,r){this._executeRequest(xe+ge+_e,e,{applicationId:t},r)},identifyUser:function(e,t){if(this._userId=e,!this._options||!this._options.applicationId)throw new Error("Init needs to be called with a valid application Id before calling identify User.");var r={user_id:e};t&&(r.metadata=t),this._session&&(r.session_token=this._session),this._campaign&&(r.campaign=this._campaign),this._companyId&&(r.company_id=this._companyId),this.updateUser(r,this._options.applicationId,this._options.callback);try{localStorage.setItem(Se,e)}catch(e){T.error("error saving to local storage")}},updateCompany:function(e,t,r){this._executeRequest(xe+ge+we,e,{applicationId:t},r)},identifyCompany:function(e,t,r){if(this._companyId=e,!this._options||!this._options.applicationId)throw new Error("Init needs to be called with a valid application Id before calling identify User.");var n={company_id:e};r&&(n.company_domain=r),t&&(n.metadata=t),this._session&&(n.session_token=this._session),this._campaign&&(n.campaign=this._campaign),this.updateCompany(n,this._options.applicationId,this._options.callback);try{localStorage.setItem(Ie,e)}catch(e){T.error("error saving to local storage")}},identifySession:function(e){this._session=e,localStorage.setItem(ke,e)},track:function(e,t){if(!e)throw new Error("track name must have action Name defined");var r={action_name:e};this._companyId&&(r.company_id=this._companyId),this._userId&&(r.user_id=this._userId),this._session&&(r.session_token=this._session),r.request={uri:document.location.href,verb:"GET",user_agent_string:navigator.userAgent},t&&(r.metadata=t);var n=xe+ge+ye;return T.log("sending or queuing: "+e),this._sendOrBatch(r,this._options.applicationId,n,this.requestBatchers.actions,this._options.callback)},recordEvent:function(e){if(qe(e))T.log("skipped logging for requests to moesif");else{T.log("determining if should log: "+e.request.uri);var t=Object.assign({},e);if(this._getUserId()&&(t.user_id=this._getUserId()),this._getCompanyId()&&(t.company_id=this._getCompanyId()),this._getSession()&&(t.session_token=this._getSession()),t.tags=this._options.getTags(e)||"",this._options.apiVersion&&(t.request.api_version=this._options.apiVersion),this._options.maskContent&&(t=this._options.maskContent(t)),this._options.getMetadata)if(t.metadata){var r=this._options.getMetadata(t);t.metadata=Object.assign(t.metadata,r)}else t.metadata=this._options.getMetadata(t);if(this._options.skip(e)||qe(e))T.log("skipped logging for "+e.request.uri);else{T.log("sending or queuing"+e.request.uri);var n=xe+ge+me;this._sendOrBatch(t,this._options.applicationId,n,this.requestBatchers.events,this._options.callback)}}},_getUserId:function(){return this._userId},_getCompanyId:function(){return this._companyId},_getSession:function(){return this._session},stop:function(){this._stopRecording&&(this._stopRecording(),this._stopRecording=null),this._stopWeb3Recording&&(this._stopWeb3Recording(),this._stopWeb3Recording=null),this._stopFetchRecording&&(this._stopFetchRecording(),this._stopFetchRecording=null)}}}return Be()}()}])}]);
\ No newline at end of file
+!function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t,r){r(1),e.exports=r(3)},function(e,t,r){var n=r(2);n.init({applicationId:"Your Application ID"}),n.start()},function(e,t,r){e.exports=function(){"use strict";var e,t={DEBUG:!1,LIB_VERSION:"1.8.13"};if("undefined"==typeof window){var r={hostname:""};e={navigator:{userAgent:""},document:{location:r,referrer:""},screen:{width:0,height:0},location:r}}else e=window;var n,i,o,s,a,c,u,l,f,h,d=Array.prototype,p=Function.prototype,g=Object.prototype,m=d.slice,v=g.toString,y=g.hasOwnProperty,b=e.console,_=e.navigator,w=e.document,S=e.opera,I=e.screen,k=_.userAgent,E=p.bind,O=d.forEach,x=d.indexOf,q=d.map,B=Array.isArray,A={},C={trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},R={log:function(){if(t.DEBUG&&!C.isUndefined(b)&&b)try{b.log.apply(b,arguments)}catch(e){C.each(arguments,(function(e){b.log(e)}))}},error:function(){if(t.DEBUG&&!C.isUndefined(b)&&b){var e=["Moesif error:"].concat(C.toArray(arguments));try{b.error.apply(b,e)}catch(t){C.each(e,(function(e){b.error(e)}))}}},critical:function(){if(!C.isUndefined(b)&&b){var e=["Moesif error:"].concat(C.toArray(arguments));try{b.error.apply(b,e)}catch(t){C.each(e,(function(e){b.error(e)}))}}}},T=function(e,t){return function(){return arguments[0]="["+t+"] "+arguments[0],e.apply(R,arguments)}},D=function(e){return{log:T(R.log,e),error:T(R.error,e),critical:T(R.critical,e)}};C.bind=function(e,t){var r,n;if(E&&e.bind===E)return E.apply(e,m.call(arguments,1));if(!C.isFunction(e))throw new TypeError;return r=m.call(arguments,2),n=function(){if(!(this instanceof n))return e.apply(t,r.concat(m.call(arguments)));var i={};i.prototype=e.prototype;var o=new i;i.prototype=null;var s=e.apply(o,r.concat(m.call(arguments)));return Object(s)===s?s:o}},C.bind_instance_methods=function(e){for(var t in e)"function"==typeof e[t]&&(e[t]=C.bind(e[t],e))},C.each=function(e,t,r){if(null!=e)if(O&&e.forEach===O)e.forEach(t,r);else if(e.length===+e.length){for(var n=0,i=e.length;n/g,">").replace(/"/g,""").replace(/'/g,"'")),t},C.extend=function(e){return C.each(m.call(arguments,1),(function(t){for(var r in t)void 0!==t[r]&&(e[r]=t[r])})),e},C.isArray=B||function(e){return"[object Array]"===v.call(e)},C.isFunction=function(e){try{return/^\s*\bfunction\b/.test(e)}catch(e){return!1}},C.isArguments=function(e){return!(!e||!y.call(e,"callee"))},C.toArray=function(e){return e?e.toArray?e.toArray():C.isArray(e)||C.isArguments(e)?m.call(e):C.values(e):[]},C.map=function(e,t){if(q&&e.map===q)return e.map(t);var r=[];return C.each(e,(function(e){r.push(t(e))})),r},C.keys=function(e){var t=[];return null===e||C.each(e,(function(e,r){t[t.length]=r})),t},C.values=function(e){var t=[];return null===e||C.each(e,(function(e){t[t.length]=e})),t},C.identity=function(e){return e},C.include=function(e,t){var r=!1;return null===e?r:x&&e.indexOf===x?-1!=e.indexOf(t):(C.each(e,(function(e){if(r||(r=e===t))return A})),r)},C.includes=function(e,t){return-1!==e.indexOf(t)},C.inherit=function(e,t){return e.prototype=new t,e.prototype.constructor=e,e.superclass=t.prototype,e},C.isArrayBuffer=function(e){var t=Object.prototype.toString;return"function"==typeof ArrayBuffer&&(e instanceof ArrayBuffer||"[object ArrayBuffer]"===t.call(e))},C.isObject=function(e){return e===Object(e)&&!C.isArray(e)},C.isEmptyObject=function(e){if(C.isObject(e)){for(var t in e)if(y.call(e,t))return!1;return!0}return!1},C.isEmptyString=function(e){return!e||0===e.length},C.isUndefined=function(e){return void 0===e},C.isString=function(e){return"[object String]"==v.call(e)},C.isDate=function(e){return"[object Date]"==v.call(e)},C.isNumber=function(e){return"[object Number]"==v.call(e)},C.isElement=function(e){return!(!e||1!==e.nodeType)},C.isNil=function(e){return C.isUndefined(e)||null===e},C.encodeDates=function(e){return C.each(e,(function(t,r){C.isDate(t)?e[r]=C.formatDate(t):C.isObject(t)&&(e[r]=C.encodeDates(t))})),e},C.timestamp=function(){return Date.now=Date.now||function(){return+new Date},Date.now()},C.formatDate=function(e){function t(e){return e<10?"0"+e:e}return e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())},C.safewrap=function(e){return function(){try{return e.apply(this,arguments)}catch(e){R.critical("Implementation error. Please turn on debug and contact support@Moesif.com."),t.DEBUG&&R.critical(e)}}},C.safewrap_class=function(e,t){for(var r=0;r0&&(t[r]=e)})),t},C.truncate=function(e,t){var r;return"string"==typeof e?r=e.slice(0,t):C.isArray(e)?(r=[],C.each(e,(function(e){r.push(C.truncate(e,t))}))):C.isObject(e)?(r={},C.each(e,(function(e,n){r[n]=C.truncate(e,t)}))):r=e,r},C.JSONEncode=function(e){var t=function(e){var t=/[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};return t.lastIndex=0,t.test(e)?'"'+e.replace(t,(function(e){var t=r[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)}))+'"':'"'+e+'"'},r=function(e,n){var i="",o=0,s="",a="",c=0,u=i,l=[],f=n[e];switch(f&&"object"==typeof f&&"function"==typeof f.toJSON&&(f=f.toJSON(e)),typeof f){case"string":return t(f);case"number":return isFinite(f)?String(f):"null";case"boolean":case"null":return String(f);case"object":if(!f)return"null";if(i+=" ",l=[],"[object Array]"===v.apply(f)){for(c=f.length,o=0;o="0"&&i<="9";)t+=i,u();if("."===i)for(t+=".";u()&&i>="0"&&i<="9";)t+=i;if("e"===i||"E"===i)for(t+=i,u(),"-"!==i&&"+"!==i||(t+=i,u());i>="0"&&i<="9";)t+=i,u();if(e=+t,isFinite(e))return e;c("Bad number")},f=function(){var e,t,r,n="";if('"'===i)for(;u();){if('"'===i)return u(),n;if("\\"===i)if(u(),"u"===i){for(r=0,t=0;t<4&&(e=parseInt(u(),16),isFinite(e));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else{if("string"!=typeof a[i])break;n+=a[i]}else n+=i}c("Bad string")},h=function(){for(;i&&i<=" ";)u()},s=function(){switch(h(),i){case"{":return function(){var e,t={};if("{"===i){if(u("{"),h(),"}"===i)return u("}"),t;for(;i;){if(e=f(),h(),u(":"),Object.hasOwnProperty.call(t,e)&&c('Duplicate key "'+e+'"'),t[e]=s(),h(),"}"===i)return u("}"),t;u(","),h()}}c("Bad object")}();case"[":return function(){var e=[];if("["===i){if(u("["),h(),"]"===i)return u("]"),e;for(;i;){if(e.push(s()),h(),"]"===i)return u("]"),e;u(","),h()}}c("Bad array")}();case'"':return f();case"-":return l();default:return i>="0"&&i<="9"?l():function(){switch(i){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}c('Unexpected "'+i+'"')}()}},function(e){var t;return o=e,n=0,i=" ",t=s(),h(),i&&c("Syntax error"),t}),C.base64Encode=function(e){var t,r,n,i,o,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,c=0,u="",l=[];if(!e)return e;e=C.utf8Encode(e);do{t=(o=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,r=o>>12&63,n=o>>6&63,i=63&o,l[c++]=s.charAt(t)+s.charAt(r)+s.charAt(n)+s.charAt(i)}while(a127&&s<2048?String.fromCharCode(s>>6|192,63&s|128):String.fromCharCode(s>>12|224,s>>6&63|128,63&s|128),null!==a&&(r>t&&(o+=e.substring(t,r)),o+=a,t=r=i+1)}return r>t&&(o+=e.substring(t,e.length)),o},C.UUID=function(){var e=(I.height*I.width).toString(16);return function(){for(var e=1*new Date,t=0;e==1*new Date;)t++;return e.toString(16)+t.toString(16)}()+"-"+Math.random().toString(16).replace(".","")+"-"+function(){var e,t,r=k,n=[],i=0;function o(e,t){var r,i=0;for(r=0;r=4&&(i=o(i,n),n=[]);return n.length>0&&(i=o(i,n)),i.toString(16)}()+"-"+e},C.uuid4=function(){var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.split(/[:\/]/g).pop().toLowerCase()},C.isBlockedUA=function(e){return!!/(google web preview|baiduspider|yandexbot|bingbot|googlebot|yahoo! slurp)/i.test(e)},C.HTTPBuildQuery=function(e,t){var r,n,i=[];return C.isUndefined(t)&&(t="&"),C.each(e,(function(e,t){r=encodeURIComponent(e.toString()),n=encodeURIComponent(t),i[i.length]=n+"="+r})),i.join(t)},C.getUrlParams=function(){return location&&(location.search||function(e){if(e){var t=e.indexOf("?");if(t>=0)return e.substring(t)}return""}(location.href))},C.getQueryParamByName=function(e,t){e=e.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var r=new RegExp("[\\?&]"+e+"=([^]*)").exec(t);return null===r?void 0:decodeURIComponent(r[1].replace(/\+/g," "))},C.getQueryParam=function(e,t){t=t.replace(/[[]/,"\\[").replace(/[\]]/,"\\]");var r=new RegExp("[\\?&]"+t+"=([^]*)").exec(e);if(null===r||r&&"string"!=typeof r[1]&&r[1].length)return"";var n=r[1];try{n=decodeURIComponent(n)}catch(e){R.error("Skipping decoding for malformed query param: "+n)}return n.replace(/\+/g," ")},C.getHashParam=function(e,t){var r=e.match(new RegExp(t+"=([^&]*)"));return r?r[1]:null},C.cookie={get:function(e){for(var t=e+"=",r=w.cookie.split(";"),n=0;n=0}function n(t){if(!w.getElementsByTagName)return[];var n,i,o,s,a,c,u,l,f,h,d=t.split(" "),p=[w];for(c=0;c-1){o=(i=n.split("#"))[0];var g=i[1],m=w.getElementById(g);if(!m||o&&m.nodeName.toLowerCase()!=o)return[];p=[m]}else if(n.indexOf(".")>-1){o=(i=n.split("."))[0];var v=i[1];for(o||(o="*"),s=[],a=0,u=0;u-1};break;default:b=function(e){return e.getAttribute(_)}}for(p=[],h=0,u=0;u=3?t[2]:""},properties:function(){return C.extend(C.strip_empty_properties({$os:C.info.os(),$browser:C.info.browser(k,_.vendor,S),$referrer:w.referrer,$referring_domain:C.info.referringDomain(w.referrer),$device:C.info.device(k)}),{$current_url:e.location.href,$browser_version:C.info.browserVersion(k,_.vendor,S),$screen_height:I.height,$screen_width:I.width,mp_lib:"web",$lib_version:t.LIB_VERSION,$insert_id:U(),time:C.timestamp()/1e3})},people_properties:function(){return C.extend(C.strip_empty_properties({$os:C.info.os(),$browser:C.info.browser(k,_.vendor,S)}),{$browser_version:C.info.browserVersion(k,_.vendor,S)})},pageviewInfo:function(e){return C.strip_empty_properties({mp_page:e,mp_referrer:w.referrer,mp_browser:C.info.browser(k,_.vendor,S),mp_platform:C.info.os()})}};var U=function(e){var t=Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10);return e?t.substring(0,e):t},j=function(e){var t=5381;if(0==e.length)return t;for(var r=0;r>>0)%1004||"com"===n||"org"===n)&&(t=N);var i=e.match(t);return i?i[0]:""},H=null,W=null;"undefined"!=typeof JSON&&(H=JSON.stringify,W=JSON.parse),H=H||C.JSONEncode,W=W||C.JSONDecode,C.toArray=C.toArray,C.isObject=C.isObject,C.JSONEncode=C.JSONEncode,C.JSONDecode=C.JSONDecode,C.isBlockedUA=C.isBlockedUA,C.isEmptyObject=C.isEmptyObject,C.isEmptyString=C.isEmptyString,C.info=C.info,C.info.device=C.info.device,C.info.browser=C.info.browser,C.info.browserVersion=C.info.browserVersion,C.info.properties=C.info.properties;var J=D("parsers"),$=function(e){try{return{body:C.JSONDecode(e)}}catch(t){return J.log("JSON decode failed"),J.log(t),{transfer_encoding:"base64",body:C.base64Encode(e)}}},Q=function(e){if(!e)return{};if(J.log("about to decode buffer"),J.log(e),J.log(e.byteLength),e.byteLength<=0)return{};try{var t=new TextDecoder("utf-8").decode(e);try{return{body:C.JSONDecode(t)}}catch(e){return J.error(e),{transfer_encoding:"base64",body:C.base64Encode(t)}}}catch(t){return J.error(t),J.log(e),{transfer_encoding:"base64",body:"can not be decoded"}}},K=D("capture"),V="http:"===(document&&document.location.protocol)?"http://":"https://";function X(e,t,r){K.log("processResponse for"+e._url);var n=(new Date).toISOString();if(r){var i=e._url?e._url.toLowerCase():e._url;if(i&&i.indexOf("moesif.com")<0&&i.indexOf("apirequest.io")<0){var o={uri:G(e._url),verb:e._method,time:e._startTime,headers:e._requestHeaders};if(t)if("string"==typeof t){K.log("request post data is string"),K.log(t);var s=$(t);o.transfer_encoding=s.transfer_encoding,o.body=s.body}else("object"==typeof t||Array.isArray(t)||"number"==typeof t||"boolean"==typeof t)&&(o.body=t);var a=e.getAllResponseHeaders();K.log("rawResponseHeaders are "+a);var c=function(e){var t={};if(!e)return t;for(var r=e.split("\r\n"),n=0;n0){var s=i.substring(0,o);t[s]=i.substring(o+2)}}return t}(a),u=e.status;1223===u&&(u=204);var l={status:u,time:n,headers:c};K.log("responseType: "+e.responseType),K.log("responseText: "+e.responseText),K.log("response: "+e.response);var f=e.responseText,h={};f?(h=$(f),l.body=h.body,l.transfer_encoding=h.transfer_encoding):e.response&&(K.log("no responseText trying with xhr.response"),C.isString(e.response)?(K.log("response is string. attempt to parse"),h=$(e.response),l.body=h.body,l.transfer_encoding=h.transfer_encoding):C.isArrayBuffer(e.response)?(K.log("response is arraybuffer. attempt to parse"),h=Q(e.response),l.body=h.body,l.transfer_encoding=h.transfer_encoding):(C.isArray(e.response)||C.isObject(e.response))&&(l.body=e.response)),r({request:o,response:l})}}}function G(e){if(e&&"string"==typeof e){var t=C.trim(e);return 0!==t.indexOf("http")?V+window.location.host+"/"+t.replace(/^\./,"").replace(/^\//,""):e}return e}var Y=D("web3capture");function Z(e){return e&&e.host?e.host:"/"}function ee(e,t,r,n,i,o){var s={uri:Z(e),verb:"POST",time:t,headers:{}};if(e.headers){var a={};C.each(e.headers,(function(e){a[e.name]=e.value})),s.headers=a}if(n)if("string"==typeof n){Y.log("request post data is string"),Y.log(n);try{s.body=C.JSONDecode(n)}catch(e){Y.log("JSON decode failed"),Y.log(e),s.transfer_encoding="base64",s.body=C.base64Encode(n)}}else("object"==typeof n||Array.isArray(n)||"number"==typeof n||"boolean"==typeof postData)&&(s.body=n);var c={status:200,time:r,headers:{}};i?c.body=i:o&&(c.body={error:o});var u={request:s,response:c,metadata:{_web3:{via_web3_provider:!0,path:e.path,host:e.host}}};return e.isMetaMask&&(u.metadata._web3.is_metamask=!0),u}function te(e,t,r){if(e.currentProvider){Y.log("found my currentProvider, patching it");var n=e.currentProvider,i=n.send,o=n.sendAsync;return n.send=function(e){Y.log("patched send is called"),Y.log(e);var r=(new Date).toISOString(),o=i.apply(n,arguments);Y.log("patch send result is back"),Y.log(o);var s=(new Date).toISOString();return t&&t(ee(n,r,s,e,o)),o},n.sendAsync=function(e,r){Y.log("patched sendAsync is called"),Y.log(e);var i=(new Date).toISOString(),s=n;o.apply(n,[e,function(n,o){var a=(new Date).toISOString();Y.log("inside patched callback"),Y.log(o),t&&t(ee(s,i,a,e,o,n)),r&&r(n,o)}])},function(){n.send=i,n.sendAsync=o}}return null}var re=D("capture fetch");function ne(e){var t={};re.log("parseheaders is called");for(var r=e.entries(),n=r.next();!n.done;)re.log(n.value),t[n.value[0]]=n.value[1],n=r.next();return t}function ie(e,t,r,n){var i=null;try{i=new Request(r,n)}catch(e){}var o=(new Date).toISOString(),s=null,a=null;a=t(r,n);var c=null;return a=a.then((function(t){return c=t.clone(),s=(new Date).toISOString(),function(e,t,r,n,i){try{setTimeout((function(){if(re.log("interception is here."),re.log(e),re.log(t),e&&t)try{Promise.all([e.arrayBuffer(),t.arrayBuffer()]).then((function(o){var s=o.map(Q),a=Object.assign(s[0],{uri:e.url,verb:e.method,time:r,headers:ne(e.headers)}),c=Object.assign(s[1],{status:t.status,time:n,headers:ne(t.headers)});re.log(a),re.log(c),i({request:a,response:c})}))}catch(e){re.error("error processing body")}else re.log("savedRequest")}),50)}catch(e){re.error("error processing saved fetch request and response, but move on anyways."),re.log(e)}}(i,c,o,s,e),t}))}var oe=D("referrer");function se(e){if(C.isEmptyString(e))return null;var t=e.split("/");return t.length>=3?t[2]:null}function ae(){var e=document&&document.referrer;if(oe.log(e),!C.isEmptyString(e)){if(0!==e.indexOf(location.protocol+"//"+location.host))return{referrer:e,referring_domain:se(e)};oe.log("referrer is the same so skipping")}}var ce=D("utm"),ue="utm_source",le="utm_medium",fe="utm_campaign",he="utm_term",de="utm_content";function pe(e,t){return e=C.getUrlParams(),function(e,t){var r=e?"?"+e.split(".").slice(-1)[0].replace(/\|/g,"&"):"";ce.log("cookie"),ce.log(r);var n=function(e,t,r,n){return C.getQueryParamByName(e,t)||C.getQueryParamByName(r,n)},i=n(ue,t,"utmcsr",r),o=n(le,t,"utmcmd",r),s=n(fe,t,"utmccn",r),a=n(he,t,"utmctr",r),c=n(de,t,"utmcct",r),u={},l=function(e,t){C.isEmptyString(t)||(u[e]=t)};return l(ue,i),l(le,o),l(fe,s),l(he,a),l(de,c),u}(C.cookie.get("__utmz"),e)}var ge="moesif_stored_user_id",me="moesif_stored_company_id",ve="moesif_stored_session_id",ye="moesif_anonymous_id",be="moesif_campaign_data",_e="moesif_campaign_company";function we(e,t){return t&&0===e.indexOf("moesif_")?e.replace("moesif_",t):e}function Se(e){return"null"===e||"undefined"===e||""===e?null:e}function Ie(e,t){var r=t&&t.persistence,n=we(e,t&&t.persistence_key_prefix);if(C.localStorage.is_supported()){var i=Se(C.localStorage.get(n)),o=Se(C.cookie.get(n));return!i&&o&&"localStorage"===r&&C.localStorage.set(n,o),i||o}return Se(C.cookie.get(n))}function ke(e){var t=e&&e.persistence_key_prefix;C.cookie.remove(we(ge,t)),C.cookie.remove(we(me,t)),C.cookie.remove(we(ye,t)),C.cookie.remove(we(ve,t)),C.cookie.remove(we(be,t)),C.cookie.remove(we(_e,t))}function Ee(e){var t=e&&e.persistence_key_prefix;C.localStorage.remove(we(ge,t)),C.localStorage.remove(we(me,t)),C.localStorage.remove(we(ye,t)),C.localStorage.remove(we(ve,t)),C.localStorage.remove(we(be,t)),C.localStorage.remove(we(_e,t))}var Oe=D("campaign");function xe(e){try{var t={};if(e.disableUtm||(t=pe()||{}),!e.disableReferer){var r=ae();r&&(t.referrer=r.referrer,t.referring_domain=r.referring_domain)}if(!e.disableRGclid){var n=function(e){var t=C.getQueryParamByName("gclid",e);if(!C.isEmptyString(t))return t}(C.getUrlParams());n&&(t.gclid=n)}return t}catch(e){Oe.log(e)}}function qe(e){return!(!e||C.isEmptyObject(e))}function Be(e,t){try{var r=Ie(e,t);if(r&&"null"!==r){var n=C.JSONDecode(r);return qe(n)?n:null}}catch(e){return Oe.error("failed to persist campaign data"),Oe.error(e),null}}function Ae(e,t,r,n){!Be(r,t)&&e&&function(e,t,r){try{qe(r)&&e(t,C.JSONEncode(r))}catch(e){Oe.error("failed to decode campaign data"),Oe.error(e)}}(e,r,n)}function Ce(e,t,r){var n=Be(r,t);if(n)try{e(r,"")}catch(e){Oe.error("failed to clear campaign data")}return n}var Re=D("lock"),Te=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||window.localStorage,this.pollIntervalMS=t.pollIntervalMS||100,this.timeoutMS=t.timeoutMS||2e3};Te.prototype.withLock=function(e,t,r){r||"function"==typeof t||(r=t,t=null);var n=r||(new Date).getTime()+"|"+Math.random(),i=(new Date).getTime(),o=this.storageKey,s=this.pollIntervalMS,a=this.timeoutMS,c=this.storage,u=o+":X",l=o+":Y",f=o+":Z",h=function(e){t&&t(e)},d=function(e){if((new Date).getTime()-i>a)return Re.error("Timeout waiting for mutex on "+o+"; clearing lock. ["+n+"]"),c.removeItem(f),c.removeItem(l),void m();setTimeout((function(){try{e()}catch(e){h(e)}}),s*(Math.random()+.1))},p=function(e,t){e()?t():d((function(){p(e,t)}))},g=function(){var e=c.getItem(l);if(e&&e!==n)return!1;if(c.setItem(l,n),c.getItem(l)===n)return!0;if(!F(c,!0))throw new Error("localStorage support dropped while acquiring lock");return!1},m=function(){c.setItem(u,n),p(g,(function(){c.getItem(u)!==n?d((function(){c.getItem(l)===n?p((function(){return!c.getItem(f)}),v):m()})):v()}))},v=function(){c.setItem(f,"1");try{e()}finally{c.removeItem(f),c.getItem(l)===n&&c.removeItem(l),c.getItem(u)===n&&c.removeItem(u)}};try{if(!F(c,!0))throw new Error("localStorage support check failed");m()}catch(e){h(e)}};var De=D("batch"),Me=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||window.localStorage,this.lock=new Te(e,{storage:this.storage}),this.storageExpiration=t.storageExpiration||216e5,this.pid=t.pid||null,this.memQueue=[]};Me.prototype.enqueue=function(e,t,r){var n={id:U(),flushAfter:(new Date).getTime()+2*t,payload:e};this.lock.withLock(C.bind((function(){var t;try{var i=this.readFromStorage();i.push(n),(t=this.saveToStorage(i))&&(De.log("succeeded saving to storage"),this.memQueue.push(n))}catch(r){De.error("Error enqueueing item",e),t=!1}r&&r(t)}),this),(function(e){De.error("Error acquiring storage lock",e),r&&r(!1)}),this.pid)},Me.prototype.fillBatch=function(e){this.memQueue=Fe(this.memQueue,{},this.storageExpiration);var t=this.memQueue.slice(0,e);if(t.lengtho.flushAfter&&o.flushAfter>=a&&!n[o.id]){if(t.push(o),t.length>=e)break}else De.log("fill batch filtered item because invalid or expired"+H(o))}}}return t};var Fe=function(e,t,r){var n=[],i=(new Date).getTime()-r;return De.log("expiration time is "+i),C.each(e,(function(e){e.id&&!t[e.id]?e.flushAfter&&e.flushAfter>=i&&n.push(e):De.log("filtered out item because invalid or expired"+H(e))})),n};Me.prototype.removeItemsByID=function(e,t){var r={};C.each(e,(function(e){r[e]=!0})),this.memQueue=Fe(this.memQueue,r,this.storageExpiration);var n=C.bind((function(){var t;try{var n=this.readFromStorage();n=Fe(n,r,this.storageExpiration),t=this.saveToStorage(n)}catch(r){De.error("Error removing items",e),t=!1}return t}),this);this.lock.withLock(C.bind((function(){var e=n();t&&(De.log("triggering callback of removalItems"),t(e))}),this),C.bind((function(e){var r=!1;if(De.error("Error acquiring storage lock",e),!F(this.storage,!0)&&!(r=n())){De.error("still can not remove from storage, thus stop using storage");try{this.storage.removeItem(this.storageKey)}catch(e){De.error("error clearing queue",e)}}t&&t(r)}),this),this.pid)},Me.prototype.readFromStorage=function(){var e;try{De.log("trying to get storage with storage key "+this.storageKey),(e=this.storage.getItem(this.storageKey))?(e=W(e),C.isArray(e)||(De.error("Invalid storage entry:",e),e=null)):De.log("storageEntry is empty")}catch(t){De.error("Error retrieving queue",t),e=null}return e||[]},Me.prototype.saveToStorage=function(e){try{return this.storage.setItem(this.storageKey,H(e)),!0}catch(e){return De.error("Error saving queue",e),!1}},Me.prototype.clear=function(){this.memQueue=[];try{this.storage.removeItem(this.storageKey)}catch(e){De.error("Failed to clear storage",e)}};var Pe=D("batch"),Ue=function(e,t,r){var n=r.libConfig.batch_storage_expiration;this.queue=new Me(e,{storage:r.storage,storageExpiration:n}),this.endpoint=t,this.libConfig=r.libConfig,this.sendRequest=r.sendRequestFunc,this.batchSize=this.libConfig.batch_size,this.flushInterval=this.libConfig.batch_flush_interval_ms,this.stopAllBatching=r.stopAllBatching,this.stopped=!1,this.removalFailures=0};function je(e){var t=C.UUID();return e&&e(ye,t),t}Ue.prototype.enqueue=function(e,t){this.queue.enqueue(e,this.flushInterval,t)},Ue.prototype.start=function(){this.stopped=!1,this.removalFailures=0,this.flush()},Ue.prototype.stop=function(){this.stopped=!0,this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null)},Ue.prototype.clear=function(){this.queue.clear()},Ue.prototype.resetBatchSize=function(){this.batchSize=this.libConfig.batch_size},Ue.prototype.resetFlush=function(){this.scheduleFlush(this.libConfig.batch_flush_interval_ms)},Ue.prototype.scheduleFlush=function(e){this.flushInterval=e,this.stopped||(this.timeoutID=setTimeout(C.bind(this.flush,this),this.flushInterval))},Ue.prototype.flush=function(e){try{if(this.requestInProgress)return void Pe.log("Flush: Request already in progress");e=e||{};var t=this.batchSize,r=this.queue.fillBatch(t);if(Pe.log("current batch size is "+r.length),r.length<1)return void this.resetFlush();this.requestInProgress=!0;var n=this.libConfig.batch_request_timeout_ms,i=(new Date).getTime(),o=C.map(r,(function(e){return e.payload})),s=C.bind((function(e){this.requestInProgress=!1;try{var o=!1;if(C.isObject(e)&&"timeout"===e.error&&(new Date).getTime()-i>=n)Pe.error("Network timeout; retrying"),this.flush();else if(C.isObject(e)&&e.xhr_req&&(e.xhr_req.status>=500||e.xhr_req.status<=0)){var s=2*this.flushInterval,a=e.xhr_req.responseHeaders;if(a){var c=a["Retry-After"];c&&(s=1e3*parseInt(c,10)||s)}s=Math.min(6e5,s),Pe.error("Error; retry in "+s+" ms"),this.scheduleFlush(s)}else if(C.isObject(e)&&e.xhr_req&&413===e.xhr_req.status)if(r.length>1){var u=Math.max(1,Math.floor(t/2));this.batchSize=Math.min(this.batchSize,u,r.length-1),Pe.error("413 response; reducing batch size to "+this.batchSize),this.resetFlush()}else Pe.error("Single-event request too large; dropping",r),this.resetBatchSize(),o=!0;else o=!0;o&&this.queue.removeItemsByID(C.map(r,(function(e){return e.id})),C.bind((function(e){e?(this.removalFailures=0,this.flush()):(this.removalFailures=this.removalFailures+1,Pe.error("failed to remove items from batched queue "+this.removalFailures+" times."),this.removalFailures>5?(Pe.error("stop batching because too m any errors remove from storage"),this.stopAllBatching()):this.resetFlush())}),this))}catch(e){Pe.error("Error handling API response",e),this.resetFlush()}}),this),a={method:"POST",verbose:!0,ignore_json_errors:!0,timeout_ms:n};e.sendBeacon&&(a.transport="sendBeacon"),Pe.log("Moesif Request:",this.endpoint,o),this.sendRequest(this.endpoint,o,a,s)}catch(e){Pe.error("Error flushing request queue",e),this.resetFlush()}};var Ne="api.moesif.net",ze="/v1/events",Le="/v1/events/batch",He="/v1/actions",We="/v1/actions/batch",Je="/v1/users",$e="/v1/companies",Qe=window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,Ke=(!Qe&&-1===k.indexOf("MSIE")&&k.indexOf("Mozilla"),function(){}),Ve=null;navigator.sendBeacon&&(Ve=function(){return navigator.sendBeacon.apply(navigator,arguments)});var Xe,Ge="http:"===(document&&document.location.protocol)?"http://":"https://";function Ye(e){try{return e.request.headers["X-Moesif-SDK"]}catch(e){return!1}}function Ze(){return R.log("moesif object creator is called"),{init:function(e){window||R.critical("Warning, this library need to be initiated on the client side"),function(e){if(!e)throw new Error("options are required by moesif-browser-js middleware");if(!e.applicationId)throw new Error("A moesif application id is required. Please obtain it through your settings at www.moesif.com");if(e.getTags&&!C.isFunction(e.getTags))throw new Error("getTags should be a function");if(e.getMetadata&&!C.isFunction(e.getMetadata))throw new Error("getMetadata should be a function");if(e.getApiVersion&&!C.isFunction(e.getApiVersion))throw new Error("identifyUser should be a function");if(e.maskContent&&!C.isFunction(e.maskContent))throw new Error("maskContent should be a function");if(e.skip&&!C.isFunction(e.skip))throw new Error("skip should be a function")}(e);var r,n={};n.getTags=e.getTags||Ke,n.maskContent=e.maskContent||function(e){return e},n.getMetadata=e.getMetadata||Ke,n.skip=e.skip||function(){return!1},n.debug=e.debug,n.callback=e.callback||Ke,n.applicationId=e.applicationId,n.apiVersion=e.apiVersion,n.disableFetch=e.disableFetch,n.disableReferrer=e.disableReferrer,n.disableGclid=e.disableGclid,n.disableUtm=e.disableUtm,n.eagerBodyLogging=e.eagerBodyLogging,n.host=e.host||Ne,n.batchEnabled=e.batchEnabled||!1,n.batch_size=e.batchSize||25,n.batch_flush_interval_ms=e.batchMaxTime||2500,n.batch_request_timeout_ms=e.batchTimeout||9e4,n.batch_storage_expiration=e.batchStorageExpiration,n.persistence=e.persistence||"localStorage",n.cross_site_cookie=e.crossSiteCookie||!1,n.cross_subdomain_cookie=!1!==e.crossSubdomainCookie,n.cookie_expiration=e.cookieExpiration||365,n.secure_cookie=e.secureCookie||!1,n.cookie_domain=e.cookieDomain||"",n.persistence_key_prefix=e.persistenceKeyPrefix,this.requestBatchers={},this._options=n,this._persist=function(e){var r=e.persistence;"cookie"!==r&&"localStorage"!==r&&(R.critical("Unknown persistence type "+r+"; falling back to cookie"),r=t.persistence="localStorage");var n=e.persistence_key_prefix,i=function(t,r){var i=we(t,n);C.localStorage.set(i,r),C.cookie.set(i,r,e.cookie_expiration,e.cross_subdomain_cookie,e.secure_cookie,e.cross_site_cookie,e.cookie_domain)};return"cookie"!==r&&C.localStorage.is_supported()||(i=function(t,r){var i=we(t,n);C.cookie.set(i,r,e.cookie_expiration,e.cross_subdomain_cookie,e.secure_cookie,e.cross_site_cookie,e.cookie_domain)}),"none"===r&&(i=function(){}),i}(n);try{if(this._userId=Ie(ge,n),this._session=Ie(ve,n),this._companyId=Ie(me,n),this._anonymousId=(r=this._persist,Ie(ye,n)||je(r)),this._currentCampaign=xe(n),this._currentCampaign&&function(e,t,r){Ae(e,t,be,r),Ae(e,t,_e,r)}(this._persist,n,this._currentCampaign),this._currentCampaign&&!this._userId){var i={};i.anonymous_id=this._anonymousId,i.campaign=this._currentCampaign,this.updateUser(i,this._options.applicationId,this._options.host,this._options.callback)}}catch(e){R.error("error loading saved data from local storage but continue")}if(n.batchEnabled)if(F()&&Qe){if(this.initBatching(),Ve&&window.addEventListener){var o=C.bind((function(){C.each(this.requestBatchers,(function(e){e.stopped||e.flush({sendBeacon:!0})}))}),this);window.addEventListener("pagehide",(function(e){o()})),window.addEventListener("visibilitychange",(function(){"hidden"===document.visibilityState&&o()}))}}else n.batchEnabled=!1,R.log("Turning off batch processing because it needs XHR and localStorage");return R.log("moesif initiated"),this},_executeRequest:function(e,r,n,i){var o=n&&n.applicationId||this._options.applicationId,s=n&&n.method||"POST";try{var a=new XMLHttpRequest;if(a.open(s,e),a.setRequestHeader("Content-Type","application/json"),a.setRequestHeader("X-Moesif-Application-Id",o),a.setRequestHeader("X-Moesif-SDK","moesif-browser-js/"+t.LIB_VERSION),n.timeout_ms&&void 0!==a.timeout){a.timeout=n.timeout_ms;var c=(new Date).getTime()}a.onreadystatechange=function(){var e;if(4===a.readyState)if(a.status>=200&&a.status<=300){if(i){var t=XMLHttpRequest.responseText;i(t)}}else e=a.timeout&&!a.status&&(new Date).getTime()-c>=a.timeout?"timeout":"Bad HTTP status: "+a.status+" "+a.statusText,R.error(e),i&&i({status:0,error:e,xhr_req:a})},a.send(H(r))}catch(e){R.error("failed to send to moesif "+(r&&r.request&&r.request.uri)),R.error(e),i&&i({status:0,error:e})}},initBatching:function(){var e=this._options.applicationId,t=this._options.host;if(R.log("does requestBatch.events exists? "+this.requestBatchers.events),!this.requestBatchers.events){var r={libConfig:this._options,sendRequestFunc:C.bind((function(e,t,r,n){this._executeRequest(e,t,r,n)}),this),stopAllBatching:C.bind((function(){this.stopAllBatching()}),this)},n=j(e),i=new Ue("__mf_"+n+"_ev",Ge+t+Le,r),o=new Ue("__mf_"+n+"_ac",Ge+t+We,r);this.requestBatchers={events:i,actions:o}}C.each(this.requestBatchers,(function(e){e.start()}))},stopAllBatching:function(){this._options.batchEnabled=!1,C.each(this.requestBatchers,(function(e){e.stop(),e.clear()}))},_sendOrBatch:function(e,t,r,n,i){var o=this,s=function(){var n={applicationId:t};return o._executeRequest(r,e,n,i)};if(!this._options.batchEnabled||!n)return s();R.log("current batcher storage key is "+n.queue.storageKey);var a=C.bind((function(e){e||(R.log("enqueue failed, send immediately"),s())}),this);return n.enqueue(e,a),!0},start:function(e){var t=this;if(this._stopRecording||this._stopWeb3Recording)return R.log("recording has already started, please call stop first."),!1;function r(e){t.recordEvent(e)}return R.log("moesif starting"),this._stopRecording=function(e,t){var r=XMLHttpRequest.prototype,n=t&&t.eagerBodyLogging,i=r.open,o=r.send,s=r.setRequestHeader;return r.open=function(e,t){return K.log("XHR open triggered"),this._method=e,this._url=t,this._requestHeaders={},this._startTime=(new Date).toISOString(),i.apply(this,arguments)},r.setRequestHeader=function(e,t){return this._requestHeaders[e]=t,s.apply(this,arguments)},r.send=function(t){K.log("XHR send started for "+this._url);var r=this;if(n||!this.addEventListener){var i=this.onreadystatechange;this.onreadystatechange=function(){var n=r.readyState;if(K.log("readyState "+n),n===XMLHttpRequest.DONE&&(K.log("XHR onreadystatechange DONE triggered for "+r._url),X(r,t,e)),i&&C.isFunction(i))return K.log("trigger old onreadystatechange"),i.apply(this,arguments)}}else this.addEventListener("loadend",(function(){K.log("XHR loadend triggered for "+r._url),X(r,t,e)}));return o.apply(this,arguments)},function(){r.open=i,r.send=o,r.setRequestHeader=s}}(r,this._options),this._options.disableFetch||(R.log("also instrumenting fetch API"),this._stopFetchRecording=function(e,t){var r,n=t||window||self;if(n.fetch){if(re.log("found fetch method."),n.fetch.polyfill)return re.log("skip patching fetch since it is polyfilled"),null;var i=n.fetch;return re.log("fetch is not polyfilled so instrumenting it"),n.fetch=(r=n.fetch,function(t,n){return ie(e,r,t,n)}),function(){n.fetch=i}}re.log("there is no fetch found, so skipping instrumentation.")}(r)),this.useWeb3(e),!0},useWeb3:function(e){var t=this;function r(e){t.recordEvent(e)}try{if(this._stopWeb3Recording&&(this._stopWeb3Recording(),this._stopWeb3Recording=null),e?this._stopWeb3Recording=te(e,r,this._options):window.web3&&(R.log("found global web3, will capture from it"),this._stopWeb3Recording=te(window.web3,r,this._options)),this._stopWeb3Recording)return!0}catch(e){R.log("error patching web3, moving forward anyways"),this._options.callback&&this._options.callback({status:0,error:e,message:"failed to instrument web3, but moving forward with other instrumentation"})}return!1},updateUser:function(e,t,r,n){this._executeRequest(Ge+r+Je,e,{applicationId:t},n)},identifyUser:function(e,t){if(C.isNil(e))R.critical("identifyUser called with nil userId");else{if(this._userId=e,!this._options||!this._options.applicationId)throw new Error("Init needs to be called with a valid application Id before calling identify User.");var r={user_id:e};t&&(r.metadata=t),this._session&&(r.session_token=this._session);var n,i,o=(n=this._persist,i=this._options,Ce(n,i,be)||this._currentCampaign);o&&(r.campaign=o),this._companyId&&(r.company_id=this._companyId),r.anonymous_id=this._anonymousId,this.updateUser(r,this._options.applicationId,this._options.host,this._options.callback);try{e&&this._persist(ge,e)}catch(e){R.error("error saving to local storage")}}},updateCompany:function(e,t,r,n){this._executeRequest(Ge+r+$e,e,{applicationId:t},n)},identifyCompany:function(e,t,r){if(C.isNil(e))R.critical("identifyCompany called with nil companyId.");else{if(this._companyId=e,!this._options||!this._options.applicationId)throw new Error("Init needs to be called with a valid application Id before calling identify User.");var n={company_id:e};r&&(n.company_domain=r),t&&(n.metadata=t),this._session&&(n.session_token=this._session);var i,o,s=(i=this._persist,o=this._options,Ce(i,o,_e)||this._currentCampaign);s&&(n.campaign=s),this.updateCompany(n,this._options.applicationId,this._options.host,this._options.callback);try{e&&this._persist(me,e)}catch(e){R.error("error saving to local storage")}}},identifySession:function(e){if(C.isNil(e))R.critical("identifySession called with nil");else if(this._session=e,e)try{this._persist(ve,e)}catch(e){R.error("local storage error")}},track:function(e,t){if(!e)throw new Error("track name must have action Name defined");var r={action_name:e};this._companyId&&(r.company_id=this._companyId),this._userId?r.user_id=this._userId:r.anonymous_id=this._anonymousId,this._session&&(r.session_token=this._session),r.request={uri:document.location.href,verb:"GET",user_agent_string:navigator.userAgent},r.transaction_id=C.uuid4(),t&&(r.metadata=t);var n=Ge+this._options.host+He;return R.log("sending or queuing: "+e),this._sendOrBatch(r,this._options.applicationId,n,this.requestBatchers.actions,this._options.callback)},recordEvent:function(e){if(Ye(e))R.log("skipped logging for requests to moesif");else{R.log("determining if should log: "+e.request.uri);var t=Object.assign({},e);if(this._getUserId()?t.user_id=this._getUserId():t.anonymous_id=this._anonymousId,this._getCompanyId()&&(t.company_id=this._getCompanyId()),this._getSession()&&(t.session_token=this._getSession()),t.tags=this._options.getTags(e)||"",this._options.apiVersion&&(t.request.api_version=this._options.apiVersion),t.request.headers["User-Agent"]||(t.request.headers["User-Agent"]=window.navigator.userAgent),t.transaction_id=C.uuid4(),this._options.maskContent&&(t=this._options.maskContent(t)),this._options.getMetadata)if(t.metadata){var r=this._options.getMetadata(t);t.metadata=Object.assign(t.metadata,r)}else t.metadata=this._options.getMetadata(t);if(this._options.skip(e)||Ye(e))R.log("skipped logging for "+e.request.uri);else{R.log("sending or queuing: "+e.request.uri);var n=Ge+this._options.host+ze;this._sendOrBatch(t,this._options.applicationId,n,this.requestBatchers.events,this._options.callback)}}},_getUserId:function(){return this._userId},_getCompanyId:function(){return this._companyId},_getSession:function(){return this._session},stop:function(){this._stopRecording&&(this._stopRecording(),this._stopRecording=null),this._stopWeb3Recording&&(this._stopWeb3Recording(),this._stopWeb3Recording=null),this._stopFetchRecording&&(this._stopFetchRecording(),this._stopFetchRecording=null)},clearCookies:function(){ke(this._options)},clearStorage:function(){Ee(this._options)},resetAnonymousId:function(){return this._anonymousId=je(this._persist),this._anonymousId},reset:function(){ke(this._options),Ee(this._options),this._anonymousId=je(this._persist),this._companyId=null,this._userId=null,this._session=null,this._currentCampaign=null}}}return(Xe=Ze()).new=Ze,Xe}()},function(e,t,r){!function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={exports:{},id:n,loaded:!1};return e[n].call(i.exports,i,i.exports,r),i.loaded=!0,i.exports}r.m=e,r.c=t,r.p="",r(0)}([function(e,t,r){var n=r(1);n.init({applicationId:"Your Application ID",debug:!0}),n.start()},function(e,t,r){e.exports=function(){"use strict";var e,t=!1,r="1.5.9";e="undefined"==typeof window?{navigator:{}}:window;var n,i,o,s,a,c,u,l,f,h,d,p=Array.prototype,g=Function.prototype,m=Object.prototype,v=p.slice,y=m.toString,b=m.hasOwnProperty,_=e.console,w=e.navigator,S=e.document,I=w.userAgent,k=g.bind,E=p.forEach,O=p.indexOf,x=p.map,q=Array.isArray,B={},A={trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},C={log:function(){if(t&&!A.isUndefined(_)&&_)try{_.log.apply(_,arguments)}catch(e){A.each(arguments,(function(e){_.log(e)}))}},error:function(){if(t&&!A.isUndefined(_)&&_){var e=["Moesif error:"].concat(A.toArray(arguments));try{_.error.apply(_,e)}catch(t){A.each(e,(function(e){_.error(e)}))}}},critical:function(){if(!A.isUndefined(_)&&_){var e=["Moesif error:"].concat(A.toArray(arguments));try{_.error.apply(_,e)}catch(t){A.each(e,(function(e){_.error(e)}))}}}};A.bind=function(e,t){var r,n;if(k&&e.bind===k)return k.apply(e,v.call(arguments,1));if(!A.isFunction(e))throw new TypeError;return r=v.call(arguments,2),n=function(){if(!(this instanceof n))return e.apply(t,r.concat(v.call(arguments)));var i={};i.prototype=e.prototype;var o=new i;i.prototype=null;var s=e.apply(o,r.concat(v.call(arguments)));return Object(s)===s?s:o}},A.bind_instance_methods=function(e){for(var t in e)"function"==typeof e[t]&&(e[t]=A.bind(e[t],e))},A.isEmptyString=function(e){return!e||0===e.length},A.each=function(e,t,r){if(null!=e)if(E&&e.forEach===E)e.forEach(t,r);else if(e.length===+e.length){for(var n=0,i=e.length;n/g,">").replace(/"/g,""").replace(/'/g,"'")),t},A.extend=function(e){return A.each(v.call(arguments,1),(function(t){for(var r in t)void 0!==t[r]&&(e[r]=t[r])})),e},A.isArray=q||function(e){return"[object Array]"===y.call(e)},A.isFunction=function(e){try{return/^\s*\bfunction\b/.test(e)}catch(e){return!1}},A.isArguments=function(e){return!(!e||!b.call(e,"callee"))},A.toArray=function(e){return e?e.toArray?e.toArray():A.isArray(e)||A.isArguments(e)?v.call(e):A.values(e):[]},A.map=function(e,t){if(x&&e.map===x)return e.map(t);var r=[];return A.each(e,(function(e){r.push(t(e))})),r},A.values=function(e){var t=[];return null===e||A.each(e,(function(e){t[t.length]=e})),t},A.identity=function(e){return e},A.include=function(e,t){var r=!1;return null===e?r:O&&e.indexOf===O?-1!=e.indexOf(t):(A.each(e,(function(e){if(r||(r=e===t))return B})),r)},A.includes=function(e,t){return-1!==e.indexOf(t)},A.inherit=function(e,t){return e.prototype=new t,e.prototype.constructor=e,e.superclass=t.prototype,e},A.isObject=function(e){return e===Object(e)&&!A.isArray(e)},A.isEmptyObject=function(e){if(A.isObject(e)){for(var t in e)if(b.call(e,t))return!1;return!0}return!1},A.isUndefined=function(e){return void 0===e},A.isString=function(e){return"[object String]"==y.call(e)},A.isDate=function(e){return"[object Date]"==y.call(e)},A.isNumber=function(e){return"[object Number]"==y.call(e)},A.isElement=function(e){return!(!e||1!==e.nodeType)},A.encodeDates=function(e){return A.each(e,(function(t,r){A.isDate(t)?e[r]=A.formatDate(t):A.isObject(t)&&(e[r]=A.encodeDates(t))})),e},A.timestamp=function(){return Date.now=Date.now||function(){return+new Date},Date.now()},A.formatDate=function(e){function t(e){return e<10?"0"+e:e}return e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())},A.safewrap=function(e){return function(){try{return e.apply(this,arguments)}catch(e){C.critical("Implementation error. Please contact support@moesif.com.")}}},A.safewrap_class=function(e,t){for(var r=0;r0&&(t[r]=e)})),t},A.truncate=function(e,t){var r;return"string"==typeof e?r=e.slice(0,t):A.isArray(e)?(r=[],A.each(e,(function(e){r.push(A.truncate(e,t))}))):A.isObject(e)?(r={},A.each(e,(function(e,n){r[n]=A.truncate(e,t)}))):r=e,r},A.JSONEncode=function(e){var t=function(e){var t=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};return t.lastIndex=0,t.test(e)?'"'+e.replace(t,(function(e){var t=r[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)}))+'"':'"'+e+'"'},r=function(e,n){var i="",o=0,s="",a="",c=0,u=i,l=[],f=n[e];switch(f&&"object"==typeof f&&"function"==typeof f.toJSON&&(f=f.toJSON(e)),typeof f){case"string":return t(f);case"number":return isFinite(f)?String(f):"null";case"boolean":case"null":return String(f);case"object":if(!f)return"null";if(i+=" ",l=[],"[object Array]"===y.apply(f)){for(c=f.length,o=0;o="0"&&o<="9";)t+=o,l();if("."===o)for(t+=".";l()&&o>="0"&&o<="9";)t+=o;if("e"===o||"E"===o)for(t+=o,l(),"-"!==o&&"+"!==o||(t+=o,l());o>="0"&&o<="9";)t+=o,l();if(e=+t,isFinite(e))return e;u("Bad number")},h=function(){var e,t,r,n="";if('"'===o)for(;l();){if('"'===o)return l(),n;if("\\"===o)if(l(),"u"===o){for(r=0,t=0;t<4&&(e=parseInt(l(),16),isFinite(e));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else{if("string"!=typeof c[o])break;n+=c[o]}else n+=o}u("Bad string")},d=function(){for(;o&&o<=" ";)l()},a=function(){switch(d(),o){case"{":return function(){var e,t={};if("{"===o){if(l("{"),d(),"}"===o)return l("}"),t;for(;o;){if(e=h(),d(),l(":"),Object.hasOwnProperty.call(t,e)&&u('Duplicate key "'+e+'"'),t[e]=a(),d(),"}"===o)return l("}"),t;l(","),d()}}u("Bad object")}();case"[":return function(){var e=[];if("["===o){if(l("["),d(),"]"===o)return l("]"),e;for(;o;){if(e.push(a()),d(),"]"===o)return l("]"),e;l(","),d()}}u("Bad array")}();case'"':return h();case"-":return f();default:return o>="0"&&o<="9"?f():function(){switch(o){case"t":return l("t"),l("r"),l("u"),l("e"),!0;case"f":return l("f"),l("a"),l("l"),l("s"),l("e"),!1;case"n":return l("n"),l("u"),l("l"),l("l"),null}u('Unexpected "'+o+'"')}()}},function(e){var t;return s=e,i=0,o=" ",t=a(),d(),o&&u("Syntax error"),t}),A.base64Encode=function(e){var t,r,n,i,o,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,c=0,u="",l=[];if(!e)return e;e=A.utf8Encode(e);do{t=(o=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,r=o>>12&63,n=o>>6&63,i=63&o,l[c++]=s.charAt(t)+s.charAt(r)+s.charAt(n)+s.charAt(i)}while(a127&&s<2048?String.fromCharCode(s>>6|192,63&s|128):String.fromCharCode(s>>12|224,s>>6&63|128,63&s|128),null!==a&&(r>t&&(o+=e.substring(t,r)),o+=a,t=r=i+1)}return r>t&&(o+=e.substring(t,e.length)),o},A.UUID=(n=function(){for(var e=1*new Date,t=0;e==1*new Date;)t++;return e.toString(16)+t.toString(16)},function(){var e=(screen.height*screen.width).toString(16);return n()+"-"+Math.random().toString(16).replace(".","")+"-"+function(){var e,t,r=I,n=[],i=0;function o(e,t){var r,i=0;for(r=0;r=4&&(i=o(i,n),n=[]);return n.length>0&&(i=o(i,n)),i.toString(16)}()+"-"+e+"-"+n()}),A.isBlockedUA=function(e){return!!/(google web preview|baiduspider|yandexbot|bingbot|googlebot|yahoo! slurp)/i.test(e)},A.HTTPBuildQuery=function(e,t){var r,n,i=[];return A.isUndefined(t)&&(t="&"),A.each(e,(function(e,t){r=encodeURIComponent(e.toString()),n=encodeURIComponent(t),i[i.length]=n+"="+r})),i.join(t)},A.getQueryParamByName=function(e,t){e=e.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var r=new RegExp("[\\?&]"+e+"=([^]*)").exec(t);return null===r?void 0:decodeURIComponent(r[1].replace(/\+/g," "))},A.getQueryParam=function(e,t){t=t.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var r=new RegExp("[\\?&]"+t+"=([^]*)").exec(e);return null===r||r&&"string"!=typeof r[1]&&r[1].length?"":decodeURIComponent(r[1]).replace(/\+/g," ")},A.getHashParam=function(e,t){var r=e.match(new RegExp(t+"=([^&]*)"));return r?r[1]:null},A.cookie={get:function(e){for(var t=e+"=",r=S.cookie.split(";"),n=0;n=0}function n(t){if(!S.getElementsByTagName)return[];var n,i,o,s,a,c,u,l,f,h,d=t.split(" "),p=[S];for(c=0;c-1){o=(i=n.split("#"))[0];var g=i[1],m=S.getElementById(g);if(!m||o&&m.nodeName.toLowerCase()!=o)return[];p=[m]}else if(n.indexOf(".")>-1){o=(i=n.split("."))[0];var v=i[1];for(o||(o="*"),s=[],a=0,u=0;u-1};break;default:b=function(e){return e.getAttribute(_)}}for(p=[],h=0,u=0;u=3?t[2]:""},properties:function(){return A.extend(A.strip_empty_properties({$os:A.info.os(),$browser:A.info.browser(I,w.vendor,window.opera),$referrer:S.referrer,$referring_domain:A.info.referringDomain(S.referrer),$device:A.info.device(I)}),{$current_url:window.location.href,$browser_version:A.info.browserVersion(I,w.vendor,window.opera),$screen_height:screen.height,$screen_width:screen.width,mp_lib:"web",$lib_version:r})},people_properties:function(){return A.extend(A.strip_empty_properties({$os:A.info.os(),$browser:A.info.browser(I,w.vendor,window.opera)}),{$browser_version:A.info.browserVersion(I,w.vendor,window.opera)})},pageviewInfo:function(e){return A.strip_empty_properties({mp_page:e,mp_referrer:S.referrer,mp_browser:A.info.browser(I,w.vendor,window.opera),mp_platform:A.info.os()})}};var D=function(e){var t=Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10);return e?t.substring(0,e):t},M=function(e,t){return function(){return arguments[0]="["+t+"] "+arguments[0],e.apply(C,arguments)}},F=function(e){return{log:M(C.log,e),error:M(C.error,e),critical:M(C.critical,e)}},P=null,U=null;"undefined"!=typeof JSON&&(P=JSON.stringify,U=JSON.parse),P=P||A.JSONEncode,U=U||A.JSONDecode,A.toArray=A.toArray,A.isObject=A.isObject,A.JSONEncode=A.JSONEncode,A.JSONDecode=A.JSONDecode,A.isBlockedUA=A.isBlockedUA,A.isEmptyObject=A.isEmptyObject,A.isEmptyString=A.isEmptyString,A.each=A.each,A.info=A.info,A.info.device=A.info.device,A.info.browser=A.info.browser,A.info.properties=A.info.properties;var j=F("capture"),N="http:"===(document&&document.location.protocol)?"http://":"https://";function z(e){var t={};if(!e)return t;for(var r=e.split("\r\n"),n=0;n0&&(t[i.substring(0,o)]=i.substring(o+2))}return t}function L(e){if(e&&"string"==typeof e){var t=A.trim(e);return 0!==t.indexOf("http")?N+window.location.host+"/"+t.replace(/^\./,"").replace(/^\//,""):e}return e}var H=F("web3capture");function W(e){return e&&e.host?e.host:"/"}function J(e,t,r,n,i,o){var s={uri:W(e),verb:"POST",time:t,headers:{}};if(e.headers){var a={};A.each(e.headers,(function(e){a[e.name]=e.value})),s.headers=a}if(n)if("string"==typeof n){H.log("request post data is string"),H.log(n);try{s.body=A.JSONDecode(n)}catch(e){H.log("JSON decode failed"),H.log(e),s.transfer_encoding="base64",s.body=A.base64Encode(n)}}else("object"==typeof n||Array.isArray(n)||"number"==typeof n||"boolean"==typeof postData)&&(s.body=n);var c={status:200,time:r,headers:{}};i?c.body=i:o&&(c.body={error:o});var u={request:s,response:c,metadata:{_web3:{via_web3_provider:!0,path:e.path,host:e.host}}};return e.isMetaMask&&(u.metadata._web3.is_metamask=!0),u}function $(e,t,r){if(e.currentProvider){H.log("found my currentProvider, patching it");var n=e.currentProvider,i=n.send,o=n.sendAsync;return n.send=function(e){H.log("patched send is called"),H.log(e);var r=(new Date).toISOString(),o=i.apply(n,arguments);H.log("patch send result is back"),H.log(o);var s=(new Date).toISOString();return t&&t(J(n,r,s,e,o)),o},n.sendAsync=function(e,r){H.log("patched sendAsync is called"),H.log(e);var i=(new Date).toISOString(),s=n;o.apply(n,[e,function(n,o){var a=(new Date).toISOString();H.log("inside patched callback"),H.log(o),t&&t(J(s,i,a,e,o,n)),r&&r(n,o)}])},function(){n.send=i,n.sendAsync=o}}return null}var Q=F("captureFetch");function K(e){if(!e)return{};if(Q.log("about to decode buffer"),Q.log(e),Q.log(e.byteLength),e.byteLength<=0)return{};try{var t=new TextDecoder("utf-8").decode(e);try{return{body:A.JSONDecode(t)}}catch(e){return Q.error(e),{transfer_encoding:"base64",body:A.base64Encode(t)}}}catch(t){return Q.error(t),Q.log(e),{transfer_encoding:"base64",body:"can not be decoded"}}}function V(e){var t={};Q.log("parseheaders is called");for(var r=e.entries(),n=r.next();!n.done;)Q.log(n.value),t[n.value[0]]=n.value[1],n=r.next();return t}function X(e,t,r,n){var i=null;try{i=new Request(r,n)}catch(e){}var o=(new Date).toISOString(),s=null,a=null;a=t(r,n);var c=null;return a=a.then((function(t){return c=t.clone(),s=(new Date).toISOString(),function(e,t,r,n,i){try{setTimeout((function(){if(Q.log("interception is here."),Q.log(e),Q.log(t),e&&t)try{Promise.all([e.arrayBuffer(),t.arrayBuffer()]).then((function(o){var s=o.map(K),a=Object.assign(s[0],{uri:e.url,verb:e.method,time:r,headers:V(e.headers)}),c=Object.assign(s[1],{status:t.status,time:n,headers:V(t.headers)});Q.log(a),Q.log(c),i({request:a,response:c})}))}catch(e){Q.error("error processing body")}else Q.log("savedRequest")}),50)}catch(e){Q.error("error processing saved fetch request and response, but move on anyways."),Q.log(e)}}(i,c,o,s,e),t}))}function G(e){if(A.isEmptyString(e))return null;var t=e.split("/");return t.length>=3?t[2]:null}function Y(){var e=document&&document.referrer;if(!A.isEmptyString(e))return{referrer:e,referring_domain:G(e)}}var Z=F("utm"),ee="utm_source",te="utm_medium",re="utm_campaign",ne="utm_term",ie="utm_content";function oe(e,t){return e=location&&location.search,function(e,t){var r=e?"?"+e.split(".").slice(-1)[0].replace(/\|/g,"&"):"";Z.log("cookie"),Z.log(r);var n=function(e,t,r,n){return A.getQueryParamByName(e,t)||A.getQueryParamByName(r,n)},i=n(ee,t,"utmcsr",r),o=n(te,t,"utmcmd",r),s=n(re,t,"utmccn",r),a=n(ne,t,"utmctr",r),c=n(ie,t,"utmcct",r),u={},l=function(e,t){A.isEmptyString(t)||(u[e]=t)};return l(ee,i),l(te,o),l(re,s),l(ne,a),l(ie,c),u}(A.cookie.get("__utmz"),e)}var se=F("campaign");function ae(e){try{var t={};if(e.disableUtm||(t=oe()||{}),!e.disableReferer){var r=Y();r&&(t.referrer=r.referrer,t.referring_domain=r.referring_domain)}if(!e.disableRGclid){var n=function(e){var t=A.getQueryParamByName("gclid",e);if(!A.isEmptyString(t))return t}(location&&location.search);n&&(t.gclid=n)}return t}catch(e){se.log(e)}}var ce=F("lock"),ue=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||window.localStorage,this.pollIntervalMS=t.pollIntervalMS||100,this.timeoutMS=t.timeoutMS||2e3};ue.prototype.withLock=function(e,t,r){r||"function"==typeof t||(r=t,t=null);var n=r||(new Date).getTime()+"|"+Math.random(),i=(new Date).getTime(),o=this.storageKey,s=this.pollIntervalMS,a=this.timeoutMS,c=this.storage,u=o+":X",l=o+":Y",f=o+":Z",h=function(e){t&&t(e)},d=function(e){if((new Date).getTime()-i>a)return ce.error("Timeout waiting for mutex on "+o+"; clearing lock. ["+n+"]"),c.removeItem(f),c.removeItem(l),void m();setTimeout((function(){try{e()}catch(e){h(e)}}),s*(Math.random()+.1))},p=function(e,t){e()?t():d((function(){p(e,t)}))},g=function(){var e=c.getItem(l);if(e&&e!==n)return!1;if(c.setItem(l,n),c.getItem(l)===n)return!0;if(!T(c,!0))throw new Error("localStorage support dropped while acquiring lock");return!1},m=function(){c.setItem(u,n),p(g,(function(){c.getItem(u)!==n?d((function(){c.getItem(l)===n?p((function(){return!c.getItem(f)}),v):m()})):v()}))},v=function(){c.setItem(f,"1");try{e()}finally{c.removeItem(f),c.getItem(l)===n&&c.removeItem(l),c.getItem(u)===n&&c.removeItem(u)}};try{if(!T(c,!0))throw new Error("localStorage support check failed");m()}catch(e){h(e)}};var le=F("batch"),fe=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||window.localStorage,this.lock=new ue(e,{storage:this.storage}),this.pid=t.pid||null,this.memQueue=[]};fe.prototype.enqueue=function(e,t,r){var n={id:D(),flushAfter:(new Date).getTime()+2*t,payload:e};this.lock.withLock(A.bind((function(){var t;try{var i=this.readFromStorage();i.push(n),(t=this.saveToStorage(i))&&(le.log("succeeded saving to storage"),this.memQueue.push(n))}catch(r){le.error("Error enqueueing item",e),t=!1}r&&r(t)}),this),(function(e){le.error("Error acquiring storage lock",e),r&&r(!1)}),this.pid)},fe.prototype.fillBatch=function(e){var t=this.memQueue.slice(0,e);if(t.lengtho.flushAfter&&!n[o.id]&&(t.push(o),t.length>=e))break}}}return t};var he=function(e,t){var r=[];return A.each(e,(function(e){e.id&&!t[e.id]&&r.push(e)})),r};fe.prototype.removeItemsByID=function(e,t){var r={};A.each(e,(function(e){r[e]=!0})),this.memQueue=he(this.memQueue,r),this.lock.withLock(A.bind((function(){var n;try{var i=this.readFromStorage();i=he(i,r),le.log(i.length),n=this.saveToStorage(i)}catch(t){le.error("Error removing items",e),n=!1}t&&(le.log("triggering callback of removalItems"),t(n))}),this),(function(e){le.error("Error acquiring storage lock",e),t&&t(!1)}),this.pid)},fe.prototype.readFromStorage=function(){var e;try{le.log("trying to get storage with storage key "+this.storageKey),(e=this.storage.getItem(this.storageKey))?(e=U(e),A.isArray(e)||(le.error("Invalid storage entry:",e),e=null)):le.log("storageEntry is empty")}catch(t){le.error("Error retrieving queue",t),e=null}return e||[]},fe.prototype.saveToStorage=function(e){try{return this.storage.setItem(this.storageKey,P(e)),!0}catch(e){return le.error("Error saving queue",e),!1}},fe.prototype.clear=function(){this.memQueue=[],this.storage.removeItem(this.storageKey)};var de=F("batch"),pe=function(e,t,r){this.queue=new fe(e,{storage:r.storage}),this.endpoint=t,this.libConfig=r.libConfig,this.sendRequest=r.sendRequestFunc,this.batchSize=this.libConfig.batch_size,this.flushInterval=this.libConfig.batch_flush_interval_ms,this.stopped=!1};pe.prototype.enqueue=function(e,t){this.queue.enqueue(e,this.flushInterval,t)},pe.prototype.start=function(){this.stopped=!1,this.flush()},pe.prototype.stop=function(){this.stopped=!0,this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null)},pe.prototype.clear=function(){this.queue.clear()},pe.prototype.resetBatchSize=function(){this.batchSize=this.libConfig.batch_size},pe.prototype.resetFlush=function(){this.scheduleFlush(this.libConfig.batch_flush_interval_ms)},pe.prototype.scheduleFlush=function(e){this.flushInterval=e,this.stopped||(this.timeoutID=setTimeout(A.bind(this.flush,this),this.flushInterval))},pe.prototype.flush=function(e){try{if(this.requestInProgress)return void de.log("Flush: Request already in progress");e=e||{};var t=this.batchSize,r=this.queue.fillBatch(t);if(de.log("current batch size is "+r.length),r.length<1)return void this.resetFlush();this.requestInProgress=!0;var n=this.libConfig.batch_request_timeout_ms,i=(new Date).getTime(),o=A.map(r,(function(e){return e.payload})),s=A.bind((function(e){this.requestInProgress=!1;try{var o=!1;if(A.isObject(e)&&"timeout"===e.error&&(new Date).getTime()-i>=n)de.error("Network timeout; retrying"),this.flush();else if(A.isObject(e)&&e.xhr_req&&(e.xhr_req.status>=500||e.xhr_req.status<=0)){var s=2*this.flushInterval,a=e.xhr_req.responseHeaders;if(a){var c=a["Retry-After"];c&&(s=1e3*parseInt(c,10)||s)}s=Math.min(6e5,s),de.error("Error; retry in "+s+" ms"),this.scheduleFlush(s)}else if(A.isObject(e)&&e.xhr_req&&413===e.xhr_req.status)if(r.length>1){var u=Math.max(1,Math.floor(t/2));this.batchSize=Math.min(this.batchSize,u,r.length-1),de.error("413 response; reducing batch size to "+this.batchSize),this.resetFlush()}else de.error("Single-event request too large; dropping",r),this.resetBatchSize(),o=!0;else o=!0;o&&this.queue.removeItemsByID(A.map(r,(function(e){return e.id})),A.bind(this.flush,this))}catch(e){de.error("Error handling API response",e),this.resetFlush()}}),this),a={method:"POST",verbose:!0,ignore_json_errors:!0,timeout_ms:n};e.sendBeacon&&(a.transport="sendBeacon"),de.log("Moesif Request:",this.endpoint,o),this.sendRequest(this.endpoint,o,a,s)}catch(e){de.error("Error flushing request queue",e),this.resetFlush()}};var ge="api.moesif.net",me="/v1/events",ve="/v1/events/batch",ye="/v1/actions",be="/v1/actions/batch",_e="/v1/users",we="/v1/companies",Se="moesif_stored_user_id",Ie="moesif_stored_company_id",ke="moesif_stored_session_id",Ee=window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,Oe=(!Ee&&-1===I.indexOf("MSIE")&&I.indexOf("Mozilla"),null);navigator.sendBeacon&&(Oe=function(){return navigator.sendBeacon.apply(navigator,arguments)});var xe="http:"===(document&&document.location.protocol)?"http://":"https://";function qe(e){try{return e.request.headers["X-Moesif-SDK"]}catch(e){return!1}}function Be(){return C.log("moesif object creator is called"),{init:function(e){window||C.critical("Warning, this library need to be initiated on the client side"),function(e){if(!e)throw new Error("options are required by moesif-express middleware");if(!e.applicationId)throw new Error("A moesif application id is required. Please obtain it through your settings at www.moesif.com");if(e.getTags&&!A.isFunction(e.getTags))throw new Error("getTags should be a function");if(e.getMetadata&&!A.isFunction(e.getMetadata))throw new Error("getMetadata should be a function");if(e.getApiVersion&&!A.isFunction(e.getApiVersion))throw new Error("identifyUser should be a function");if(e.maskContent&&!A.isFunction(e.maskContent))throw new Error("maskContent should be a function");if(e.skip&&!A.isFunction(e.skip))throw new Error("skip should be a function")}(e);var t={};t.getTags=e.getTags||function(){},t.maskContent=e.maskContent||function(e){return e},t.getMetadata=e.getMetadata||function(){},t.skip=e.skip||function(){return!1},t.debug=e.debug,t.callback=e.callback,t.applicationId=e.applicationId,t.apiVersion=e.apiVersion,t.disableFetch=e.disableFetch,t.disableReferrer=e.disableReferrer,t.disableGclid=e.disableGclid,t.disableUtm=e.disableUtm,t.batch=e.batch||!1,t.batch_size=e.batchSize||50,t.batch_flush_interval_ms=e.batchIntervalMs||5e3,t.batch_request_timeout_ms=e.batchTimeoutMs||9e4,this.requestBatchers={},this._options=t;try{this._userId=localStorage.getItem(Se),this._session=localStorage.getItem(ke),this._companyId=localStorage.getItem(Ie),this._campaign=ae(t)}catch(e){C.error("error loading saved data from local storage but continue")}return t.batch&&(T&&Ee?(this.initBatching(),Oe&&window.addEventListener&&window.addEventListener("unload",A.bind((function(){this.requestBatchers.events.flush({sendBeacon:!0})}),this))):(t.batch=!1,C.log("Turning off batch processing because it needs XHR and localStorage"))),C.log("moesif initiated"),this},_executeRequest:function(e,t,n,i){var o=n&&n.applicationId||this._options.applicationId,s=n&&n.method||"POST";try{var a=new XMLHttpRequest;if(a.open(s,e),a.setRequestHeader("Content-Type","application/json"),a.setRequestHeader("X-Moesif-Application-Id",o),a.setRequestHeader("X-Moesif-SDK","moesif-browser-js/"+r),n.timeout_ms&&void 0!==a.timeout){a.timeout=n.timeout_ms;var c=(new Date).getTime()}a.onreadystatechange=function(){var e;if(4===a.readyState)if(a.status>=200&&a.status<=300){if(i){var t=XMLHttpRequest.responseText;i(t)}}else e=a.timeout&&!a.status&&(new Date).getTime()-c>=a.timeout?"timeout":"Bad HTTP status: "+a.status+" "+a.statusText,C.error(e),i&&i({status:0,error:e,xhr_req:a})},a.send(P(t))}catch(e){C.error("failed to send event to moesif"+event.request.uri),C.error(e),i&&i({status:0,error:e})}},initBatching:function(){var e=this._options.applicationId;if(C.log("does requestBatch.events exists? "+this.requestBatchers.events),!this.requestBatchers.events){var t={libConfig:this._options,sendRequestFunc:A.bind((function(e,t,r,n){this._executeRequest(e,t,r,n)}),this)},r=new pe("__mf_"+e+"_ev",xe+ge+ve,t),n=new pe("__mf_"+e+"_ac",xe+ge+be,t);this.requestBatchers={events:r,actions:n}}A.each(this.requestBatchers,(function(e){e.start()}))},_sendOrBatch:function(e,t,r,n,i){var o=!0;if(this._options.batch&&n)C.log("current batcher storage key is "+n.queue.storageKey),n.enqueue(e);else{var s={applicationId:t};o=this._executeRequest(r,e,s,i)}return o},start:function(e){var t=this;if(this._stopRecording||this._stopWeb3Recording)return C.log("recording has already started, please call stop first."),!1;function r(e){t.recordEvent(e)}return C.log("moesif starting"),this._stopRecording=function(e){var t=XMLHttpRequest.prototype,r=t.open,n=t.send,i=t.setRequestHeader;return t.open=function(e,t){return this._method=e,this._url=t,this._requestHeaders={},this._startTime=(new Date).toISOString(),r.apply(this,arguments)},t.setRequestHeader=function(e,t){return this._requestHeaders[e]=t,i.apply(this,arguments)},t.send=function(t){return this.addEventListener("load",(function(){var r=(new Date).toISOString();if(e){var n=this._url?this._url.toLowerCase():this._url;if(n&&n.indexOf("moesif.com")<0&&n.indexOf("apirequest.io")<0){var i={uri:L(this._url),verb:this._method,time:this._startTime,headers:this._requestHeaders};if(t)if("string"==typeof t){j.log("request post data is string"),j.log(t);try{i.body=A.JSONDecode(t)}catch(e){j.log("JSON decode failed"),j.log(e),i.transfer_encoding="base64",i.body=A.base64Encode(t)}}else("object"==typeof t||Array.isArray(t)||"number"==typeof t||"boolean"==typeof t)&&(i.body=t);var o=z(this.getAllResponseHeaders()),s={status:this.status,time:r,headers:o};if(this.responseText)try{s.body=A.JSONDecode(this.responseText)}catch(e){s.transfer_encoding="base64",s.body=A.base64Encode(this.responseText)}e({request:i,response:s})}}})),n.apply(this,arguments)},function(){t.open=r,t.send=n,t.setRequestHeader=i}}(r),this._options.disableFetch||(C.log("also instrumenting fetch API"),this._stopFetchRecording=function(e,t){var r,n=t||window||self;if(n.fetch){if(Q.log("found fetch method."),n.fetch.polyfill)return Q.log("skip patching fetch since it is polyfilled"),null;var i=n.fetch;return Q.log("fetch is not polyfilled so instrumenting it"),n.fetch=(r=n.fetch,function(t,n){return X(e,r,t,n)}),function(){n.fetch=i}}Q.log("there is no fetch found, so skipping instrumentation.")}(r)),this.useWeb3(e),!0},useWeb3:function(e){var t=this;function r(e){t.recordEvent(e)}return this._stopWeb3Recording&&(this._stopWeb3Recording(),this._stopWeb3Recording=null),e?this._stopWeb3Recording=$(e,r,this._options):window.web3&&(C.log("found global web3, will capture from it"),this._stopWeb3Recording=$(window.web3,r,this._options)),!!this._stopWeb3Recording},updateUser:function(e,t,r){this._executeRequest(xe+ge+_e,e,{applicationId:t},r)},identifyUser:function(e,t){if(this._userId=e,!this._options||!this._options.applicationId)throw new Error("Init needs to be called with a valid application Id before calling identify User.");var r={user_id:e};t&&(r.metadata=t),this._session&&(r.session_token=this._session),this._campaign&&(r.campaign=this._campaign),this._companyId&&(r.company_id=this._companyId),this.updateUser(r,this._options.applicationId,this._options.callback);try{localStorage.setItem(Se,e)}catch(e){C.error("error saving to local storage")}},updateCompany:function(e,t,r){this._executeRequest(xe+ge+we,e,{applicationId:t},r)},identifyCompany:function(e,t,r){if(this._companyId=e,!this._options||!this._options.applicationId)throw new Error("Init needs to be called with a valid application Id before calling identify User.");var n={company_id:e};r&&(n.company_domain=r),t&&(n.metadata=t),this._session&&(n.session_token=this._session),this._campaign&&(n.campaign=this._campaign),this.updateCompany(n,this._options.applicationId,this._options.callback);try{localStorage.setItem(Ie,e)}catch(e){C.error("error saving to local storage")}},identifySession:function(e){this._session=e,localStorage.setItem(ke,e)},track:function(e,t){if(!e)throw new Error("track name must have action Name defined");var r={action_name:e};this._companyId&&(r.company_id=this._companyId),this._userId&&(r.user_id=this._userId),this._session&&(r.session_token=this._session),r.request={uri:document.location.href,verb:"GET",user_agent_string:navigator.userAgent},t&&(r.metadata=t);var n=xe+ge+ye;return C.log("sending or queuing: "+e),this._sendOrBatch(r,this._options.applicationId,n,this.requestBatchers.actions,this._options.callback)},recordEvent:function(e){if(qe(e))C.log("skipped logging for requests to moesif");else{C.log("determining if should log: "+e.request.uri);var t=Object.assign({},e);if(this._getUserId()&&(t.user_id=this._getUserId()),this._getCompanyId()&&(t.company_id=this._getCompanyId()),this._getSession()&&(t.session_token=this._getSession()),t.tags=this._options.getTags(e)||"",this._options.apiVersion&&(t.request.api_version=this._options.apiVersion),this._options.maskContent&&(t=this._options.maskContent(t)),this._options.getMetadata)if(t.metadata){var r=this._options.getMetadata(t);t.metadata=Object.assign(t.metadata,r)}else t.metadata=this._options.getMetadata(t);if(this._options.skip(e)||qe(e))C.log("skipped logging for "+e.request.uri);else{C.log("sending or queuing"+e.request.uri);var n=xe+ge+me;this._sendOrBatch(t,this._options.applicationId,n,this.requestBatchers.events,this._options.callback)}}},_getUserId:function(){return this._userId},_getCompanyId:function(){return this._companyId},_getSession:function(){return this._session},stop:function(){this._stopRecording&&(this._stopRecording(),this._stopRecording=null),this._stopWeb3Recording&&(this._stopWeb3Recording(),this._stopWeb3Recording=null),this._stopFetchRecording&&(this._stopFetchRecording(),this._stopFetchRecording=null)}}}return Be()}()}])}]);
\ No newline at end of file
diff --git a/moesif.min.js b/moesif.min.js
index 07fd69a..514b07d 100644
--- a/moesif.min.js
+++ b/moesif.min.js
@@ -1,91 +1,90 @@
(function() {
-(function(){var ga,ha,ia,ja,ka,la,ma,L,M,N,O,P,W;function na(a,b,d){p.log("processResponse for"+a._url);var f=(new Date).toISOString();if(d){var h=a._url?a._url.toLowerCase():a._url;if(h&&0>h.indexOf("moesif.com")&&0>h.indexOf("apirequest.io")){a:if((h=a._url)&&"string"===typeof h){var e=c.trim(h);if(0!==e.indexOf("http")){h=Ha+window.location.host+"/"+e.replace(/^\./,"").replace(/^\//,"");break a}}h={uri:h,verb:a._method,time:a._startTime,headers:a._requestHeaders};if(b)if("string"===typeof b)p.log("request post data is string"),
-p.log(b),b=X(b),h.transfer_encoding=b.transfer_encoding,h.body=b.body;else if("object"===typeof b||Array.isArray(b)||"number"===typeof b||"boolean"===typeof b)h.body=b;e=a.getAllResponseHeaders();p.log("rawResponseHeaders are "+e);b={};if(e)for(var e=e.split("\r\n"),i=0;i=i.status)c&&c(XMLHttpRequest.responseText);else{var a;a=i.timeout&&!i.status&&(new Date).getTime()-k>=i.timeout?"timeout":"Bad HTTP status: "+i.status+" "+i.statusText;j.error(a);c&&c({status:0,error:a,xhr_req:i})}};i.send(E(b))}catch(g){j.error("failed to send to moesif "+(b&&b.request&&b.request.uri)),j.error(g),c&&c({status:0,error:g})}},initBatching:function(){var a=this._options.applicationId,b=this._options.host;j.log("does requestBatch.events exists? "+
-this.requestBatchers.events);if(!this.requestBatchers.events){var d={libConfig:this._options,sendRequestFunc:c.bind(function(a,b,d,c){this._executeRequest(a,b,d,c)},this),stopAllBatching:c.bind(function(){this.stopAllBatching()},this)},f=Ba(a),a=new A("__mf_"+f+"_ev",I+b+ha,d),b=new A("__mf_"+f+"_ac",I+b+ia,d);this.requestBatchers={events:a,actions:b}}c.each(this.requestBatchers,function(a){a.start()})},stopAllBatching:function(){this._options.batchEnabled=!1;c.each(this.requestBatchers,function(a){a.stop();
-a.clear()})},_sendOrBatch:function(a,b,d,f,h){var e=this,i=function(){return e._executeRequest(d,a,{applicationId:b},h)};if(this._options.batchEnabled&&f){j.log("current batcher storage key is "+f.queue.storageKey);var k=c.bind(function(a){a||(j.log("enqueue failed, send immediately"),i())},this);f.enqueue(a,k)}else return i();return!0},start:function(a){function b(a){d.recordEvent(a)}var d=this;if(this._stopRecording||this._stopWeb3Recording)return j.log("recording has already started, please call stop first."),
-!1;j.log("moesif starting");this._stopRecording=Ia(b,this._options);if(!this._options.disableFetch)j.log("also instrumenting fetch API"),this._stopFetchRecording=La(b);this.useWeb3(a);return!0},useWeb3:function(a){function b(a){d.recordEvent(a)}var d=this;try{if(this._stopWeb3Recording)this._stopWeb3Recording(),this._stopWeb3Recording=null;if(a)this._stopWeb3Recording=qa(a,b,this._options);else if(window.web3)j.log("found global web3, will capture from it"),this._stopWeb3Recording=qa(window.web3,
-b,this._options);if(this._stopWeb3Recording)return!0}catch(c){j.log("error patching web3, moving forward anyways"),this._options.callback&&this._options.callback({status:0,error:c,message:"failed to instrument web3, but moving forward with other instrumentation"})}return!1},updateUser:function(a,b,d,c){this._executeRequest(I+d+ja,a,{applicationId:b},c)},identifyUser:function(a,b){if(c.isNil(a))j.critical("identifyUser called with nil userId");else{this._userId=a;if(!this._options||!this._options.applicationId)throw Error("Init needs to be called with a valid application Id before calling identify User.");
-var d={user_id:a};b&&(d.metadata=b);if(this._session)d.session_token=this._session;if(this._campaign)d.campaign=this._campaign;if(this._companyId)d.company_id=this._companyId;d.anonymous_id=this._anonymousId;this.updateUser(d,this._options.applicationId,this._options.host,this._options.callback);try{a&&this._persist(L,a)}catch(f){j.error("error saving to local storage")}}},updateCompany:function(a,b,d,c){this._executeRequest(I+d+ka,a,{applicationId:b},c)},identifyCompany:function(a,b,d){if(c.isNil(a))j.critical("identifyCompany called with nil companyId.");
-else{var f=!!this._companyId;this._companyId=a;if(!this._options||!this._options.applicationId)throw Error("Init needs to be called with a valid application Id before calling identify User.");var h={company_id:a};d&&(h.company_domain=d);b&&(h.metadata=b);if(this._session)h.session_token=this._session;if(f)b=this._campaign;else{d=b=null;try{(d=H(W,this._options))&&(b=c.JSONDecode(d))}catch(e){y.error("failed to decode company campaign data "+d),y.error(e)}b=b||this._campaign}b&&(h.campaign=b);this.updateCompany(h,
-this._options.applicationId,this._options.host,this._options.callback);try{a&&this._persist(M,a)}catch(i){j.error("error saving to local storage")}}},identifySession:function(a){if(c.isNil(a))j.critical("identifySession called with nil");else if(this._session=a)try{this._persist(O,a)}catch(b){j.error("local storage error")}},track:function(a,b){if(!a)throw Error("track name must have action Name defined");var d={action_name:a};if(this._companyId)d.company_id=this._companyId;this._userId?d.user_id=
-this._userId:d.anonymous_id=this._anonymousId;if(this._session)d.session_token=this._session;d.request={uri:document.location.href,verb:"GET",user_agent_string:navigator.userAgent};d.transaction_id=c.uuid4();b&&(d.metadata=b);var f=I+this._options.host+la;j.log("sending or queuing: "+a);return this._sendOrBatch(d,this._options.applicationId,f,this.requestBatchers.actions,this._options.callback)},recordEvent:function(a){if(xa(a))j.log("skipped logging for requests to moesif");else{j.log("determining if should log: "+
-a.request.uri);var b=Object.assign({},a);this._getUserId()?b.user_id=this._getUserId():b.anonymous_id=this._anonymousId;this._getCompanyId()&&(b.company_id=this._getCompanyId());this._getSession()&&(b.session_token=this._getSession());b.tags=this._options.getTags(a)||"";if(this._options.apiVersion)b.request.api_version=this._options.apiVersion;if(!b.request.headers["User-Agent"])b.request.headers["User-Agent"]=window.navigator.userAgent;b.transaction_id=c.uuid4();this._options.maskContent&&(b=this._options.maskContent(b));
-if(this._options.getMetadata)if(b.metadata){var d=this._options.getMetadata(b);b.metadata=Object.assign(b.metadata,d)}else b.metadata=this._options.getMetadata(b);!this._options.skip(a)&&!xa(a)?(j.log("sending or queuing: "+a.request.uri),this._sendOrBatch(b,this._options.applicationId,I+this._options.host+ma,this.requestBatchers.events,this._options.callback)):j.log("skipped logging for "+a.request.uri)}},_getUserId:function(){return this._userId},_getCompanyId:function(){return this._companyId},
-_getSession:function(){return this._session},stop:function(){if(this._stopRecording)this._stopRecording(),this._stopRecording=null;if(this._stopWeb3Recording)this._stopWeb3Recording(),this._stopWeb3Recording=null;if(this._stopFetchRecording)this._stopFetchRecording(),this._stopFetchRecording=null},clearCookies:function(){ta(this._options)},clearStorage:function(){ua(this._options)},resetAnonymousId:function(){return this._anonymousId=Z(this._persist)},reset:function(){ta(this._options);ua(this._options);
-this._anonymousId=Z(this._persist);this._campaign=this._session=this._userId=this._companyId=null}}}var G={DEBUG:!1,LIB_VERSION:"1.8.12"},C;if("undefined"===typeof window){var B={hostname:""};C={navigator:{userAgent:""},document:{location:B,referrer:""},screen:{width:0,height:0},location:B}}else C=window;var B=Array.prototype,w=Object.prototype,J=B.slice,R=w.toString,T=w.hasOwnProperty,s=C.console,K=C.navigator,x=C.document,S=C.opera,U=C.screen,m=K.userAgent,aa=Function.prototype.bind,Ca=B.forEach,
-Da=B.indexOf,Ea=B.map,B=Array.isArray,ba={},c={trim:function(a){return a.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},j={log:function(){if(G.DEBUG&&!c.isUndefined(s)&&s)try{s.log.apply(s,arguments)}catch(a){c.each(arguments,function(a){s.log(a)})}},error:function(){if(G.DEBUG&&!c.isUndefined(s)&&s){var a=["Moesif error:"].concat(c.toArray(arguments));try{s.error.apply(s,a)}catch(b){c.each(a,function(a){s.error(a)})}}},critical:function(){if(!c.isUndefined(s)&&s){var a=["Moesif error:"].concat(c.toArray(arguments));
-try{s.error.apply(s,a)}catch(b){c.each(a,function(a){s.error(a)})}}}},ca=function(a,b){return function(){arguments[0]="["+b+"] "+arguments[0];return a.apply(j,arguments)}},w=function(a){return{log:ca(j.log,a),error:ca(j.error,a),critical:ca(j.critical,a)}};c.bind=function(a,b){var d,f;if(aa&&a.bind===aa)return aa.apply(a,J.call(arguments,1));if(!c.isFunction(a))throw new TypeError;d=J.call(arguments,2);return f=function(){if(!(this instanceof f))return a.apply(b,d.concat(J.call(arguments)));var c=
-{};c.prototype=a.prototype;var e=new c;c.prototype=null;c=a.apply(e,d.concat(J.call(arguments)));return Object(c)===c?c:e}};c.bind_instance_methods=function(a){for(var b in a)"function"===typeof a[b]&&(a[b]=c.bind(a[b],a))};c.each=function(a,b,d){if(!(null===a||void 0===a))if(Ca&&a.forEach===Ca)a.forEach(b,d);else if(a.length===+a.length)for(var c=0,h=a.length;c/g,">").replace(/"/g,""").replace(/'/g,"'"));return a};c.extend=function(a){c.each(J.call(arguments,1),function(b){for(var d in b)void 0!==b[d]&&(a[d]=b[d])});return a};c.isArray=B||function(a){return"[object Array]"===R.call(a)};c.isFunction=function(a){try{return/^\s*\bfunction\b/.test(a)}catch(b){return!1}};c.isArguments=function(a){return!(!a||!T.call(a,"callee"))};c.toArray=function(a){return!a?[]:a.toArray?a.toArray():c.isArray(a)||
-c.isArguments(a)?J.call(a):c.values(a)};c.map=function(a,b){if(Ea&&a.map===Ea)return a.map(b);var d=[];c.each(a,function(a){d.push(b(a))});return d};c.keys=function(a){var b=[];if(null===a)return b;c.each(a,function(a,c){b[b.length]=c});return b};c.values=function(a){var b=[];if(null===a)return b;c.each(a,function(a){b[b.length]=a});return b};c.identity=function(a){return a};c.include=function(a,b){var d=!1;if(null===a)return d;if(Da&&a.indexOf===Da)return-1!=a.indexOf(b);c.each(a,function(a){if(d||
-(d=a===b))return ba});return d};c.includes=function(a,b){return-1!==a.indexOf(b)};c.inherit=function(a,b){a.prototype=new b;a.prototype.constructor=a;a.superclass=b.prototype;return a};c.isArrayBuffer=function(a){var b=Object.prototype.toString;return"function"===typeof ArrayBuffer&&(a instanceof ArrayBuffer||"[object ArrayBuffer]"===b.call(a))};c.isObject=function(a){return a===Object(a)&&!c.isArray(a)};c.isEmptyObject=function(a){if(c.isObject(a)){for(var b in a)if(T.call(a,b))return!1;return!0}return!1};
-c.isEmptyString=function(a){return!a||0===a.length};c.isUndefined=function(a){return void 0===a};c.isString=function(a){return"[object String]"==R.call(a)};c.isDate=function(a){return"[object Date]"==R.call(a)};c.isNumber=function(a){return"[object Number]"==R.call(a)};c.isElement=function(a){return!!(a&&1===a.nodeType)};c.isNil=function(a){return c.isUndefined(a)||null===a};c.encodeDates=function(a){c.each(a,function(b,d){c.isDate(b)?a[d]=c.formatDate(b):c.isObject(b)&&(a[d]=c.encodeDates(b))});
-return a};c.timestamp=function(){Date.now=Date.now||function(){return+new Date};return Date.now()};c.formatDate=function(a){function b(a){return 10>a?"0"+a:a}return a.getUTCFullYear()+"-"+b(a.getUTCMonth()+1)+"-"+b(a.getUTCDate())+"T"+b(a.getUTCHours())+":"+b(a.getUTCMinutes())+":"+b(a.getUTCSeconds())};c.safewrap=function(a){return function(){try{return a.apply(this,arguments)}catch(b){j.critical("Implementation error. Please turn on debug and contact support@Moesif.com."),G.DEBUG&&j.critical(b)}}};
-c.safewrap_class=function(a,b){for(var d=0;d=b;)a+=b,e();if("."===b)for(a+=".";e()&&"0"<=b&&"9">=b;)a+=
-b;if("e"===b||"E"===b){a+=b;e();if("-"===b||"+"===b)a+=b,e();for(;"0"<=b&&"9">=b;)a+=b,e()}a=+a;if(isFinite(a))return a;h("Bad number")},k=function(){var a,f,g="",i;if('"'===b)for(;e();){if('"'===b)return e(),g;if("\\"===b)if(e(),"u"===b){for(f=i=0;4>f;f+=1){a=parseInt(e(),16);if(!isFinite(a))break;i=16*i+a}g+=String.fromCharCode(i)}else if("string"===typeof c[b])g+=c[b];else break;else g+=b}h("Bad string")},g=function(){for(;b&&" ">=b;)e()},l=function(){switch(b){case "t":return e("t"),e("r"),e("u"),
-e("e"),!0;case "f":return e("f"),e("a"),e("l"),e("s"),e("e"),!1;case "n":return e("n"),e("u"),e("l"),e("l"),null}h('Unexpected "'+b+'"')},n;n=function(){g();switch(b){case "{":var a;a:{var c,d={};if("{"===b){e("{");g();if("}"===b){e("}");a=d;break a}for(;b;){c=k();g();e(":");Object.hasOwnProperty.call(d,c)&&h('Duplicate key "'+c+'"');d[c]=n();g();if("}"===b){e("}");a=d;break a}e(",");g()}}h("Bad object")}return a;case "[":a:{a=[];if("["===b){e("[");g();if("]"===b){e("]");c=a;break a}for(;b;){a.push(n());
-g();if("]"===b){e("]");c=a;break a}e(",");g()}}h("Bad array")}return c;case '"':return k();case "-":return i();default:return"0"<=b&&"9">=b?i():l()}};return function(c){f=c;a=0;b=" ";c=n();g();b&&h("Syntax error");return c}}();c.base64Encode=function(a){var b,d,f,h,e=0,i=0,k="",k=[];if(!a)return a;a=c.utf8Encode(a);do b=a.charCodeAt(e++),d=a.charCodeAt(e++),f=a.charCodeAt(e++),h=b<<16|d<<8|f,b=h>>18&63,d=h>>12&63,f=h>>6&63,h&=63,k[i++]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(b)+
-"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(d)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(f)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(h);while(ei?f++:k=127i?String.fromCharCode(i>>6|192,i&63|128):String.fromCharCode(i>>12|224,i>>6&63|128,i&63|128);null!==k&&(f>c&&(b+=a.substring(c,f)),b+=k,c=f=e+1)}f>c&&(b+=a.substring(c,a.length));return b};c.UUID=function(){var a=function(){function a(b,c){var d,e=0;for(d=0;d>>0)%100=a.byteLength)return{};try{var b=(new TextDecoder("utf-8")).decode(a);try{return{body:c.JSONDecode(b)}}catch(d){return D.error(d),{transfer_encoding:"base64",body:c.base64Encode(b)}}}catch(f){return D.error(f),D.log(a),{transfer_encoding:"base64",body:"can not be decoded"}}},p=w("capture"),Ha="http:"===(document&&document.location.protocol)?"http://":"https://",u=w("web3capture"),r=w("capture fetch"),va=
-w("referrer"),sa=w("utm"),q={UTM_SOURCE:"utm_source",UTM_MEDIUM:"utm_medium",UTM_CAMPAIGN:"utm_campaign",UTM_TERM:"utm_term",UTM_CONTENT:"utm_content"};L="moesif_stored_user_id";M="moesif_stored_company_id";O="moesif_stored_session_id";N="moesif_anonymous_id";P="moesif_campaign_data";W="moesif_initial_campaign";var y=w("campaign"),Wa=w("lock"),Ga=function(a,b){b=b||{};this.storageKey=a;this.storage=b.storage||window.localStorage;this.pollIntervalMS=b.pollIntervalMS||100;this.timeoutMS=b.timeoutMS||
-2E3};Ga.prototype.withLock=function(a,b,c){!c&&"function"!==typeof b&&(c=b,b=null);var f=c||(new Date).getTime()+"|"+Math.random(),h=(new Date).getTime(),e=this.storageKey,i=this.pollIntervalMS,k=this.timeoutMS,g=this.storage,l=e+":X",j=e+":Y",m=e+":Z",o=function(a){(new Date).getTime()-h>k?(Wa.error("Timeout waiting for mutex on "+e+"; clearing lock. ["+f+"]"),g.removeItem(m),g.removeItem(j),q()):setTimeout(function(){try{a()}catch(c){b&&b(c)}},i*(Math.random()+0.1))},p=function(a,b){a()?b():o(function(){p(a,
-b)})},r=function(){var a=g.getItem(j);if(a&&a!==f)return!1;g.setItem(j,f);if(g.getItem(j)===f)return!0;if(!Q(g,!0))throw Error("localStorage support dropped while acquiring lock");return!1},q=function(){g.setItem(l,f);p(r,function(){g.getItem(l)===f?t():o(function(){g.getItem(j)!==f?q():p(function(){return!g.getItem(m)},t)})})},t=function(){g.setItem(m,"1");try{a()}finally{g.removeItem(m),g.getItem(j)===f&&g.removeItem(j),g.getItem(l)===f&&g.removeItem(l)}};try{if(Q(g,!0))q();else throw Error("localStorage support check failed");
-}catch(s){b&&b(s)}};var o=w("batch"),F=function(a,b){b=b||{};this.storageKey=a;this.storage=b.storage||window.localStorage;this.lock=new Ga(a,{storage:this.storage});this.storageExpiration=b.storageExpiration||216E5;this.pid=b.pid||null;this.memQueue=[]};F.prototype.enqueue=function(a,b,d){var f={id:ea(),flushAfter:(new Date).getTime()+2*b,payload:a};this.lock.withLock(c.bind(function(){var b;try{var c=this.readFromStorage();c.push(f);if(b=this.saveToStorage(c))o.log("succeeded saving to storage"),
-this.memQueue.push(f)}catch(i){o.error("Error enqueueing item",a),b=!1}d&&d(b)},this),function(a){o.error("Error acquiring storage lock",a);d&&d(!1)},this.pid)};F.prototype.fillBatch=function(a){this.memQueue=fa(this.memQueue,{},this.storageExpiration);var b=this.memQueue.slice(0,a);if(b.lengthe.flushAfter&&e.flushAfter>=j&&!f[e.id]){if(b.push(e),b.length>=a)break}else o.log("fill batch filtered item because invalid or expired"+E(e))}}}return b};var fa=function(a,b,d){var f=[],h=(new Date).getTime()-d;o.log("expiration time is "+h);c.each(a,function(a){a.id&&!b[a.id]?a.flushAfter&&a.flushAfter>=h&&f.push(a):o.log("filtered out item because invalid or expired"+E(a))});return f};F.prototype.removeItemsByID=function(a,b){var d={};c.each(a,function(a){d[a]=!0});this.memQueue=fa(this.memQueue,
-d,this.storageExpiration);var f=c.bind(function(){var b;try{var c=this.readFromStorage(),c=fa(c,d,this.storageExpiration);b=this.saveToStorage(c)}catch(f){o.error("Error removing items",a),b=!1}return b},this);this.lock.withLock(c.bind(function(){var a=f();b&&(o.log("triggering callback of removalItems"),b(a))},this),c.bind(function(a){var c=!1;o.error("Error acquiring storage lock",a);if(!Q(this.storage,!0)&&(c=f(),!c)){o.error("still can not remove from storage, thus stop using storage");try{this.storage.removeItem(this.storageKey)}catch(d){o.error("error clearing queue",
-d)}}b&&b(c)},this),this.pid)};F.prototype.readFromStorage=function(){var a;try{o.log("trying to get storage with storage key "+this.storageKey),(a=this.storage.getItem(this.storageKey))?(a=V(a),c.isArray(a)||(o.error("Invalid storage entry:",a),a=null)):o.log("storageEntry is empty")}catch(b){o.error("Error retrieving queue",b),a=null}return a||[]};F.prototype.saveToStorage=function(a){try{return this.storage.setItem(this.storageKey,E(a)),!0}catch(b){return o.error("Error saving queue",b),!1}};F.prototype.clear=
-function(){this.memQueue=[];try{this.storage.removeItem(this.storageKey)}catch(a){o.error("Failed to clear storage",a)}};var z=w("batch"),A=function(a,b,c){this.queue=new F(a,{storage:c.storage,storageExpiration:c.libConfig.batch_storage_expiration});this.endpoint=b;this.libConfig=c.libConfig;this.sendRequest=c.sendRequestFunc;this.batchSize=this.libConfig.batch_size;this.flushInterval=this.libConfig.batch_flush_interval_ms;this.stopAllBatching=c.stopAllBatching;this.stopped=!1;this.removalFailures=
-0};A.prototype.enqueue=function(a,b){this.queue.enqueue(a,this.flushInterval,b)};A.prototype.start=function(){this.stopped=!1;this.removalFailures=0;this.flush()};A.prototype.stop=function(){this.stopped=!0;if(this.timeoutID)clearTimeout(this.timeoutID),this.timeoutID=null};A.prototype.clear=function(){this.queue.clear()};A.prototype.resetBatchSize=function(){this.batchSize=this.libConfig.batch_size};A.prototype.resetFlush=function(){this.scheduleFlush(this.libConfig.batch_flush_interval_ms)};A.prototype.scheduleFlush=
-function(a){this.flushInterval=a;if(!this.stopped)this.timeoutID=setTimeout(c.bind(this.flush,this),this.flushInterval)};A.prototype.flush=function(a){try{if(this.requestInProgress)z.log("Flush: Request already in progress");else{var a=a||{},b=this.batchSize,d=this.queue.fillBatch(b);z.log("current batch size is "+d.length);if(1>d.length)this.resetFlush();else{this.requestInProgress=!0;var f=this.libConfig.batch_request_timeout_ms,h=(new Date).getTime(),e=c.map(d,function(a){return a.payload}),i=
-c.bind(function(a){this.requestInProgress=!1;try{var e=!1;if(c.isObject(a)&&"timeout"===a.error&&(new Date).getTime()-h>=f)z.error("Network timeout; retrying"),this.flush();else if(c.isObject(a)&&a.xhr_req&&(500<=a.xhr_req.status||0>=a.xhr_req.status)){var g=2*this.flushInterval,i=a.xhr_req.responseHeaders;if(i){var j=i["Retry-After"];j&&(g=1E3*parseInt(j,10)||g)}g=Math.min(6E5,g);z.error("Error; retry in "+g+" ms");this.scheduleFlush(g)}else if(c.isObject(a)&&a.xhr_req&&413===a.xhr_req.status)if(1<
-d.length){var k=Math.max(1,Math.floor(b/2));this.batchSize=Math.min(this.batchSize,k,d.length-1);z.error("413 response; reducing batch size to "+this.batchSize);this.resetFlush()}else z.error("Single-event request too large; dropping",d),this.resetBatchSize(),e=!0;else e=!0;e&&this.queue.removeItemsByID(c.map(d,function(a){return a.id}),c.bind(function(a){a?(this.removalFailures=0,this.flush()):(this.removalFailures+=1,z.error("failed to remove items from batched queue "+this.removalFailures+" times."),
-5g.indexOf("moesif.com")&&0>g.indexOf("apirequest.io")){a:if((g=a._url)&&"string"===typeof g){var e=c.trim(g);if(0!==e.indexOf("http")){g=Ma+window.location.host+"/"+e.replace(/^\./,"").replace(/^\//,"");break a}}g={uri:g,verb:a._method,time:a._startTime,headers:a._requestHeaders};if(b)if("string"===typeof b)p.log("request post data is string"),
+p.log(b),b=$(b),g.transfer_encoding=b.transfer_encoding,g.body=b.body;else if("object"===typeof b||Array.isArray(b)||"number"===typeof b||"boolean"===typeof b)g.body=b;e=a.getAllResponseHeaders();p.log("rawResponseHeaders are "+e);b={};if(e)for(var e=e.split("\r\n"),i=0;i=i.status)c&&c(XMLHttpRequest.responseText);else{var a;a=i.timeout&&
+!i.status&&(new Date).getTime()-j>=i.timeout?"timeout":"Bad HTTP status: "+i.status+" "+i.statusText;k.error(a);c&&c({status:0,error:a,xhr_req:i})}};i.send(B(b))}catch(h){k.error("failed to send to moesif "+(b&&b.request&&b.request.uri)),k.error(h),c&&c({status:0,error:h})}},initBatching:function(){var a=this._options.applicationId,b=this._options.host;k.log("does requestBatch.events exists? "+this.requestBatchers.events);if(!this.requestBatchers.events){var d={libConfig:this._options,sendRequestFunc:c.bind(function(a,
+b,d,c){this._executeRequest(a,b,d,c)},this),stopAllBatching:c.bind(function(){this.stopAllBatching()},this)},f=Ga(a),a=new x("__mf_"+f+"_ev",F+b+la,d),b=new x("__mf_"+f+"_ac",F+b+ma,d);this.requestBatchers={events:a,actions:b}}c.each(this.requestBatchers,function(a){a.start()})},stopAllBatching:function(){this._options.batchEnabled=!1;c.each(this.requestBatchers,function(a){a.stop();a.clear()})},_sendOrBatch:function(a,b,d,f,g){var e=this,i=function(){return e._executeRequest(d,a,{applicationId:b},
+g)};if(this._options.batchEnabled&&f){k.log("current batcher storage key is "+f.queue.storageKey);var j=c.bind(function(a){a||(k.log("enqueue failed, send immediately"),i())},this);f.enqueue(a,j)}else return i();return!0},start:function(a){function b(a){d.recordEvent(a)}var d=this;if(this._stopRecording||this._stopWeb3Recording)return k.log("recording has already started, please call stop first."),!1;k.log("moesif starting");this._stopRecording=Na(b,this._options);if(!this._options.disableFetch)k.log("also instrumenting fetch API"),
+this._stopFetchRecording=Qa(b);this.useWeb3(a);return!0},useWeb3:function(a){function b(a){d.recordEvent(a)}var d=this;try{if(this._stopWeb3Recording)this._stopWeb3Recording(),this._stopWeb3Recording=null;if(a)this._stopWeb3Recording=ua(a,b,this._options);else if(window.web3)k.log("found global web3, will capture from it"),this._stopWeb3Recording=ua(window.web3,b,this._options);if(this._stopWeb3Recording)return!0}catch(c){k.log("error patching web3, moving forward anyways"),this._options.callback&&
+this._options.callback({status:0,error:c,message:"failed to instrument web3, but moving forward with other instrumentation"})}return!1},updateUser:function(a,b,d,c){this._executeRequest(F+d+na,a,{applicationId:b},c)},identifyUser:function(a,b){if(c.isNil(a))k.critical("identifyUser called with nil userId");else{this._userId=a;if(!this._options||!this._options.applicationId)throw Error("Init needs to be called with a valid application Id before calling identify User.");var d={user_id:a};b&&(d.metadata=
+b);if(this._session)d.session_token=this._session;var f=Ba(this._persist,this._options,M)||this._currentCampaign;f&&(d.campaign=f);if(this._companyId)d.company_id=this._companyId;d.anonymous_id=this._anonymousId;this.updateUser(d,this._options.applicationId,this._options.host,this._options.callback);try{a&&this._persist(I,a)}catch(g){k.error("error saving to local storage")}}},updateCompany:function(a,b,d,c){this._executeRequest(F+d+oa,a,{applicationId:b},c)},identifyCompany:function(a,b,d){if(c.isNil(a))k.critical("identifyCompany called with nil companyId.");
+else{this._companyId=a;if(!this._options||!this._options.applicationId)throw Error("Init needs to be called with a valid application Id before calling identify User.");var f={company_id:a};d&&(f.company_domain=d);b&&(f.metadata=b);if(this._session)f.session_token=this._session;(b=Ba(this._persist,this._options,N)||this._currentCampaign)&&(f.campaign=b);this.updateCompany(f,this._options.applicationId,this._options.host,this._options.callback);try{a&&this._persist(J,a)}catch(g){k.error("error saving to local storage")}}},
+identifySession:function(a){if(c.isNil(a))k.critical("identifySession called with nil");else if(this._session=a)try{this._persist(L,a)}catch(b){k.error("local storage error")}},track:function(a,b){if(!a)throw Error("track name must have action Name defined");var d={action_name:a};if(this._companyId)d.company_id=this._companyId;this._userId?d.user_id=this._userId:d.anonymous_id=this._anonymousId;if(this._session)d.session_token=this._session;d.request={uri:document.location.href,verb:"GET",user_agent_string:navigator.userAgent};
+d.transaction_id=c.uuid4();b&&(d.metadata=b);var f=F+this._options.host+pa;k.log("sending or queuing: "+a);return this._sendOrBatch(d,this._options.applicationId,f,this.requestBatchers.actions,this._options.callback)},recordEvent:function(a){if(Ca(a))k.log("skipped logging for requests to moesif");else{k.log("determining if should log: "+a.request.uri);var b=Object.assign({},a);this._getUserId()?b.user_id=this._getUserId():b.anonymous_id=this._anonymousId;this._getCompanyId()&&(b.company_id=this._getCompanyId());
+this._getSession()&&(b.session_token=this._getSession());b.tags=this._options.getTags(a)||"";if(this._options.apiVersion)b.request.api_version=this._options.apiVersion;if(!b.request.headers["User-Agent"])b.request.headers["User-Agent"]=window.navigator.userAgent;b.transaction_id=c.uuid4();this._options.maskContent&&(b=this._options.maskContent(b));if(this._options.getMetadata)if(b.metadata){var d=this._options.getMetadata(b);b.metadata=Object.assign(b.metadata,d)}else b.metadata=this._options.getMetadata(b);
+!this._options.skip(a)&&!Ca(a)?(k.log("sending or queuing: "+a.request.uri),this._sendOrBatch(b,this._options.applicationId,F+this._options.host+qa,this.requestBatchers.events,this._options.callback)):k.log("skipped logging for "+a.request.uri)}},_getUserId:function(){return this._userId},_getCompanyId:function(){return this._companyId},_getSession:function(){return this._session},stop:function(){if(this._stopRecording)this._stopRecording(),this._stopRecording=null;if(this._stopWeb3Recording)this._stopWeb3Recording(),
+this._stopWeb3Recording=null;if(this._stopFetchRecording)this._stopFetchRecording(),this._stopFetchRecording=null},clearCookies:function(){xa(this._options)},clearStorage:function(){ya(this._options)},resetAnonymousId:function(){return this._anonymousId=ca(this._persist)},reset:function(){xa(this._options);ya(this._options);this._anonymousId=ca(this._persist);this._currentCampaign=this._session=this._userId=this._companyId=null}}}var D={DEBUG:!1,LIB_VERSION:"1.8.13"},z;if("undefined"===typeof window){var y=
+{hostname:""};z={navigator:{userAgent:""},document:{location:y,referrer:""},screen:{width:0,height:0},location:y}}else z=window;var y=Array.prototype,u=Object.prototype,G=y.slice,Q=u.toString,S=u.hasOwnProperty,r=z.console,H=z.navigator,v=z.document,R=z.opera,T=z.screen,n=H.userAgent,ea=Function.prototype.bind,Ha=y.forEach,Ia=y.indexOf,Ja=y.map,y=Array.isArray,fa={},c={trim:function(a){return a.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},k={log:function(){if(D.DEBUG&&!c.isUndefined(r)&&r)try{r.log.apply(r,
+arguments)}catch(a){c.each(arguments,function(a){r.log(a)})}},error:function(){if(D.DEBUG&&!c.isUndefined(r)&&r){var a=["Moesif error:"].concat(c.toArray(arguments));try{r.error.apply(r,a)}catch(b){c.each(a,function(a){r.error(a)})}}},critical:function(){if(!c.isUndefined(r)&&r){var a=["Moesif error:"].concat(c.toArray(arguments));try{r.error.apply(r,a)}catch(b){c.each(a,function(a){r.error(a)})}}}},ga=function(a,b){return function(){arguments[0]="["+b+"] "+arguments[0];return a.apply(k,arguments)}},
+u=function(a){return{log:ga(k.log,a),error:ga(k.error,a),critical:ga(k.critical,a)}};c.bind=function(a,b){var d,f;if(ea&&a.bind===ea)return ea.apply(a,G.call(arguments,1));if(!c.isFunction(a))throw new TypeError;d=G.call(arguments,2);return f=function(){if(!(this instanceof f))return a.apply(b,d.concat(G.call(arguments)));var c={};c.prototype=a.prototype;var e=new c;c.prototype=null;c=a.apply(e,d.concat(G.call(arguments)));return Object(c)===c?c:e}};c.bind_instance_methods=function(a){for(var b in a)"function"===
+typeof a[b]&&(a[b]=c.bind(a[b],a))};c.each=function(a,b,d){if(!(null===a||void 0===a))if(Ha&&a.forEach===Ha)a.forEach(b,d);else if(a.length===+a.length)for(var c=0,g=a.length;c/g,">").replace(/"/g,""").replace(/'/g,"'"));return a};c.extend=function(a){c.each(G.call(arguments,1),function(b){for(var d in b)void 0!==
+b[d]&&(a[d]=b[d])});return a};c.isArray=y||function(a){return"[object Array]"===Q.call(a)};c.isFunction=function(a){try{return/^\s*\bfunction\b/.test(a)}catch(b){return!1}};c.isArguments=function(a){return!(!a||!S.call(a,"callee"))};c.toArray=function(a){return!a?[]:a.toArray?a.toArray():c.isArray(a)||c.isArguments(a)?G.call(a):c.values(a)};c.map=function(a,b){if(Ja&&a.map===Ja)return a.map(b);var d=[];c.each(a,function(a){d.push(b(a))});return d};c.keys=function(a){var b=[];if(null===a)return b;
+c.each(a,function(a,c){b[b.length]=c});return b};c.values=function(a){var b=[];if(null===a)return b;c.each(a,function(a){b[b.length]=a});return b};c.identity=function(a){return a};c.include=function(a,b){var d=!1;if(null===a)return d;if(Ia&&a.indexOf===Ia)return-1!=a.indexOf(b);c.each(a,function(a){if(d||(d=a===b))return fa});return d};c.includes=function(a,b){return-1!==a.indexOf(b)};c.inherit=function(a,b){a.prototype=new b;a.prototype.constructor=a;a.superclass=b.prototype;return a};c.isArrayBuffer=
+function(a){var b=Object.prototype.toString;return"function"===typeof ArrayBuffer&&(a instanceof ArrayBuffer||"[object ArrayBuffer]"===b.call(a))};c.isObject=function(a){return a===Object(a)&&!c.isArray(a)};c.isEmptyObject=function(a){if(c.isObject(a)){for(var b in a)if(S.call(a,b))return!1;return!0}return!1};c.isEmptyString=function(a){return!a||0===a.length};c.isUndefined=function(a){return void 0===a};c.isString=function(a){return"[object String]"==Q.call(a)};c.isDate=function(a){return"[object Date]"==
+Q.call(a)};c.isNumber=function(a){return"[object Number]"==Q.call(a)};c.isElement=function(a){return!!(a&&1===a.nodeType)};c.isNil=function(a){return c.isUndefined(a)||null===a};c.encodeDates=function(a){c.each(a,function(b,d){c.isDate(b)?a[d]=c.formatDate(b):c.isObject(b)&&(a[d]=c.encodeDates(b))});return a};c.timestamp=function(){Date.now=Date.now||function(){return+new Date};return Date.now()};c.formatDate=function(a){function b(a){return 10>a?"0"+a:a}return a.getUTCFullYear()+"-"+b(a.getUTCMonth()+
+1)+"-"+b(a.getUTCDate())+"T"+b(a.getUTCHours())+":"+b(a.getUTCMinutes())+":"+b(a.getUTCSeconds())};c.safewrap=function(a){return function(){try{return a.apply(this,arguments)}catch(b){k.critical("Implementation error. Please turn on debug and contact support@Moesif.com."),D.DEBUG&&k.critical(b)}}};c.safewrap_class=function(a,b){for(var d=0;d=b;)a+=b,e();if("."===b)for(a+=".";e()&&"0"<=b&&"9">=b;)a+=b;if("e"===b||"E"===b){a+=b;e();if("-"===b||"+"===b)a+=b,e();for(;"0"<=b&&"9">=b;)a+=b,e()}a=+a;if(isFinite(a))return a;g("Bad number")},j=function(){var a,f,h="",i;if('"'===b)for(;e();){if('"'===b)return e(),h;if("\\"===b)if(e(),"u"===b){for(f=
+i=0;4>f;f+=1){a=parseInt(e(),16);if(!isFinite(a))break;i=16*i+a}h+=String.fromCharCode(i)}else if("string"===typeof c[b])h+=c[b];else break;else h+=b}g("Bad string")},h=function(){for(;b&&" ">=b;)e()},l=function(){switch(b){case "t":return e("t"),e("r"),e("u"),e("e"),!0;case "f":return e("f"),e("a"),e("l"),e("s"),e("e"),!1;case "n":return e("n"),e("u"),e("l"),e("l"),null}g('Unexpected "'+b+'"')},m;m=function(){h();switch(b){case "{":var a;a:{var c,d={};if("{"===b){e("{");h();if("}"===b){e("}");a=
+d;break a}for(;b;){c=j();h();e(":");Object.hasOwnProperty.call(d,c)&&g('Duplicate key "'+c+'"');d[c]=m();h();if("}"===b){e("}");a=d;break a}e(",");h()}}g("Bad object")}return a;case "[":a:{a=[];if("["===b){e("[");h();if("]"===b){e("]");c=a;break a}for(;b;){a.push(m());h();if("]"===b){e("]");c=a;break a}e(",");h()}}g("Bad array")}return c;case '"':return j();case "-":return i();default:return"0"<=b&&"9">=b?i():l()}};return function(c){f=c;a=0;b=" ";c=m();h();b&&g("Syntax error");return c}}();c.base64Encode=
+function(a){var b,d,f,g,e=0,i=0,j="",j=[];if(!a)return a;a=c.utf8Encode(a);do b=a.charCodeAt(e++),d=a.charCodeAt(e++),f=a.charCodeAt(e++),g=b<<16|d<<8|f,b=g>>18&63,d=g>>12&63,f=g>>6&63,g&=63,j[i++]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(b)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(d)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(f)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(g);
+while(ei?f++:j=127i?String.fromCharCode(i>>6|192,i&63|128):String.fromCharCode(i>>12|224,i>>6&63|128,i&63|128);null!==j&&(f>c&&(b+=a.substring(c,f)),b+=j,c=f=e+1)}f>c&&(b+=a.substring(c,a.length));return b};c.UUID=function(){var a=
+function(){function a(b,c){var d,e=0;for(d=0;d>>0)%100=a.byteLength)return{};try{var b=(new TextDecoder("utf-8")).decode(a);try{return{body:c.JSONDecode(b)}}catch(d){return A.error(d),{transfer_encoding:"base64",body:c.base64Encode(b)}}}catch(f){return A.error(f),A.log(a),{transfer_encoding:"base64",body:"can not be decoded"}}},p=u("capture"),Ma="http:"===(document&&document.location.protocol)?
+"http://":"https://",t=u("web3capture"),s=u("capture fetch"),za=u("referrer"),wa=u("utm");V="utm_source";W="utm_medium";X="utm_campaign";Y="utm_term";Z="utm_content";I="moesif_stored_user_id";J="moesif_stored_company_id";L="moesif_stored_session_id";K="moesif_anonymous_id";M="moesif_campaign_data";N="moesif_campaign_company";var E=u("campaign"),ab=u("lock"),La=function(a,b){b=b||{};this.storageKey=a;this.storage=b.storage||window.localStorage;this.pollIntervalMS=b.pollIntervalMS||100;this.timeoutMS=
+b.timeoutMS||2E3};La.prototype.withLock=function(a,b,c){!c&&"function"!==typeof b&&(c=b,b=null);var f=c||(new Date).getTime()+"|"+Math.random(),g=(new Date).getTime(),e=this.storageKey,i=this.pollIntervalMS,j=this.timeoutMS,h=this.storage,k=e+":X",m=e+":Y",n=e+":Z",o=function(a){(new Date).getTime()-g>j?(ab.error("Timeout waiting for mutex on "+e+"; clearing lock. ["+f+"]"),h.removeItem(n),h.removeItem(m),q()):setTimeout(function(){try{a()}catch(c){b&&b(c)}},i*(Math.random()+0.1))},p=function(a,b){a()?
+b():o(function(){p(a,b)})},s=function(){var a=h.getItem(m);if(a&&a!==f)return!1;h.setItem(m,f);if(h.getItem(m)===f)return!0;if(!P(h,!0))throw Error("localStorage support dropped while acquiring lock");return!1},q=function(){h.setItem(k,f);p(s,function(){h.getItem(k)===f?r():o(function(){h.getItem(m)!==f?q():p(function(){return!h.getItem(n)},r)})})},r=function(){h.setItem(n,"1");try{a()}finally{h.removeItem(n),h.getItem(m)===f&&h.removeItem(m),h.getItem(k)===f&&h.removeItem(k)}};try{if(P(h,!0))q();
+else throw Error("localStorage support check failed");}catch(t){b&&b(t)}};var o=u("batch"),C=function(a,b){b=b||{};this.storageKey=a;this.storage=b.storage||window.localStorage;this.lock=new La(a,{storage:this.storage});this.storageExpiration=b.storageExpiration||216E5;this.pid=b.pid||null;this.memQueue=[]};C.prototype.enqueue=function(a,b,d){var f={id:ia(),flushAfter:(new Date).getTime()+2*b,payload:a};this.lock.withLock(c.bind(function(){var b;try{var c=this.readFromStorage();c.push(f);if(b=this.saveToStorage(c))o.log("succeeded saving to storage"),
+this.memQueue.push(f)}catch(i){o.error("Error enqueueing item",a),b=!1}d&&d(b)},this),function(a){o.error("Error acquiring storage lock",a);d&&d(!1)},this.pid)};C.prototype.fillBatch=function(a){this.memQueue=ja(this.memQueue,{},this.storageExpiration);var b=this.memQueue.slice(0,a);if(b.lengthe.flushAfter&&e.flushAfter>=j&&!f[e.id]){if(b.push(e),b.length>=a)break}else o.log("fill batch filtered item because invalid or expired"+B(e))}}}return b};var ja=function(a,b,d){var f=[],g=(new Date).getTime()-d;o.log("expiration time is "+g);c.each(a,function(a){a.id&&!b[a.id]?a.flushAfter&&a.flushAfter>=g&&f.push(a):o.log("filtered out item because invalid or expired"+B(a))});return f};C.prototype.removeItemsByID=function(a,b){var d={};c.each(a,function(a){d[a]=!0});this.memQueue=ja(this.memQueue,
+d,this.storageExpiration);var f=c.bind(function(){var b;try{var c=this.readFromStorage(),c=ja(c,d,this.storageExpiration);b=this.saveToStorage(c)}catch(f){o.error("Error removing items",a),b=!1}return b},this);this.lock.withLock(c.bind(function(){var a=f();b&&(o.log("triggering callback of removalItems"),b(a))},this),c.bind(function(a){var c=!1;o.error("Error acquiring storage lock",a);if(!P(this.storage,!0)&&(c=f(),!c)){o.error("still can not remove from storage, thus stop using storage");try{this.storage.removeItem(this.storageKey)}catch(d){o.error("error clearing queue",
+d)}}b&&b(c)},this),this.pid)};C.prototype.readFromStorage=function(){var a;try{o.log("trying to get storage with storage key "+this.storageKey),(a=this.storage.getItem(this.storageKey))?(a=U(a),c.isArray(a)||(o.error("Invalid storage entry:",a),a=null)):o.log("storageEntry is empty")}catch(b){o.error("Error retrieving queue",b),a=null}return a||[]};C.prototype.saveToStorage=function(a){try{return this.storage.setItem(this.storageKey,B(a)),!0}catch(b){return o.error("Error saving queue",b),!1}};C.prototype.clear=
+function(){this.memQueue=[];try{this.storage.removeItem(this.storageKey)}catch(a){o.error("Failed to clear storage",a)}};var w=u("batch"),x=function(a,b,c){this.queue=new C(a,{storage:c.storage,storageExpiration:c.libConfig.batch_storage_expiration});this.endpoint=b;this.libConfig=c.libConfig;this.sendRequest=c.sendRequestFunc;this.batchSize=this.libConfig.batch_size;this.flushInterval=this.libConfig.batch_flush_interval_ms;this.stopAllBatching=c.stopAllBatching;this.stopped=!1;this.removalFailures=
+0};x.prototype.enqueue=function(a,b){this.queue.enqueue(a,this.flushInterval,b)};x.prototype.start=function(){this.stopped=!1;this.removalFailures=0;this.flush()};x.prototype.stop=function(){this.stopped=!0;if(this.timeoutID)clearTimeout(this.timeoutID),this.timeoutID=null};x.prototype.clear=function(){this.queue.clear()};x.prototype.resetBatchSize=function(){this.batchSize=this.libConfig.batch_size};x.prototype.resetFlush=function(){this.scheduleFlush(this.libConfig.batch_flush_interval_ms)};x.prototype.scheduleFlush=
+function(a){this.flushInterval=a;if(!this.stopped)this.timeoutID=setTimeout(c.bind(this.flush,this),this.flushInterval)};x.prototype.flush=function(a){try{if(this.requestInProgress)w.log("Flush: Request already in progress");else{var a=a||{},b=this.batchSize,d=this.queue.fillBatch(b);w.log("current batch size is "+d.length);if(1>d.length)this.resetFlush();else{this.requestInProgress=!0;var f=this.libConfig.batch_request_timeout_ms,g=(new Date).getTime(),e=c.map(d,function(a){return a.payload}),i=
+c.bind(function(a){this.requestInProgress=!1;try{var e=!1;if(c.isObject(a)&&"timeout"===a.error&&(new Date).getTime()-g>=f)w.error("Network timeout; retrying"),this.flush();else if(c.isObject(a)&&a.xhr_req&&(500<=a.xhr_req.status||0>=a.xhr_req.status)){var h=2*this.flushInterval,i=a.xhr_req.responseHeaders;if(i){var j=i["Retry-After"];j&&(h=1E3*parseInt(j,10)||h)}h=Math.min(6E5,h);w.error("Error; retry in "+h+" ms");this.scheduleFlush(h)}else if(c.isObject(a)&&a.xhr_req&&413===a.xhr_req.status)if(1<
+d.length){var k=Math.max(1,Math.floor(b/2));this.batchSize=Math.min(this.batchSize,k,d.length-1);w.error("413 response; reducing batch size to "+this.batchSize);this.resetFlush()}else w.error("Single-event request too large; dropping",d),this.resetBatchSize(),e=!0;else e=!0;e&&this.queue.removeItemsByID(c.map(d,function(a){return a.id}),c.bind(function(a){a?(this.removalFailures=0,this.flush()):(this.removalFailures+=1,w.error("failed to remove items from batched queue "+this.removalFailures+" times."),
+5