From 2e0e81b63a67a75e4d097b607d9f4a3857a54acf Mon Sep 17 00:00:00 2001 From: Krishna Rajendran Date: Thu, 18 Jan 2018 13:40:46 -0800 Subject: [PATCH] Namespace local storage keys with api key (#132) * Namespace local storage keys with api key Some weird sites(eg optimizely's visual editor) pollute local storage by acting as a proxy to other sites. These changes should prevent different domains from contaminating each other. --- amplitude.js | 94 ++++++++++++++++++++++++++++----------- amplitude.min.js | 2 +- karma.conf.js | 3 ++ package.json | 1 + rollup.test.js | 1 + src/amplitude-client.js | 95 +++++++++++++++++++++++++++++----------- test/amplitude-client.js | 68 ++++++++++++++-------------- test/amplitude.js | 81 ++++++++++++++++++++++------------ yarn.lock | 6 +++ 9 files changed, 239 insertions(+), 112 deletions(-) diff --git a/amplitude.js b/amplitude.js index 89706bf3..334b9ba9 100644 --- a/amplitude.js +++ b/amplitude.js @@ -5673,7 +5673,7 @@ var DEFAULT_OPTIONS = { */ var AmplitudeClient = function AmplitudeClient(instanceName) { this._instanceName = utils.isEmptyString(instanceName) ? constants.DEFAULT_INSTANCE : instanceName.toLowerCase(); - this._storageSuffix = this._instanceName === constants.DEFAULT_INSTANCE ? '' : '_' + this._instanceName; + this._legacyStorageSuffix = this._instanceName === constants.DEFAULT_INSTANCE ? '' : '_' + this._instanceName; this._unsentEvents = []; this._unsentIdentifys = []; this._ua = new uaParser(navigator.userAgent).getResult(); @@ -5716,6 +5716,7 @@ AmplitudeClient.prototype.init = function init(apiKey, opt_userId, opt_config, o try { this.options.apiKey = apiKey; + this._storageSuffix = '_' + apiKey + this._legacyStorageSuffix; _parseConfig(this.options, opt_config); this.cookieStorage.options({ expirationDays: this.options.cookieExpiration, @@ -5864,6 +5865,29 @@ AmplitudeClient.prototype._apiKeySet = function _apiKeySet(methodName) { */ AmplitudeClient.prototype._loadSavedUnsentEvents = function _loadSavedUnsentEvents(unsentKey) { var savedUnsentEventsString = this._getFromStorage(localStorage$1, unsentKey); + var events = this._parseSavedUnsentEventsString(savedUnsentEventsString, unsentKey); + + var savedUnsentEventsStringLegacy = this._getFromStorageLegacy(localStorage$1, unsentKey); + var legacyEvents = this._parseSavedUnsentEventsString(savedUnsentEventsStringLegacy, unsentKey); + + var unsentEvents = legacyEvents.concat(events); + + // Migrate legacy events out of storage + this._removeFromLegacyStorage(localStorage$1, unsentKey); + this._setInStorage(localStorage$1, unsentKey, JSON.stringify(unsentEvents)); + + return unsentEvents; +}; + +AmplitudeClient.prototype._removeFromLegacyStorage = function _removeFromLegacyStorage(storage, key) { + storage.removeItem(key + this._legacyStorageSuffix); +}; + +/** + * Load saved events from localStorage. JSON deserializes event array. Handles case where string is corrupted. + * @private + */ +AmplitudeClient.prototype._parseSavedUnsentEventsString = function _parseSavedUnsentEventsString(savedUnsentEventsString, unsentKey) { if (utils.isEmptyString(savedUnsentEventsString)) { return []; // new app, does not have any saved events } @@ -5977,6 +6001,15 @@ AmplitudeClient.prototype._getFromStorage = function _getFromStorage(storage, ke return storage.getItem(key + this._storageSuffix); }; +/** + * Helper function to fetch values from storage + * Storage argument allows for localStoraoge and sessionStoraoge + * @private + */ +AmplitudeClient.prototype._getFromStorageLegacy = function _getFromStorageLegacy(storage, key) { + return storage.getItem(key + this._legacyStorageSuffix); +}; + /** * Helper function to set values in storage * Storage argument allows for localStoraoge and sessionStoraoge @@ -5994,7 +6027,7 @@ AmplitudeClient.prototype._setInStorage = function _setInStorage(storage, key, v */ var _upgradeCookeData = function _upgradeCookeData(scope) { // skip if migration already happened - var cookieData = scope.cookieStorage.get(scope.options.cookieName); + var cookieData = scope.cookieStorage.get(scope.options.cookieName + scope._storageSuffix); if (type(cookieData) === 'object' && cookieData.deviceId && cookieData.sessionId && cookieData.lastEventTime) { return; } @@ -6047,34 +6080,45 @@ var _upgradeCookeData = function _upgradeCookeData(scope) { */ var _loadCookieData = function _loadCookieData(scope) { var cookieData = scope.cookieStorage.get(scope.options.cookieName + scope._storageSuffix); + if (type(cookieData) === 'object') { - if (cookieData.deviceId) { - scope.options.deviceId = cookieData.deviceId; - } - if (cookieData.userId) { - scope.options.userId = cookieData.userId; - } - if (cookieData.optOut !== null && cookieData.optOut !== undefined) { - scope.options.optOut = cookieData.optOut; - } - if (cookieData.sessionId) { - scope._sessionId = parseInt(cookieData.sessionId); - } - if (cookieData.lastEventTime) { - scope._lastEventTime = parseInt(cookieData.lastEventTime); - } - if (cookieData.eventId) { - scope._eventId = parseInt(cookieData.eventId); - } - if (cookieData.identifyId) { - scope._identifyId = parseInt(cookieData.identifyId); - } - if (cookieData.sequenceNumber) { - scope._sequenceNumber = parseInt(cookieData.sequenceNumber); + _loadCookieDataProps(scope, cookieData); + } else { + var legacyCookieData = scope.cookieStorage.get(scope.options.cookieName + scope._legacyStorageSuffix); + if (type(legacyCookieData) === 'object') { + scope.cookieStorage.remove(scope.options.cookieName + scope._legacyStorageSuffix); + _loadCookieDataProps(scope, legacyCookieData); } } }; +var _loadCookieDataProps = function _loadCookieDataProps(scope, cookieData) { + if (cookieData.deviceId) { + scope.options.deviceId = cookieData.deviceId; + } + if (cookieData.userId) { + scope.options.userId = cookieData.userId; + } + if (cookieData.optOut !== null && cookieData.optOut !== undefined) { + scope.options.optOut = cookieData.optOut; + } + if (cookieData.sessionId) { + scope._sessionId = parseInt(cookieData.sessionId); + } + if (cookieData.lastEventTime) { + scope._lastEventTime = parseInt(cookieData.lastEventTime); + } + if (cookieData.eventId) { + scope._eventId = parseInt(cookieData.eventId); + } + if (cookieData.identifyId) { + scope._identifyId = parseInt(cookieData.identifyId); + } + if (cookieData.sequenceNumber) { + scope._sequenceNumber = parseInt(cookieData.sequenceNumber); + } +}; + /** * Saves deviceId, userId, event meta data to amplitude cookie * @private diff --git a/amplitude.min.js b/amplitude.min.js index c2107d7f..20712a59 100644 --- a/amplitude.min.js +++ b/amplitude.min.js @@ -1 +1 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.amplitude=t()}(this,function(){"use strict";function e(e,t){return t={exports:{}},e(t,t.exports),t.exports}function t(e,t,n){if(!(e0&&u>a&&(u=a);for(var c=0;c=0?(p=h.substr(0,g),l=h.substr(g+1)):(p=h,l=""),d=decodeURIComponent(p),f=decodeURIComponent(l),i(o,d)?jt(o[d])?o[d].push(f):o[d]=[o[d],f]:o[d]=f}return o}var p,l="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},d=(e(function(e,t){(function(){function n(e,t){function o(e){if(o[e]!==v)return o[e];var n;if("bug-string-char-index"==e)n="a"!="a"[0];else if("json"==e)n=o("json-stringify")&&o("json-parse");else{var r,i='{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';if("json-stringify"==e){var u=t.stringify,p="function"==typeof u&&_;if(p){(r=function(){return 1}).toJSON=r;try{p="0"===u(0)&&"0"===u(new s)&&'""'==u(new a)&&u(m)===v&&u(v)===v&&u()===v&&"1"===u(r)&&"[1]"==u([r])&&"[null]"==u([v])&&"null"==u(null)&&"[null,null,null]"==u([v,m,null])&&u({a:[r,!0,!1,null,"\0\b\n\f\r\t"]})==i&&"1"===u(null,r)&&"[\n 1,\n 2\n]"==u([1,2],null,1)&&'"-271821-04-20T00:00:00.000Z"'==u(new c(-864e13))&&'"+275760-09-13T00:00:00.000Z"'==u(new c(864e13))&&'"-000001-01-01T00:00:00.000Z"'==u(new c(-621987552e5))&&'"1969-12-31T23:59:59.999Z"'==u(new c(-1))}catch(e){p=!1}}n=p}if("json-parse"==e){var l=t.parse;if("function"==typeof l)try{if(0===l("0")&&!l(!1)){var d=5==(r=l(i)).a.length&&1===r.a[0];if(d){try{d=!l('"\t"')}catch(e){}if(d)try{d=1!==l("01")}catch(e){}if(d)try{d=1!==l("1.")}catch(e){}}}}catch(e){d=!1}n=d}}return o[e]=!!n}e||(e=i.Object()),t||(t=i.Object());var s=e.Number||i.Number,a=e.String||i.String,u=e.Object||i.Object,c=e.Date||i.Date,p=e.SyntaxError||i.SyntaxError,l=e.TypeError||i.TypeError,d=e.Math||i.Math,f=e.JSON||i.JSON;"object"==typeof f&&f&&(t.stringify=f.stringify,t.parse=f.parse);var h,g,v,y=u.prototype,m=y.toString,_=new c(-0xc782b5b800cec);try{_=-109252==_.getUTCFullYear()&&0===_.getUTCMonth()&&1===_.getUTCDate()&&10==_.getUTCHours()&&37==_.getUTCMinutes()&&6==_.getUTCSeconds()&&708==_.getUTCMilliseconds()}catch(e){}if(!o("json")){var b=o("bug-string-char-index");if(!_)var w=d.floor,I=[0,31,59,90,120,151,181,212,243,273,304,334],E=function(e,t){return I[t]+365*(e-1970)+w((e-1969+(t=+(t>1)))/4)-w((e-1901+t)/100)+w((e-1601+t)/400)};if((h=y.hasOwnProperty)||(h=function(e){var t,n={};return(n.__proto__=null,n.__proto__={toString:1},n).toString!=m?h=function(e){var t=this.__proto__,n=e in(this.__proto__=null,this);return this.__proto__=t,n}:(t=n.constructor,h=function(e){var n=(this.constructor||t).prototype;return e in this&&!(e in n&&this[e]===n[e])}),n=null,h.call(this,e)}),g=function(e,t){var n,o,i,s=0;(n=function(){this.valueOf=0}).prototype.valueOf=0,o=new n;for(i in o)h.call(o,i)&&s++;return n=o=null,s?g=2==s?function(e,t){var n,r={},o="[object Function]"==m.call(e);for(n in e)o&&"prototype"==n||h.call(r,n)||!(r[n]=1)||!h.call(e,n)||t(n)}:function(e,t){var n,r,o="[object Function]"==m.call(e);for(n in e)o&&"prototype"==n||!h.call(e,n)||(r="constructor"===n)||t(n);(r||h.call(e,n="constructor"))&&t(n)}:(o=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"],g=function(e,t){var n,i,s="[object Function]"==m.call(e),a=!s&&"function"!=typeof e.constructor&&r[typeof e.hasOwnProperty]&&e.hasOwnProperty||h;for(n in e)s&&"prototype"==n||!a.call(e,n)||t(n);for(i=o.length;n=o[--i];a.call(e,n)&&t(n));}),g(e,t)},!o("json-stringify")){var S={92:"\\\\",34:'\\"',8:"\\b",12:"\\f",10:"\\n",13:"\\r",9:"\\t"},C=function(e,t){return("000000"+(t||0)).slice(-e)},O=function(e){for(var t='"',n=0,r=e.length,o=!b||r>10,i=o&&(b?e.split(""):e);n-1/0&&a<1/0){if(E){for(d=w(a/864e5),c=w(d/365.2425)+1970-1;E(c+1,0)<=d;c++);for(p=w((d-E(c,0))/30.42);E(c,p+1)<=d;p++);d=1+d-E(c,p),y=w((f=(a%864e5+864e5)%864e5)/36e5)%24,_=w(f/6e4)%60,b=w(f/1e3)%60,I=f%1e3}else c=a.getUTCFullYear(),p=a.getUTCMonth(),d=a.getUTCDate(),y=a.getUTCHours(),_=a.getUTCMinutes(),b=a.getUTCSeconds(),I=a.getUTCMilliseconds();a=(c<=0||c>=1e4?(c<0?"-":"+")+C(6,c<0?-c:c):C(4,c))+"-"+C(2,p+1)+"-"+C(2,d)+"T"+C(2,y)+":"+C(2,_)+":"+C(2,b)+"."+C(3,I)+"Z"}else a=null;if(n&&(a=n.call(t,e,a)),null===a)return"null";if("[object Boolean]"==(u=m.call(a)))return""+a;if("[object Number]"==u)return a>-1/0&&a<1/0?""+a:"null";if("[object String]"==u)return O(""+a);if("object"==typeof a){for(x=s.length;x--;)if(s[x]===a)throw l();if(s.push(a),S=[],j=i,i+=o,"[object Array]"==u){for(T=0,x=a.length;T0)for(o="",n>10&&(n=10);o.length=48&&o<=57||o>=97&&o<=102||o>=65&&o<=70||R();e+=x("0x"+i.slice(t,A));break;default:R()}else{if(34==o)break;for(o=i.charCodeAt(A),t=A;o>=32&&92!=o&&34!=o;)o=i.charCodeAt(++A);e+=i.slice(t,A)}if(34==i.charCodeAt(A))return A++,e;R();default:if(t=A,45==o&&(r=!0,o=i.charCodeAt(++A)),o>=48&&o<=57){for(48==o&&(o=i.charCodeAt(A+1))>=48&&o<=57&&R(),r=!1;A=48&&o<=57;A++);if(46==i.charCodeAt(A)){for(n=++A;n=48&&o<=57;n++);n==A&&R(),A=n}if(101==(o=i.charCodeAt(A))||69==o){for(43!=(o=i.charCodeAt(++A))&&45!=o||A++,n=A;n=48&&o<=57;n++);n==A&&R(),A=n}return+i.slice(t,A)}if(r&&R(),"true"==i.slice(A,A+4))return A+=4,!0;if("false"==i.slice(A,A+5))return A+=5,!1;if("null"==i.slice(A,A+4))return A+=4,null;R()}return"$"},k=function(e){var t,n;if("$"==e&&R(),"string"==typeof e){if("@"==(b?e.charAt(0):e[0]))return e.slice(1);if("["==e){for(t=[];"]"!=(e=P());n||(n=!0))n&&(","==e?"]"==(e=P())&&R():R()),","==e&&R(),t.push(k(e));return t}if("{"==e){for(t={};"}"!=(e=P());n||(n=!0))n&&(","==e?"}"==(e=P())&&R():R()),","!=e&&"string"==typeof e&&"@"==(b?e.charAt(0):e[0])&&":"==P()||R(),t[e.slice(1)]=k(P());return t}R()}return e},F=function(e,t,n){var r=U(e,t,n);r===v?delete e[t]:e[t]=r},U=function(e,t,n){var r,o=e[t];if("object"==typeof o&&o)if("[object Array]"==m.call(o))for(r=o.length;r--;)F(o,r,n);else g(o,function(e){F(o,e,n)});return n.call(e,t,o)};t.parse=function(e,t){var n,r;return A=0,T=""+e,n=k(P()),"$"!=P()&&R(),A=T=null,t&&"[object Function]"==m.call(t)?U((r={},r[""]=n,r),"",t):n}}}return t.runInContext=n,t}var r={function:!0,object:!0},o=r.object&&t&&!t.nodeType&&t,i=r[typeof window]&&window||this,s=o&&r.object&&e&&!e.nodeType&&"object"==typeof l&&l;if(!s||s.global!==s&&s.window!==s&&s.self!==s||(i=s),o)n(i,o);else{var a=i.JSON,u=i.JSON3,c=!1,p=n(i,i.JSON3={noConflict:function(){return c||(c=!0,i.JSON=a,i.JSON3=u,a=u=null),p}});i.JSON={parse:p.parse,stringify:p.stringify}}}).call(l)}),{DEFAULT_INSTANCE:"$default_instance",API_VERSION:2,MAX_STRING_LENGTH:4096,MAX_PROPERTY_KEYS:1e3,IDENTIFY_EVENT:"$identify",LAST_EVENT_ID:"amplitude_lastEventId",LAST_EVENT_TIME:"amplitude_lastEventTime",LAST_IDENTIFY_ID:"amplitude_lastIdentifyId",LAST_SEQUENCE_NUMBER:"amplitude_lastSequenceNumber",SESSION_ID:"amplitude_sessionId",DEVICE_ID:"amplitude_deviceId",OPT_OUT:"amplitude_optOut",USER_ID:"amplitude_userId",COOKIE_TEST:"amplitude_cookie_test",REVENUE_EVENT:"revenue_amount",REVENUE_PRODUCT_ID:"$productId",REVENUE_QUANTITY:"$quantity",REVENUE_PRICE:"$price",REVENUE_REVENUE_TYPE:"$revenueType",AMP_DEVICE_ID_PARAM:"amp_device_id"}),f={encode:function(e){for(var t="",n=0;n127&&r<2048?(t+=String.fromCharCode(r>>6|192),t+=String.fromCharCode(63&r|128)):(t+=String.fromCharCode(r>>12|224),t+=String.fromCharCode(r>>6&63|128),t+=String.fromCharCode(63&r|128))}return t},decode:function(e){for(var t="",n=0,r=0,o=0,i=0;n191&&r<224?(o=e.charCodeAt(n+1),t+=String.fromCharCode((31&r)<<6|63&o),n+=2):(o=e.charCodeAt(n+1),i=e.charCodeAt(n+2),t+=String.fromCharCode((15&r)<<12|(63&o)<<6|63&i),n+=3);return t}},h={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){try{if(window.btoa&&window.atob)return window.btoa(unescape(encodeURIComponent(e)))}catch(e){}return h._encode(e)},_encode:function(e){var t,n,r,o,i,s,a,u="",c=0;for(e=f.encode(e);c>2,i=(3&t)<<4|(n=e.charCodeAt(c++))>>4,s=(15&n)<<2|(r=e.charCodeAt(c++))>>6,a=63&r,isNaN(n)?s=a=64:isNaN(r)&&(a=64),u=u+h._keyStr.charAt(o)+h._keyStr.charAt(i)+h._keyStr.charAt(s)+h._keyStr.charAt(a);return u},decode:function(e){try{if(window.btoa&&window.atob)return decodeURIComponent(escape(window.atob(e)))}catch(e){}return h._decode(e)},_decode:function(e){var t,n,r,o,i,s,a="",u=0;for(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");u>4,n=(15&o)<<4|(i=h._keyStr.indexOf(e.charAt(u++)))>>2,r=(3&i)<<6|(s=h._keyStr.indexOf(e.charAt(u++))),a+=String.fromCharCode(t),64!==i&&(a+=String.fromCharCode(n)),64!==s&&(a+=String.fromCharCode(r));return a=f.decode(a)}},g=e(function(e,t){t.parse=function(e){var t=document.createElement("a");return t.href=e,{href:t.href,host:t.host||location.host,port:"0"===t.port||""===t.port?function(e){switch(e){case"http:":return 80;case"https:":return 443;default:return location.port}}(t.protocol):t.port,hash:t.hash,hostname:t.hostname||location.hostname,pathname:"/"!=t.pathname.charAt(0)?"/"+t.pathname:t.pathname,protocol:t.protocol&&":"!=t.protocol?t.protocol:location.protocol,search:t.search,query:t.search.slice(1)}},t.isAbsolute=function(e){return 0==e.indexOf("//")||!!~e.indexOf("://")},t.isRelative=function(e){return!t.isAbsolute(e)},t.isCrossDomain=function(e){e=t.parse(e);var n=t.parse(window.location.href);return e.hostname!==n.hostname||e.port!==n.port||e.protocol!==n.protocol}}),v=1e3,y=60*v,m=60*y,_=24*m,b=365.25*_,w=function(e,n){n=n||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*b;case"days":case"day":case"d":return n*_;case"hours":case"hour":case"hrs":case"hr":case"h":return n*m;case"minutes":case"minute":case"mins":case"min":case"m":return n*y;case"seconds":case"second":case"secs":case"sec":case"s":return n*v;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}(e);if("number"===r&&!1===isNaN(e))return n.long?function(e){return t(e,_,"day")||t(e,m,"hour")||t(e,y,"minute")||t(e,v,"second")||e+" ms"}(e):function(e){return e>=_?Math.round(e/_)+"d":e>=m?Math.round(e/m)+"h":e>=y?Math.round(e/y)+"m":e>=v?Math.round(e/v)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))},I=e(function(e,t){function n(e){function n(){if(n.enabled){var e=n,r=+new Date,i=r-(o||r);e.diff=i,e.prev=o,e.curr=r,o=r;for(var s=new Array(arguments.length),a=0;a=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())})("cookie"),S=function(e,t,o){switch(arguments.length){case 3:case 2:return function(e,t,n){n=n||{};var o=r(e)+"="+r(t);null==t&&(n.maxage=-1),n.maxage&&(n.expires=new Date(+new Date+n.maxage)),n.path&&(o+="; path="+n.path),n.domain&&(o+="; domain="+n.domain),n.expires&&(o+="; expires="+n.expires.toUTCString()),n.secure&&(o+="; secure"),document.cookie=o}(e,t,o);case 1:return function(e){return n()[e]}(e);default:return n()}},C=e(function(e,t){function n(e){for(var n=t.cookie,r=t.levels(e),o=0;o=0;--i)o.push(t.slice(i).join("."));return o},n.cookie=S,t=e.exports=n}),O="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},N=Object.prototype.toString,A=function(e){switch(N.call(e)){case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object Error]":return"error"}return null===e?"null":void 0===e?"undefined":e!=e?"nan":e&&1===e.nodeType?"element":"undefined"!=typeof Buffer&&Buffer.isBuffer(e)?"buffer":void 0===(e=e.valueOf?e.valueOf():Object.prototype.valueOf.apply(e))?"undefined":O(e)},T="WARN",x={DISABLE:0,ERROR:1,WARN:2,INFO:3},j={error:function(e){T>=x.ERROR&&R(e)},warn:function(e){T>=x.WARN&&R(e)},info:function(e){T>=x.INFO&&R(e)}},R=function(e){try{console.log("[Amplitude] "+e)}catch(e){}},P=function(e){return"string"===A(e)&&e.length>d.MAX_STRING_LENGTH?e.substring(0,d.MAX_STRING_LENGTH):e},k=function(e){var t=A(e);if("object"!==t)return j.error("Error: invalid properties format. Expecting Javascript object, received "+t+", ignoring"),{};if(Object.keys(e).length>d.MAX_PROPERTY_KEYS)return j.error("Error: too many properties (more than 1000), ignoring"),{};var n={};for(var r in e)if(e.hasOwnProperty(r)){var o=r,i=A(o);"string"!==i&&(o=String(o),j.warn("WARNING: Non-string property key, received type "+i+', coercing to string "'+o+'"'));var s=U(o,e[r]);null!==s&&(n[o]=s)}return n},F=["null","nan","undefined","function","arguments","regexp","element"],U=function e(t,n){var r=A(n);if(-1!==F.indexOf(r))j.warn('WARNING: Property key "'+t+'" with invalid value type '+r+", ignoring"),n=null;else if("error"===r)n=String(n),j.warn('WARNING: Property key "'+t+'" with value type error, coercing to '+n);else if("array"===r){for(var o=[],i=0;i0?(this.userPropertiesOperations.hasOwnProperty("$clearAll")||M.log.error("Need to send $clearAll on its own Identify object without any other operations, skipping $clearAll"),this):(this.userPropertiesOperations.$clearAll="-",this)},Q.prototype.prepend=function(e,t){return this._addOperation("$prepend",e,t),this},Q.prototype.set=function(e,t){return this._addOperation("$set",e,t),this},Q.prototype.setOnce=function(e,t){return this._addOperation("$setOnce",e,t),this},Q.prototype.unset=function(e){return this._addOperation("$unset",e,"-"),this},Q.prototype._addOperation=function(e,t,n){this.userPropertiesOperations.hasOwnProperty("$clearAll")?M.log.error("This identify already contains a $clearAll operation, skipping operation "+e):-1===this.properties.indexOf(t)?(this.userPropertiesOperations.hasOwnProperty(e)||(this.userPropertiesOperations[e]={}),this.userPropertiesOperations[e][t]=n,this.properties.push(t)):M.log.error('User property "'+t+'" already used in this identify, skipping operation '+e)};var X=e(function(e){!function(t){function n(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function r(e,t,r,o,i,s){return n(function(e,t){return e<>>32-t}(n(n(t,e),n(o,s)),i),r)}function o(e,t,n,o,i,s,a){return r(t&n|~t&o,e,t,i,s,a)}function i(e,t,n,o,i,s,a){return r(t&o|n&~o,e,t,i,s,a)}function s(e,t,n,o,i,s,a){return r(t^n^o,e,t,i,s,a)}function a(e,t,n,o,i,s,a){return r(n^(t|~o),e,t,i,s,a)}function u(e,t){e[t>>5]|=128<>>9<<4)]=t;var r,u,c,p,l,d=1732584193,f=-271733879,h=-1732584194,g=271733878;for(r=0;r>5]>>>t%32&255);return n}function p(e){var t,n=[];for(n[(e.length>>2)-1]=void 0,t=0;t>5]|=(255&e.charCodeAt(t/8))<>>4&15)+"0123456789abcdef".charAt(15&t);return r}function d(e){return unescape(encodeURIComponent(e))}function f(e){return function(e){return c(u(p(e),8*e.length))}(d(e))}function h(e,t){return function(e,t){var n,r,o=p(e),i=[],s=[];for(i[15]=s[15]=void 0,o.length>16&&(o=u(o,8*e.length)),n=0;n<16;n+=1)i[n]=909522486^o[n],s[n]=1549556828^o[n];return r=u(i.concat(p(t)),512+8*t.length),c(u(s.concat(r),640))}(d(e),d(t))}function g(e,t,n){return t?n?h(t,e):function(e,t){return l(h(e,t))}(t,e):n?f(e):function(e){return l(f(e))}(e)}e.exports?e.exports=g:t.md5=g}(l)}),H="object"==typeof l&&l&&l.Object===Object&&l,Z="object"==typeof self&&self&&self.Object===Object&&self,ee=H||Z||Function("return this")(),te=ee.Symbol,ne=Object.prototype,re=ne.hasOwnProperty,oe=ne.toString,ie=te?te.toStringTag:void 0,se=function(e){var t=re.call(e,ie),n=e[ie];try{e[ie]=void 0;var r=!0}catch(e){}var o=oe.call(e);return r&&(t?e[ie]=n:delete e[ie]),o},ae=Object.prototype.toString,ue=function(e){return ae.call(e)},ce="[object Null]",pe="[object Undefined]",le=te?te.toStringTag:void 0,de=function(e){return null==e?void 0===e?pe:ce:le&&le in Object(e)?se(e):ue(e)},fe=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},he="[object AsyncFunction]",ge="[object Function]",ve="[object GeneratorFunction]",ye="[object Proxy]",me=function(e){if(!fe(e))return!1;var t=de(e);return t==ge||t==ve||t==he||t==ye},_e=ee["__core-js_shared__"],be=function(){var e=/[^.]+$/.exec(_e&&_e.keys&&_e.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),we=function(e){return!!be&&be in e},Ie=Function.prototype.toString,Ee=function(e){if(null!=e){try{return Ie.call(e)}catch(e){}try{return e+""}catch(e){}}return""},Se=/^\[object .+?Constructor\]$/,Ce=Function.prototype,Oe=Object.prototype,Ne=Ce.toString,Ae=Oe.hasOwnProperty,Te=RegExp("^"+Ne.call(Ae).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),xe=function(e){return!(!fe(e)||we(e))&&(me(e)?Te:Se).test(Ee(e))},je=function(e,t){return null==e?void 0:e[t]},Re=function(e,t){var n=je(e,t);return xe(n)?n:void 0},Pe=function(){try{var e=Re(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),ke=function(e,t,n){"__proto__"==t&&Pe?Pe(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n},Fe=function(e,t){return e===t||e!=e&&t!=t},Ue=Object.prototype.hasOwnProperty,De=function(e,t,n){var r=e[t];Ue.call(e,t)&&Fe(r,n)&&(void 0!==n||t in e)||ke(e,t,n)},Me=function(e,t,n,r){var o=!n;n||(n={});for(var i=-1,s=t.length;++i0){if(++t>=ze)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}(Ke),Ye=function(e,t){return We(Ge(e,t,qe),e+"")},Qe=9007199254740991,Xe=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=Qe},He=function(e){return null!=e&&Xe(e.length)&&!me(e)},Ze=9007199254740991,et=/^(?:0|[1-9]\d*)$/,tt=function(e,t){return!!(t=null==t?Ze:t)&&("number"==typeof e||et.test(e))&&e>-1&&e%1==0&&e1?n[o-1]:void 0,s=o>2?n[2]:void 0;for(i=e.length>3&&"function"==typeof i?(o--,i):void 0,s&&nt(n[0],n[1],s)&&(i=o<3?void 0:i,o=1),t=Object(t);++r0?2==o.length?"function"==typeof o[1]?e[o[0]]=o[1].call(this,s):e[o[0]]=o[1]:3==o.length?"function"!=typeof o[1]||o[1].exec&&o[1].test?e[o[0]]=s?s.replace(o[1],o[2]):void 0:e[o[0]]=s?o[1].call(this,s,o[2]):void 0:4==o.length&&(e[o[0]]=s?o[3].call(this,s.replace(o[1],o[2])):void 0):e[o]=s||void 0;a+=2}return e},str:function(e,t){for(var n in t)if("object"==typeof t[n]&&t[n].length>0){for(var r=0;r>t/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,e)},Mt={apiEndpoint:"api.amplitude.com",cookieExpiration:3650,cookieName:"amplitude_id",domain:"",includeReferrer:!1,includeUtm:!1,language:{language:navigator&&(navigator.languages&&navigator.languages[0]||navigator.language||navigator.userLanguage)||void 0}.language,logLevel:"WARN",optOut:!1,platform:"Web",savedMaxCount:1e3,saveEvents:!0,sessionTimeout:18e5,unsentKey:"amplitude_unsent",unsentIdentifyKey:"amplitude_unsent_identify",uploadBatchSize:100,batchEvents:!1,eventUploadThreshold:30,eventUploadPeriodMillis:3e4,forceHttps:!0,includeGclid:!1,saveParamsReferrerOncePerSession:!0,deviceIdFromUrlParam:!1},qt=function(e){this._instanceName=M.isEmptyString(e)?d.DEFAULT_INSTANCE:e.toLowerCase(),this._storageSuffix=this._instanceName===d.DEFAULT_INSTANCE?"":"_"+this._instanceName,this._unsentEvents=[],this._unsentIdentifys=[],this._ua=new Ut(navigator.userAgent).getResult(),this.options=xt({},Mt),this.cookieStorage=(new Y).getStorage(),this._q=[],this._sending=!1,this._updateScheduled=!1,this._eventId=0,this._identifyId=0,this._lastEventTime=null,this._newSession=!1,this._sequenceNumber=0,this._sessionId=null,this._userAgent=navigator&&navigator.userAgent||null};qt.prototype.Identify=Q,qt.prototype.Revenue=Ft,qt.prototype.init=function(e,t,n,r){if("string"!==A(e)||M.isEmptyString(e))M.log.error("Invalid apiKey. Please re-initialize with a valid apiKey");else try{if(this.options.apiKey=e,Vt(this.options,n),this.cookieStorage.options({expirationDays:this.options.cookieExpiration,domain:this.options.domain}),this.options.domain=this.cookieStorage.options().domain,this._instanceName===d.DEFAULT_INSTANCE&&Lt(this),Gt(this),this.options.deviceId="object"===A(n)&&"string"===A(n.deviceId)&&!M.isEmptyString(n.deviceId)&&n.deviceId||this.options.deviceIdFromUrlParam&&this._getDeviceIdFromUrlParam(this._getUrlParams())||this.options.deviceId||Dt()+"R",this.options.userId="string"===A(t)&&!M.isEmptyString(t)&&t||"number"===A(t)&&t.toString()||this.options.userId||null,this.options.saveEvents){this._unsentEvents=this._loadSavedUnsentEvents(this.options.unsentKey),this._unsentIdentifys=this._loadSavedUnsentEvents(this.options.unsentIdentifyKey);for(var o=0;othis.options.sessionTimeout)&&(this._newSession=!0,this._sessionId=p,this.options.saveParamsReferrerOncePerSession&&this._trackParamsAndReferrer()),this.options.saveParamsReferrerOncePerSession||this._trackParamsAndReferrer(),this._lastEventTime=p,Bt(this),this._sendEventsIfReady()}catch(e){M.log.error(e)}finally{"function"===A(r)&&r(this)}},qt.prototype._trackParamsAndReferrer=function(){this.options.includeUtm&&this._initUtmData(),this.options.includeReferrer&&this._saveReferrer(this._getReferrer()),this.options.includeGclid&&this._saveGclid(this._getUrlParams())};var Vt=function(e,t){if("object"===A(t)){var n=function(n){if(Mt.hasOwnProperty(n)){var r=t[n],o=A(Mt[n]);M.validateInput(r,n+" option",o)&&("boolean"===o?e[n]=!!r:("string"===o&&!M.isEmptyString(r)||"number"===o&&r>0)&&(e[n]=r))}};for(var r in t)t.hasOwnProperty(r)&&n(r)}};qt.prototype.runQueuedFunctions=function(){for(var e=0;e=this.options.eventUploadThreshold?(this.sendEvents(e),!0):(this._updateScheduled||(this._updateScheduled=!0,setTimeout(function(){this._updateScheduled=!1,this.sendEvents()}.bind(this),this.options.eventUploadPeriodMillis)),!1):(this.sendEvents(e),!0))},qt.prototype._getFromStorage=function(e,t){return e.getItem(t+this._storageSuffix)},qt.prototype._setInStorage=function(e,t,n){e.setItem(t+this._storageSuffix,n)};var Lt=function(e){var t=e.cookieStorage.get(e.options.cookieName);if(!("object"===A(t)&&t.deviceId&&t.sessionId&&t.lastEventTime)){var n=function(e){var t=W.getItem(e);return W.removeItem(e),t},r="string"===A(e.options.apiKey)&&"_"+e.options.apiKey.slice(0,6)||"",o=n(d.DEVICE_ID+r),i=n(d.USER_ID+r),s=n(d.OPT_OUT+r);null!==s&&void 0!==s&&(s="true"===String(s));var a=parseInt(n(d.SESSION_ID)),u=parseInt(n(d.LAST_EVENT_TIME)),c=parseInt(n(d.LAST_EVENT_ID)),p=parseInt(n(d.LAST_IDENTIFY_ID)),l=parseInt(n(d.LAST_SEQUENCE_NUMBER)),f=function(e){return"object"===A(t)&&t[e]};e.options.deviceId=f("deviceId")||o,e.options.userId=f("userId")||i,e._sessionId=f("sessionId")||a||e._sessionId,e._lastEventTime=f("lastEventTime")||u||e._lastEventTime,e._eventId=f("eventId")||c||e._eventId,e._identifyId=f("identifyId")||p||e._identifyId,e._sequenceNumber=f("sequenceNumber")||l||e._sequenceNumber,e.options.optOut=s||!1,t&&void 0!==t.optOut&&null!==t.optOut&&(e.options.optOut="true"===String(t.optOut)),Bt(e)}},Gt=function(e){var t=e.cookieStorage.get(e.options.cookieName+e._storageSuffix);"object"===A(t)&&(t.deviceId&&(e.options.deviceId=t.deviceId),t.userId&&(e.options.userId=t.userId),null!==t.optOut&&void 0!==t.optOut&&(e.options.optOut=t.optOut),t.sessionId&&(e._sessionId=parseInt(t.sessionId)),t.lastEventTime&&(e._lastEventTime=parseInt(t.lastEventTime)),t.eventId&&(e._eventId=parseInt(t.eventId)),t.identifyId&&(e._identifyId=parseInt(t.identifyId)),t.sequenceNumber&&(e._sequenceNumber=parseInt(t.sequenceNumber)))},Bt=function(e){e.cookieStorage.set(e.options.cookieName+e._storageSuffix,{deviceId:e.options.deviceId,userId:e.options.userId,optOut:e.options.optOut,sessionId:e._sessionId,lastEventTime:e._lastEventTime,eventId:e._eventId,identifyId:e._identifyId,sequenceNumber:e._sequenceNumber})};qt.prototype._initUtmData=function(e,t){e=e||this._getUrlParams();var n=function(e,t){var n=e?"?"+e.split(".").slice(-1)[0].replace(/\|/g,"&"):"",r=function(e,t,n,r){return M.getQueryParam(e,t)||M.getQueryParam(n,r)},o=r("utm_source",t,"utmcsr",n),i=r("utm_medium",t,"utmcmd",n),s=r("utm_campaign",t,"utmccn",n),a=r("utm_term",t,"utmctr",n),u=r("utm_content",t,"utmcct",n),c={},p=function(e,t){M.isEmptyString(t)||(c[e]=t)};return p("utm_source",o),p("utm_medium",i),p("utm_campaign",s),p("utm_term",a),p("utm_content",u),c}(t=t||this.cookieStorage.get("__utmz"),e);Kt(this,n)};var Kt=function(e,t){if("object"===A(t)&&0!==Object.keys(t).length){var n=new Q;for(var r in t)t.hasOwnProperty(r)&&(n.setOnce("initial_"+r,t[r]),n.set(r,t[r]));e.identify(n)}};qt.prototype._getReferrer=function(){return document.referrer},qt.prototype._getUrlParams=function(){return location.search},qt.prototype._saveGclid=function(e){var t=M.getQueryParam("gclid",e);if(!M.isEmptyString(t)){Kt(this,{gclid:t})}},qt.prototype._getDeviceIdFromUrlParam=function(e){return M.getQueryParam(d.AMP_DEVICE_ID_PARAM,e)},qt.prototype._getReferringDomain=function(e){if(M.isEmptyString(e))return null;var t=e.split("/");return t.length>=3?t[2]:null},qt.prototype._saveReferrer=function(e){if(!M.isEmptyString(e)){var t={referrer:e,referring_domain:this._getReferringDomain(e)};Kt(this,t)}},qt.prototype.saveEvents=function(){try{this._setInStorage(W,this.options.unsentKey,JSON.stringify(this._unsentEvents))}catch(e){}try{this._setInStorage(W,this.options.unsentIdentifyKey,JSON.stringify(this._unsentIdentifys))}catch(e){}},qt.prototype.setDomain=function(e){if(M.validateInput(e,"domain","string"))try{this.cookieStorage.options({domain:e}),this.options.domain=this.cookieStorage.options().domain,Gt(this),Bt(this)}catch(e){M.log.error(e)}},qt.prototype.setUserId=function(e){try{this.options.userId=void 0!==e&&null!==e&&""+e||null,Bt(this)}catch(e){M.log.error(e)}},qt.prototype.setGroup=function(e,t){if(this._apiKeySet("setGroup()")&&M.validateInput(e,"groupType","string")&&!M.isEmptyString(e)){var n={};n[e]=t;var r=(new Q).set(e,t);this._logEvent(d.IDENTIFY_EVENT,null,null,r.userPropertiesOperations,n,null,null)}},qt.prototype.setOptOut=function(e){if(M.validateInput(e,"enable","boolean"))try{this.options.optOut=e,Bt(this)}catch(e){M.log.error(e)}},qt.prototype.setSessionId=function(e){if(M.validateInput(e,"sessionId","number"))try{this._sessionId=e,Bt(this)}catch(e){M.log.error(e)}},qt.prototype.regenerateDeviceId=function(){this.setDeviceId(Dt()+"R")},qt.prototype.setDeviceId=function(e){if(M.validateInput(e,"deviceId","string"))try{M.isEmptyString(e)||(this.options.deviceId=""+e,Bt(this))}catch(e){M.log.error(e)}},qt.prototype.setUserProperties=function(e){if(this._apiKeySet("setUserProperties()")&&M.validateInput(e,"userProperties","object")){var t=M.truncate(M.validateProperties(e));if(0!==Object.keys(t).length){var n=new Q;for(var r in t)t.hasOwnProperty(r)&&n.set(r,t[r]);this.identify(n)}}},qt.prototype.clearUserProperties=function(){if(this._apiKeySet("clearUserProperties()")){var e=new Q;e.clearAll(),this.identify(e)}};var zt=function(e,t){for(var n=0;n0)return this._logEvent(d.IDENTIFY_EVENT,null,null,e.userPropertiesOperations,null,null,t)}else M.log.error("Invalid identify input type. Expected Identify object but saw "+A(e));"function"===A(t)&&t(0,"No request sent")}else"function"===A(t)&&t(0,"No request sent")},qt.prototype.setVersionName=function(e){M.validateInput(e,"versionName","string")&&(this.options.versionName=e)},qt.prototype._logEvent=function(e,t,n,r,o,i,s){if(Gt(this),e&&!this.options.optOut)try{var a;a=e===d.IDENTIFY_EVENT?this.nextIdentifyId():this.nextEventId();var u=this.nextSequenceNumber(),c="number"===A(i)?i:(new Date).getTime();(!this._sessionId||!this._lastEventTime||c-this._lastEventTime>this.options.sessionTimeout)&&(this._sessionId=c),this._lastEventTime=c,Bt(this),r=r||{},n=n||{},t=t||{},o=o||{};var p={device_id:this.options.deviceId,user_id:this.options.userId,timestamp:c,event_id:a,session_id:this._sessionId||-1,event_type:e,version_name:this.options.versionName||null,platform:this.options.platform,os_name:this._ua.browser.name||null,os_version:this._ua.browser.major||null,device_model:this._ua.os.name||null,language:this.options.language,api_properties:n,event_properties:M.truncate(M.validateProperties(t)),user_properties:M.truncate(M.validateProperties(r)),uuid:Dt(),library:{name:"amplitude-js",version:"4.0.0"},sequence_number:u,groups:M.truncate(M.validateGroups(o)),user_agent:this._userAgent};return e===d.IDENTIFY_EVENT?(this._unsentIdentifys.push(p),this._limitEventsQueued(this._unsentIdentifys)):(this._unsentEvents.push(p),this._limitEventsQueued(this._unsentEvents)),this.options.saveEvents&&this.saveEvents(),this._sendEventsIfReady(s)||"function"!==A(s)||s(0,"No request sent"),a}catch(e){M.log.error(e)}else"function"===A(s)&&s(0,"No request sent")},qt.prototype._limitEventsQueued=function(e){e.length>this.options.savedMaxCount&&e.splice(0,e.length-this.options.savedMaxCount)},qt.prototype.logEvent=function(e,t,n){return this.logEventWithTimestamp(e,t,null,n)},qt.prototype.logEventWithTimestamp=function(e,t,n,r){return this._apiKeySet("logEvent()")&&M.validateInput(e,"eventType","string")&&!M.isEmptyString(e)?this._logEvent(e,t,null,null,null,n,r):("function"===A(r)&&r(0,"No request sent"),-1)},qt.prototype.logEventWithGroups=function(e,t,n,r){return this._apiKeySet("logEventWithGroup()")&&M.validateInput(e,"eventType","string")?this._logEvent(e,t,null,null,n,null,r):("function"===A(r)&&r(0,"No request sent"),-1)};var $t=function(e){return!isNaN(parseFloat(e))&&isFinite(e)};qt.prototype.logRevenueV2=function(e){if(this._apiKeySet("logRevenueV2()"))if("object"===A(e)&&e.hasOwnProperty("_q")&&(e=zt(new Ft,e)),e instanceof Ft){if(e&&e._isValidRevenue())return this.logEvent(d.REVENUE_EVENT,e._toJSONObject())}else M.log.error("Invalid revenue input type. Expected Revenue object but saw "+A(e))},qt.prototype.logRevenue=function(e,t,n){return this._apiKeySet("logRevenue()")&&$t(e)&&(void 0===t||$t(t))?this._logEvent(d.REVENUE_EVENT,{},{productId:n,special:"revenue_amount",quantity:t||1,price:e},null,null,null,null):-1},qt.prototype.removeEvents=function(e,t){Jt(this,"_unsentEvents",e),Jt(this,"_unsentIdentifys",t)};var Jt=function(e,t,n){if(!(n<0)){for(var r=[],o=0;on&&r.push(e[t][o]);e[t]=r}};qt.prototype.sendEvents=function(e){if(!this._apiKeySet("sendEvents()")||this._sending||this.options.optOut||0===this._unsentCount())"function"===A(e)&&e(0,"No request sent");else{this._sending=!0;var t=(this.options.forceHttps?"https":"https:"===window.location.protocol?"https":"http")+"://"+this.options.apiEndpoint+"/",n=Math.min(this._unsentCount(),this.options.uploadBatchSize),r=this._mergeEventsAndIdentifys(n),o=r.maxEventId,i=r.maxIdentifyId,s=JSON.stringify(r.eventsToSend),a=(new Date).getTime(),u={client:this.options.apiKey,e:s,v:d.API_VERSION,upload_time:a,checksum:X(d.API_VERSION+this.options.apiKey+s+a)},c=this;new kt(t,u).send(function(t,r){c._sending=!1;try{200===t&&"success"===r?(c.removeEvents(o,i),c.options.saveEvents&&c.saveEvents(),c._sendEventsIfReady(e)||"function"!==A(e)||e(t,r)):413===t?(1===c.options.uploadBatchSize&&c.removeEvents(o,i),c.options.uploadBatchSize=Math.ceil(n/2),c.sendEvents(e)):"function"===A(e)&&e(t,r)}catch(e){}})}},qt.prototype._mergeEventsAndIdentifys=function(e){for(var t=[],n=0,r=-1,o=0,i=-1;t.length=this._unsentIdentifys.length,u=n>=this._unsentEvents.length;if(u&&a){M.log.error("Merging Events and Identifys, less events and identifys than expected");break}a?r=(s=this._unsentEvents[n++]).event_id:u?i=(s=this._unsentIdentifys[o++]).event_id:!("sequence_number"in this._unsentEvents[n])||this._unsentEvents[n].sequence_number0&&u>a&&(u=a);for(var c=0;c=0?(p=h.substr(0,g),l=h.substr(g+1)):(p=h,l=""),f=decodeURIComponent(p),d=decodeURIComponent(l),i(o,f)?jt(o[f])?o[f].push(d):o[f]=[o[f],d]:o[f]=d}return o}var p,l="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},f=(e(function(e,t){(function(){function n(e,t){function o(e){if(o[e]!==v)return o[e];var n;if("bug-string-char-index"==e)n="a"!="a"[0];else if("json"==e)n=o("json-stringify")&&o("json-parse");else{var r,i='{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';if("json-stringify"==e){var u=t.stringify,p="function"==typeof u&&_;if(p){(r=function(){return 1}).toJSON=r;try{p="0"===u(0)&&"0"===u(new s)&&'""'==u(new a)&&u(m)===v&&u(v)===v&&u()===v&&"1"===u(r)&&"[1]"==u([r])&&"[null]"==u([v])&&"null"==u(null)&&"[null,null,null]"==u([v,m,null])&&u({a:[r,!0,!1,null,"\0\b\n\f\r\t"]})==i&&"1"===u(null,r)&&"[\n 1,\n 2\n]"==u([1,2],null,1)&&'"-271821-04-20T00:00:00.000Z"'==u(new c(-864e13))&&'"+275760-09-13T00:00:00.000Z"'==u(new c(864e13))&&'"-000001-01-01T00:00:00.000Z"'==u(new c(-621987552e5))&&'"1969-12-31T23:59:59.999Z"'==u(new c(-1))}catch(e){p=!1}}n=p}if("json-parse"==e){var l=t.parse;if("function"==typeof l)try{if(0===l("0")&&!l(!1)){var f=5==(r=l(i)).a.length&&1===r.a[0];if(f){try{f=!l('"\t"')}catch(e){}if(f)try{f=1!==l("01")}catch(e){}if(f)try{f=1!==l("1.")}catch(e){}}}}catch(e){f=!1}n=f}}return o[e]=!!n}e||(e=i.Object()),t||(t=i.Object());var s=e.Number||i.Number,a=e.String||i.String,u=e.Object||i.Object,c=e.Date||i.Date,p=e.SyntaxError||i.SyntaxError,l=e.TypeError||i.TypeError,f=e.Math||i.Math,d=e.JSON||i.JSON;"object"==typeof d&&d&&(t.stringify=d.stringify,t.parse=d.parse);var h,g,v,y=u.prototype,m=y.toString,_=new c(-0xc782b5b800cec);try{_=-109252==_.getUTCFullYear()&&0===_.getUTCMonth()&&1===_.getUTCDate()&&10==_.getUTCHours()&&37==_.getUTCMinutes()&&6==_.getUTCSeconds()&&708==_.getUTCMilliseconds()}catch(e){}if(!o("json")){var b=o("bug-string-char-index");if(!_)var w=f.floor,I=[0,31,59,90,120,151,181,212,243,273,304,334],E=function(e,t){return I[t]+365*(e-1970)+w((e-1969+(t=+(t>1)))/4)-w((e-1901+t)/100)+w((e-1601+t)/400)};if((h=y.hasOwnProperty)||(h=function(e){var t,n={};return(n.__proto__=null,n.__proto__={toString:1},n).toString!=m?h=function(e){var t=this.__proto__,n=e in(this.__proto__=null,this);return this.__proto__=t,n}:(t=n.constructor,h=function(e){var n=(this.constructor||t).prototype;return e in this&&!(e in n&&this[e]===n[e])}),n=null,h.call(this,e)}),g=function(e,t){var n,o,i,s=0;(n=function(){this.valueOf=0}).prototype.valueOf=0,o=new n;for(i in o)h.call(o,i)&&s++;return n=o=null,s?g=2==s?function(e,t){var n,r={},o="[object Function]"==m.call(e);for(n in e)o&&"prototype"==n||h.call(r,n)||!(r[n]=1)||!h.call(e,n)||t(n)}:function(e,t){var n,r,o="[object Function]"==m.call(e);for(n in e)o&&"prototype"==n||!h.call(e,n)||(r="constructor"===n)||t(n);(r||h.call(e,n="constructor"))&&t(n)}:(o=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"],g=function(e,t){var n,i,s="[object Function]"==m.call(e),a=!s&&"function"!=typeof e.constructor&&r[typeof e.hasOwnProperty]&&e.hasOwnProperty||h;for(n in e)s&&"prototype"==n||!a.call(e,n)||t(n);for(i=o.length;n=o[--i];a.call(e,n)&&t(n));}),g(e,t)},!o("json-stringify")){var S={92:"\\\\",34:'\\"',8:"\\b",12:"\\f",10:"\\n",13:"\\r",9:"\\t"},C=function(e,t){return("000000"+(t||0)).slice(-e)},O=function(e){for(var t='"',n=0,r=e.length,o=!b||r>10,i=o&&(b?e.split(""):e);n-1/0&&a<1/0){if(E){for(f=w(a/864e5),c=w(f/365.2425)+1970-1;E(c+1,0)<=f;c++);for(p=w((f-E(c,0))/30.42);E(c,p+1)<=f;p++);f=1+f-E(c,p),y=w((d=(a%864e5+864e5)%864e5)/36e5)%24,_=w(d/6e4)%60,b=w(d/1e3)%60,I=d%1e3}else c=a.getUTCFullYear(),p=a.getUTCMonth(),f=a.getUTCDate(),y=a.getUTCHours(),_=a.getUTCMinutes(),b=a.getUTCSeconds(),I=a.getUTCMilliseconds();a=(c<=0||c>=1e4?(c<0?"-":"+")+C(6,c<0?-c:c):C(4,c))+"-"+C(2,p+1)+"-"+C(2,f)+"T"+C(2,y)+":"+C(2,_)+":"+C(2,b)+"."+C(3,I)+"Z"}else a=null;if(n&&(a=n.call(t,e,a)),null===a)return"null";if("[object Boolean]"==(u=m.call(a)))return""+a;if("[object Number]"==u)return a>-1/0&&a<1/0?""+a:"null";if("[object String]"==u)return O(""+a);if("object"==typeof a){for(x=s.length;x--;)if(s[x]===a)throw l();if(s.push(a),S=[],j=i,i+=o,"[object Array]"==u){for(T=0,x=a.length;T0)for(o="",n>10&&(n=10);o.length=48&&o<=57||o>=97&&o<=102||o>=65&&o<=70||k();e+=x("0x"+i.slice(t,A));break;default:k()}else{if(34==o)break;for(o=i.charCodeAt(A),t=A;o>=32&&92!=o&&34!=o;)o=i.charCodeAt(++A);e+=i.slice(t,A)}if(34==i.charCodeAt(A))return A++,e;k();default:if(t=A,45==o&&(r=!0,o=i.charCodeAt(++A)),o>=48&&o<=57){for(48==o&&(o=i.charCodeAt(A+1))>=48&&o<=57&&k(),r=!1;A=48&&o<=57;A++);if(46==i.charCodeAt(A)){for(n=++A;n=48&&o<=57;n++);n==A&&k(),A=n}if(101==(o=i.charCodeAt(A))||69==o){for(43!=(o=i.charCodeAt(++A))&&45!=o||A++,n=A;n=48&&o<=57;n++);n==A&&k(),A=n}return+i.slice(t,A)}if(r&&k(),"true"==i.slice(A,A+4))return A+=4,!0;if("false"==i.slice(A,A+5))return A+=5,!1;if("null"==i.slice(A,A+4))return A+=4,null;k()}return"$"},P=function(e){var t,n;if("$"==e&&k(),"string"==typeof e){if("@"==(b?e.charAt(0):e[0]))return e.slice(1);if("["==e){for(t=[];"]"!=(e=R());n||(n=!0))n&&(","==e?"]"==(e=R())&&k():k()),","==e&&k(),t.push(P(e));return t}if("{"==e){for(t={};"}"!=(e=R());n||(n=!0))n&&(","==e?"}"==(e=R())&&k():k()),","!=e&&"string"==typeof e&&"@"==(b?e.charAt(0):e[0])&&":"==R()||k(),t[e.slice(1)]=P(R());return t}k()}return e},F=function(e,t,n){var r=U(e,t,n);r===v?delete e[t]:e[t]=r},U=function(e,t,n){var r,o=e[t];if("object"==typeof o&&o)if("[object Array]"==m.call(o))for(r=o.length;r--;)F(o,r,n);else g(o,function(e){F(o,e,n)});return n.call(e,t,o)};t.parse=function(e,t){var n,r;return A=0,T=""+e,n=P(R()),"$"!=R()&&k(),A=T=null,t&&"[object Function]"==m.call(t)?U((r={},r[""]=n,r),"",t):n}}}return t.runInContext=n,t}var r={function:!0,object:!0},o=r.object&&t&&!t.nodeType&&t,i=r[typeof window]&&window||this,s=o&&r.object&&e&&!e.nodeType&&"object"==typeof l&&l;if(!s||s.global!==s&&s.window!==s&&s.self!==s||(i=s),o)n(i,o);else{var a=i.JSON,u=i.JSON3,c=!1,p=n(i,i.JSON3={noConflict:function(){return c||(c=!0,i.JSON=a,i.JSON3=u,a=u=null),p}});i.JSON={parse:p.parse,stringify:p.stringify}}}).call(l)}),{DEFAULT_INSTANCE:"$default_instance",API_VERSION:2,MAX_STRING_LENGTH:4096,MAX_PROPERTY_KEYS:1e3,IDENTIFY_EVENT:"$identify",LAST_EVENT_ID:"amplitude_lastEventId",LAST_EVENT_TIME:"amplitude_lastEventTime",LAST_IDENTIFY_ID:"amplitude_lastIdentifyId",LAST_SEQUENCE_NUMBER:"amplitude_lastSequenceNumber",SESSION_ID:"amplitude_sessionId",DEVICE_ID:"amplitude_deviceId",OPT_OUT:"amplitude_optOut",USER_ID:"amplitude_userId",COOKIE_TEST:"amplitude_cookie_test",REVENUE_EVENT:"revenue_amount",REVENUE_PRODUCT_ID:"$productId",REVENUE_QUANTITY:"$quantity",REVENUE_PRICE:"$price",REVENUE_REVENUE_TYPE:"$revenueType",AMP_DEVICE_ID_PARAM:"amp_device_id"}),d={encode:function(e){for(var t="",n=0;n127&&r<2048?(t+=String.fromCharCode(r>>6|192),t+=String.fromCharCode(63&r|128)):(t+=String.fromCharCode(r>>12|224),t+=String.fromCharCode(r>>6&63|128),t+=String.fromCharCode(63&r|128))}return t},decode:function(e){for(var t="",n=0,r=0,o=0,i=0;n191&&r<224?(o=e.charCodeAt(n+1),t+=String.fromCharCode((31&r)<<6|63&o),n+=2):(o=e.charCodeAt(n+1),i=e.charCodeAt(n+2),t+=String.fromCharCode((15&r)<<12|(63&o)<<6|63&i),n+=3);return t}},h={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){try{if(window.btoa&&window.atob)return window.btoa(unescape(encodeURIComponent(e)))}catch(e){}return h._encode(e)},_encode:function(e){var t,n,r,o,i,s,a,u="",c=0;for(e=d.encode(e);c>2,i=(3&t)<<4|(n=e.charCodeAt(c++))>>4,s=(15&n)<<2|(r=e.charCodeAt(c++))>>6,a=63&r,isNaN(n)?s=a=64:isNaN(r)&&(a=64),u=u+h._keyStr.charAt(o)+h._keyStr.charAt(i)+h._keyStr.charAt(s)+h._keyStr.charAt(a);return u},decode:function(e){try{if(window.btoa&&window.atob)return decodeURIComponent(escape(window.atob(e)))}catch(e){}return h._decode(e)},_decode:function(e){var t,n,r,o,i,s,a="",u=0;for(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");u>4,n=(15&o)<<4|(i=h._keyStr.indexOf(e.charAt(u++)))>>2,r=(3&i)<<6|(s=h._keyStr.indexOf(e.charAt(u++))),a+=String.fromCharCode(t),64!==i&&(a+=String.fromCharCode(n)),64!==s&&(a+=String.fromCharCode(r));return a=d.decode(a)}},g=e(function(e,t){t.parse=function(e){var t=document.createElement("a");return t.href=e,{href:t.href,host:t.host||location.host,port:"0"===t.port||""===t.port?function(e){switch(e){case"http:":return 80;case"https:":return 443;default:return location.port}}(t.protocol):t.port,hash:t.hash,hostname:t.hostname||location.hostname,pathname:"/"!=t.pathname.charAt(0)?"/"+t.pathname:t.pathname,protocol:t.protocol&&":"!=t.protocol?t.protocol:location.protocol,search:t.search,query:t.search.slice(1)}},t.isAbsolute=function(e){return 0==e.indexOf("//")||!!~e.indexOf("://")},t.isRelative=function(e){return!t.isAbsolute(e)},t.isCrossDomain=function(e){e=t.parse(e);var n=t.parse(window.location.href);return e.hostname!==n.hostname||e.port!==n.port||e.protocol!==n.protocol}}),v=1e3,y=60*v,m=60*y,_=24*m,b=365.25*_,w=function(e,n){n=n||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*b;case"days":case"day":case"d":return n*_;case"hours":case"hour":case"hrs":case"hr":case"h":return n*m;case"minutes":case"minute":case"mins":case"min":case"m":return n*y;case"seconds":case"second":case"secs":case"sec":case"s":return n*v;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}(e);if("number"===r&&!1===isNaN(e))return n.long?function(e){return t(e,_,"day")||t(e,m,"hour")||t(e,y,"minute")||t(e,v,"second")||e+" ms"}(e):function(e){return e>=_?Math.round(e/_)+"d":e>=m?Math.round(e/m)+"h":e>=y?Math.round(e/y)+"m":e>=v?Math.round(e/v)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))},I=e(function(e,t){function n(e){function n(){if(n.enabled){var e=n,r=+new Date,i=r-(o||r);e.diff=i,e.prev=o,e.curr=r,o=r;for(var s=new Array(arguments.length),a=0;a=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())})("cookie"),S=function(e,t,o){switch(arguments.length){case 3:case 2:return function(e,t,n){n=n||{};var o=r(e)+"="+r(t);null==t&&(n.maxage=-1),n.maxage&&(n.expires=new Date(+new Date+n.maxage)),n.path&&(o+="; path="+n.path),n.domain&&(o+="; domain="+n.domain),n.expires&&(o+="; expires="+n.expires.toUTCString()),n.secure&&(o+="; secure"),document.cookie=o}(e,t,o);case 1:return function(e){return n()[e]}(e);default:return n()}},C=e(function(e,t){function n(e){for(var n=t.cookie,r=t.levels(e),o=0;o=0;--i)o.push(t.slice(i).join("."));return o},n.cookie=S,t=e.exports=n}),O="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},N=Object.prototype.toString,A=function(e){switch(N.call(e)){case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object Error]":return"error"}return null===e?"null":void 0===e?"undefined":e!=e?"nan":e&&1===e.nodeType?"element":"undefined"!=typeof Buffer&&Buffer.isBuffer(e)?"buffer":void 0===(e=e.valueOf?e.valueOf():Object.prototype.valueOf.apply(e))?"undefined":O(e)},T="WARN",x={DISABLE:0,ERROR:1,WARN:2,INFO:3},j={error:function(e){T>=x.ERROR&&k(e)},warn:function(e){T>=x.WARN&&k(e)},info:function(e){T>=x.INFO&&k(e)}},k=function(e){try{console.log("[Amplitude] "+e)}catch(e){}},R=function(e){return"string"===A(e)&&e.length>f.MAX_STRING_LENGTH?e.substring(0,f.MAX_STRING_LENGTH):e},P=function(e){var t=A(e);if("object"!==t)return j.error("Error: invalid properties format. Expecting Javascript object, received "+t+", ignoring"),{};if(Object.keys(e).length>f.MAX_PROPERTY_KEYS)return j.error("Error: too many properties (more than 1000), ignoring"),{};var n={};for(var r in e)if(e.hasOwnProperty(r)){var o=r,i=A(o);"string"!==i&&(o=String(o),j.warn("WARNING: Non-string property key, received type "+i+', coercing to string "'+o+'"'));var s=U(o,e[r]);null!==s&&(n[o]=s)}return n},F=["null","nan","undefined","function","arguments","regexp","element"],U=function e(t,n){var r=A(n);if(-1!==F.indexOf(r))j.warn('WARNING: Property key "'+t+'" with invalid value type '+r+", ignoring"),n=null;else if("error"===r)n=String(n),j.warn('WARNING: Property key "'+t+'" with value type error, coercing to '+n);else if("array"===r){for(var o=[],i=0;i0?(this.userPropertiesOperations.hasOwnProperty("$clearAll")||M.log.error("Need to send $clearAll on its own Identify object without any other operations, skipping $clearAll"),this):(this.userPropertiesOperations.$clearAll="-",this)},Q.prototype.prepend=function(e,t){return this._addOperation("$prepend",e,t),this},Q.prototype.set=function(e,t){return this._addOperation("$set",e,t),this},Q.prototype.setOnce=function(e,t){return this._addOperation("$setOnce",e,t),this},Q.prototype.unset=function(e){return this._addOperation("$unset",e,"-"),this},Q.prototype._addOperation=function(e,t,n){this.userPropertiesOperations.hasOwnProperty("$clearAll")?M.log.error("This identify already contains a $clearAll operation, skipping operation "+e):-1===this.properties.indexOf(t)?(this.userPropertiesOperations.hasOwnProperty(e)||(this.userPropertiesOperations[e]={}),this.userPropertiesOperations[e][t]=n,this.properties.push(t)):M.log.error('User property "'+t+'" already used in this identify, skipping operation '+e)};var X=e(function(e){!function(t){function n(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function r(e,t,r,o,i,s){return n(function(e,t){return e<>>32-t}(n(n(t,e),n(o,s)),i),r)}function o(e,t,n,o,i,s,a){return r(t&n|~t&o,e,t,i,s,a)}function i(e,t,n,o,i,s,a){return r(t&o|n&~o,e,t,i,s,a)}function s(e,t,n,o,i,s,a){return r(t^n^o,e,t,i,s,a)}function a(e,t,n,o,i,s,a){return r(n^(t|~o),e,t,i,s,a)}function u(e,t){e[t>>5]|=128<>>9<<4)]=t;var r,u,c,p,l,f=1732584193,d=-271733879,h=-1732584194,g=271733878;for(r=0;r>5]>>>t%32&255);return n}function p(e){var t,n=[];for(n[(e.length>>2)-1]=void 0,t=0;t>5]|=(255&e.charCodeAt(t/8))<>>4&15)+"0123456789abcdef".charAt(15&t);return r}function f(e){return unescape(encodeURIComponent(e))}function d(e){return function(e){return c(u(p(e),8*e.length))}(f(e))}function h(e,t){return function(e,t){var n,r,o=p(e),i=[],s=[];for(i[15]=s[15]=void 0,o.length>16&&(o=u(o,8*e.length)),n=0;n<16;n+=1)i[n]=909522486^o[n],s[n]=1549556828^o[n];return r=u(i.concat(p(t)),512+8*t.length),c(u(s.concat(r),640))}(f(e),f(t))}function g(e,t,n){return t?n?h(t,e):function(e,t){return l(h(e,t))}(t,e):n?d(e):function(e){return l(d(e))}(e)}e.exports?e.exports=g:t.md5=g}(l)}),H="object"==typeof l&&l&&l.Object===Object&&l,Z="object"==typeof self&&self&&self.Object===Object&&self,ee=H||Z||Function("return this")(),te=ee.Symbol,ne=Object.prototype,re=ne.hasOwnProperty,oe=ne.toString,ie=te?te.toStringTag:void 0,se=function(e){var t=re.call(e,ie),n=e[ie];try{e[ie]=void 0;var r=!0}catch(e){}var o=oe.call(e);return r&&(t?e[ie]=n:delete e[ie]),o},ae=Object.prototype.toString,ue=function(e){return ae.call(e)},ce="[object Null]",pe="[object Undefined]",le=te?te.toStringTag:void 0,fe=function(e){return null==e?void 0===e?pe:ce:le&&le in Object(e)?se(e):ue(e)},de=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},he="[object AsyncFunction]",ge="[object Function]",ve="[object GeneratorFunction]",ye="[object Proxy]",me=function(e){if(!de(e))return!1;var t=fe(e);return t==ge||t==ve||t==he||t==ye},_e=ee["__core-js_shared__"],be=function(){var e=/[^.]+$/.exec(_e&&_e.keys&&_e.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),we=function(e){return!!be&&be in e},Ie=Function.prototype.toString,Ee=function(e){if(null!=e){try{return Ie.call(e)}catch(e){}try{return e+""}catch(e){}}return""},Se=/^\[object .+?Constructor\]$/,Ce=Function.prototype,Oe=Object.prototype,Ne=Ce.toString,Ae=Oe.hasOwnProperty,Te=RegExp("^"+Ne.call(Ae).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),xe=function(e){return!(!de(e)||we(e))&&(me(e)?Te:Se).test(Ee(e))},je=function(e,t){return null==e?void 0:e[t]},ke=function(e,t){var n=je(e,t);return xe(n)?n:void 0},Re=function(){try{var e=ke(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),Pe=function(e,t,n){"__proto__"==t&&Re?Re(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n},Fe=function(e,t){return e===t||e!=e&&t!=t},Ue=Object.prototype.hasOwnProperty,De=function(e,t,n){var r=e[t];Ue.call(e,t)&&Fe(r,n)&&(void 0!==n||t in e)||Pe(e,t,n)},Me=function(e,t,n,r){var o=!n;n||(n={});for(var i=-1,s=t.length;++i0){if(++t>=ze)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}(Ke),Ye=function(e,t){return We(Ge(e,t,qe),e+"")},Qe=9007199254740991,Xe=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=Qe},He=function(e){return null!=e&&Xe(e.length)&&!me(e)},Ze=9007199254740991,et=/^(?:0|[1-9]\d*)$/,tt=function(e,t){return!!(t=null==t?Ze:t)&&("number"==typeof e||et.test(e))&&e>-1&&e%1==0&&e1?n[o-1]:void 0,s=o>2?n[2]:void 0;for(i=e.length>3&&"function"==typeof i?(o--,i):void 0,s&&nt(n[0],n[1],s)&&(i=o<3?void 0:i,o=1),t=Object(t);++r0?2==o.length?"function"==typeof o[1]?e[o[0]]=o[1].call(this,s):e[o[0]]=o[1]:3==o.length?"function"!=typeof o[1]||o[1].exec&&o[1].test?e[o[0]]=s?s.replace(o[1],o[2]):void 0:e[o[0]]=s?o[1].call(this,s,o[2]):void 0:4==o.length&&(e[o[0]]=s?o[3].call(this,s.replace(o[1],o[2])):void 0):e[o]=s||void 0;a+=2}return e},str:function(e,t){for(var n in t)if("object"==typeof t[n]&&t[n].length>0){for(var r=0;r>t/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,e)},Mt={apiEndpoint:"api.amplitude.com",cookieExpiration:3650,cookieName:"amplitude_id",domain:"",includeReferrer:!1,includeUtm:!1,language:{language:navigator&&(navigator.languages&&navigator.languages[0]||navigator.language||navigator.userLanguage)||void 0}.language,logLevel:"WARN",optOut:!1,platform:"Web",savedMaxCount:1e3,saveEvents:!0,sessionTimeout:18e5,unsentKey:"amplitude_unsent",unsentIdentifyKey:"amplitude_unsent_identify",uploadBatchSize:100,batchEvents:!1,eventUploadThreshold:30,eventUploadPeriodMillis:3e4,forceHttps:!0,includeGclid:!1,saveParamsReferrerOncePerSession:!0,deviceIdFromUrlParam:!1},qt=function(e){this._instanceName=M.isEmptyString(e)?f.DEFAULT_INSTANCE:e.toLowerCase(),this._legacyStorageSuffix=this._instanceName===f.DEFAULT_INSTANCE?"":"_"+this._instanceName,this._unsentEvents=[],this._unsentIdentifys=[],this._ua=new Ut(navigator.userAgent).getResult(),this.options=xt({},Mt),this.cookieStorage=(new Y).getStorage(),this._q=[],this._sending=!1,this._updateScheduled=!1,this._eventId=0,this._identifyId=0,this._lastEventTime=null,this._newSession=!1,this._sequenceNumber=0,this._sessionId=null,this._userAgent=navigator&&navigator.userAgent||null};qt.prototype.Identify=Q,qt.prototype.Revenue=Ft,qt.prototype.init=function(e,t,n,r){if("string"!==A(e)||M.isEmptyString(e))M.log.error("Invalid apiKey. Please re-initialize with a valid apiKey");else try{if(this.options.apiKey=e,this._storageSuffix="_"+e+this._legacyStorageSuffix,Lt(this.options,n),this.cookieStorage.options({expirationDays:this.options.cookieExpiration,domain:this.options.domain}),this.options.domain=this.cookieStorage.options().domain,this._instanceName===f.DEFAULT_INSTANCE&&Vt(this),Gt(this),this.options.deviceId="object"===A(n)&&"string"===A(n.deviceId)&&!M.isEmptyString(n.deviceId)&&n.deviceId||this.options.deviceIdFromUrlParam&&this._getDeviceIdFromUrlParam(this._getUrlParams())||this.options.deviceId||Dt()+"R",this.options.userId="string"===A(t)&&!M.isEmptyString(t)&&t||"number"===A(t)&&t.toString()||this.options.userId||null,this.options.saveEvents){this._unsentEvents=this._loadSavedUnsentEvents(this.options.unsentKey),this._unsentIdentifys=this._loadSavedUnsentEvents(this.options.unsentIdentifyKey);for(var o=0;othis.options.sessionTimeout)&&(this._newSession=!0,this._sessionId=p,this.options.saveParamsReferrerOncePerSession&&this._trackParamsAndReferrer()),this.options.saveParamsReferrerOncePerSession||this._trackParamsAndReferrer(),this._lastEventTime=p,Kt(this),this._sendEventsIfReady()}catch(e){M.log.error(e)}finally{"function"===A(r)&&r(this)}},qt.prototype._trackParamsAndReferrer=function(){this.options.includeUtm&&this._initUtmData(),this.options.includeReferrer&&this._saveReferrer(this._getReferrer()),this.options.includeGclid&&this._saveGclid(this._getUrlParams())};var Lt=function(e,t){if("object"===A(t)){var n=function(n){if(Mt.hasOwnProperty(n)){var r=t[n],o=A(Mt[n]);M.validateInput(r,n+" option",o)&&("boolean"===o?e[n]=!!r:("string"===o&&!M.isEmptyString(r)||"number"===o&&r>0)&&(e[n]=r))}};for(var r in t)t.hasOwnProperty(r)&&n(r)}};qt.prototype.runQueuedFunctions=function(){for(var e=0;e=this.options.eventUploadThreshold?(this.sendEvents(e),!0):(this._updateScheduled||(this._updateScheduled=!0,setTimeout(function(){this._updateScheduled=!1,this.sendEvents()}.bind(this),this.options.eventUploadPeriodMillis)),!1):(this.sendEvents(e),!0))},qt.prototype._getFromStorage=function(e,t){return e.getItem(t+this._storageSuffix)},qt.prototype._getFromStorageLegacy=function(e,t){return e.getItem(t+this._legacyStorageSuffix)},qt.prototype._setInStorage=function(e,t,n){e.setItem(t+this._storageSuffix,n)};var Vt=function(e){var t=e.cookieStorage.get(e.options.cookieName+e._storageSuffix);if(!("object"===A(t)&&t.deviceId&&t.sessionId&&t.lastEventTime)){var n=function(e){var t=W.getItem(e);return W.removeItem(e),t},r="string"===A(e.options.apiKey)&&"_"+e.options.apiKey.slice(0,6)||"",o=n(f.DEVICE_ID+r),i=n(f.USER_ID+r),s=n(f.OPT_OUT+r);null!==s&&void 0!==s&&(s="true"===String(s));var a=parseInt(n(f.SESSION_ID)),u=parseInt(n(f.LAST_EVENT_TIME)),c=parseInt(n(f.LAST_EVENT_ID)),p=parseInt(n(f.LAST_IDENTIFY_ID)),l=parseInt(n(f.LAST_SEQUENCE_NUMBER)),d=function(e){return"object"===A(t)&&t[e]};e.options.deviceId=d("deviceId")||o,e.options.userId=d("userId")||i,e._sessionId=d("sessionId")||a||e._sessionId,e._lastEventTime=d("lastEventTime")||u||e._lastEventTime,e._eventId=d("eventId")||c||e._eventId,e._identifyId=d("identifyId")||p||e._identifyId,e._sequenceNumber=d("sequenceNumber")||l||e._sequenceNumber,e.options.optOut=s||!1,t&&void 0!==t.optOut&&null!==t.optOut&&(e.options.optOut="true"===String(t.optOut)),Kt(e)}},Gt=function(e){var t=e.cookieStorage.get(e.options.cookieName+e._storageSuffix);if("object"===A(t))Bt(e,t);else{var n=e.cookieStorage.get(e.options.cookieName+e._legacyStorageSuffix);"object"===A(n)&&(e.cookieStorage.remove(e.options.cookieName+e._legacyStorageSuffix),Bt(e,n))}},Bt=function(e,t){t.deviceId&&(e.options.deviceId=t.deviceId),t.userId&&(e.options.userId=t.userId),null!==t.optOut&&void 0!==t.optOut&&(e.options.optOut=t.optOut),t.sessionId&&(e._sessionId=parseInt(t.sessionId)),t.lastEventTime&&(e._lastEventTime=parseInt(t.lastEventTime)),t.eventId&&(e._eventId=parseInt(t.eventId)),t.identifyId&&(e._identifyId=parseInt(t.identifyId)),t.sequenceNumber&&(e._sequenceNumber=parseInt(t.sequenceNumber))},Kt=function(e){e.cookieStorage.set(e.options.cookieName+e._storageSuffix,{deviceId:e.options.deviceId,userId:e.options.userId,optOut:e.options.optOut,sessionId:e._sessionId,lastEventTime:e._lastEventTime,eventId:e._eventId,identifyId:e._identifyId,sequenceNumber:e._sequenceNumber})};qt.prototype._initUtmData=function(e,t){e=e||this._getUrlParams();var n=function(e,t){var n=e?"?"+e.split(".").slice(-1)[0].replace(/\|/g,"&"):"",r=function(e,t,n,r){return M.getQueryParam(e,t)||M.getQueryParam(n,r)},o=r("utm_source",t,"utmcsr",n),i=r("utm_medium",t,"utmcmd",n),s=r("utm_campaign",t,"utmccn",n),a=r("utm_term",t,"utmctr",n),u=r("utm_content",t,"utmcct",n),c={},p=function(e,t){M.isEmptyString(t)||(c[e]=t)};return p("utm_source",o),p("utm_medium",i),p("utm_campaign",s),p("utm_term",a),p("utm_content",u),c}(t=t||this.cookieStorage.get("__utmz"),e);zt(this,n)};var zt=function(e,t){if("object"===A(t)&&0!==Object.keys(t).length){var n=new Q;for(var r in t)t.hasOwnProperty(r)&&(n.setOnce("initial_"+r,t[r]),n.set(r,t[r]));e.identify(n)}};qt.prototype._getReferrer=function(){return document.referrer},qt.prototype._getUrlParams=function(){return location.search},qt.prototype._saveGclid=function(e){var t=M.getQueryParam("gclid",e);if(!M.isEmptyString(t)){zt(this,{gclid:t})}},qt.prototype._getDeviceIdFromUrlParam=function(e){return M.getQueryParam(f.AMP_DEVICE_ID_PARAM,e)},qt.prototype._getReferringDomain=function(e){if(M.isEmptyString(e))return null;var t=e.split("/");return t.length>=3?t[2]:null},qt.prototype._saveReferrer=function(e){if(!M.isEmptyString(e)){var t={referrer:e,referring_domain:this._getReferringDomain(e)};zt(this,t)}},qt.prototype.saveEvents=function(){try{this._setInStorage(W,this.options.unsentKey,JSON.stringify(this._unsentEvents))}catch(e){}try{this._setInStorage(W,this.options.unsentIdentifyKey,JSON.stringify(this._unsentIdentifys))}catch(e){}},qt.prototype.setDomain=function(e){if(M.validateInput(e,"domain","string"))try{this.cookieStorage.options({domain:e}),this.options.domain=this.cookieStorage.options().domain,Gt(this),Kt(this)}catch(e){M.log.error(e)}},qt.prototype.setUserId=function(e){try{this.options.userId=void 0!==e&&null!==e&&""+e||null,Kt(this)}catch(e){M.log.error(e)}},qt.prototype.setGroup=function(e,t){if(this._apiKeySet("setGroup()")&&M.validateInput(e,"groupType","string")&&!M.isEmptyString(e)){var n={};n[e]=t;var r=(new Q).set(e,t);this._logEvent(f.IDENTIFY_EVENT,null,null,r.userPropertiesOperations,n,null,null)}},qt.prototype.setOptOut=function(e){if(M.validateInput(e,"enable","boolean"))try{this.options.optOut=e,Kt(this)}catch(e){M.log.error(e)}},qt.prototype.setSessionId=function(e){if(M.validateInput(e,"sessionId","number"))try{this._sessionId=e,Kt(this)}catch(e){M.log.error(e)}},qt.prototype.regenerateDeviceId=function(){this.setDeviceId(Dt()+"R")},qt.prototype.setDeviceId=function(e){if(M.validateInput(e,"deviceId","string"))try{M.isEmptyString(e)||(this.options.deviceId=""+e,Kt(this))}catch(e){M.log.error(e)}},qt.prototype.setUserProperties=function(e){if(this._apiKeySet("setUserProperties()")&&M.validateInput(e,"userProperties","object")){var t=M.truncate(M.validateProperties(e));if(0!==Object.keys(t).length){var n=new Q;for(var r in t)t.hasOwnProperty(r)&&n.set(r,t[r]);this.identify(n)}}},qt.prototype.clearUserProperties=function(){if(this._apiKeySet("clearUserProperties()")){var e=new Q;e.clearAll(),this.identify(e)}};var Jt=function(e,t){for(var n=0;n0)return this._logEvent(f.IDENTIFY_EVENT,null,null,e.userPropertiesOperations,null,null,t)}else M.log.error("Invalid identify input type. Expected Identify object but saw "+A(e));"function"===A(t)&&t(0,"No request sent")}else"function"===A(t)&&t(0,"No request sent")},qt.prototype.setVersionName=function(e){M.validateInput(e,"versionName","string")&&(this.options.versionName=e)},qt.prototype._logEvent=function(e,t,n,r,o,i,s){if(Gt(this),e&&!this.options.optOut)try{var a;a=e===f.IDENTIFY_EVENT?this.nextIdentifyId():this.nextEventId();var u=this.nextSequenceNumber(),c="number"===A(i)?i:(new Date).getTime();(!this._sessionId||!this._lastEventTime||c-this._lastEventTime>this.options.sessionTimeout)&&(this._sessionId=c),this._lastEventTime=c,Kt(this),r=r||{},n=n||{},t=t||{},o=o||{};var p={device_id:this.options.deviceId,user_id:this.options.userId,timestamp:c,event_id:a,session_id:this._sessionId||-1,event_type:e,version_name:this.options.versionName||null,platform:this.options.platform,os_name:this._ua.browser.name||null,os_version:this._ua.browser.major||null,device_model:this._ua.os.name||null,language:this.options.language,api_properties:n,event_properties:M.truncate(M.validateProperties(t)),user_properties:M.truncate(M.validateProperties(r)),uuid:Dt(),library:{name:"amplitude-js",version:"4.0.0"},sequence_number:u,groups:M.truncate(M.validateGroups(o)),user_agent:this._userAgent};return e===f.IDENTIFY_EVENT?(this._unsentIdentifys.push(p),this._limitEventsQueued(this._unsentIdentifys)):(this._unsentEvents.push(p),this._limitEventsQueued(this._unsentEvents)),this.options.saveEvents&&this.saveEvents(),this._sendEventsIfReady(s)||"function"!==A(s)||s(0,"No request sent"),a}catch(e){M.log.error(e)}else"function"===A(s)&&s(0,"No request sent")},qt.prototype._limitEventsQueued=function(e){e.length>this.options.savedMaxCount&&e.splice(0,e.length-this.options.savedMaxCount)},qt.prototype.logEvent=function(e,t,n){return this.logEventWithTimestamp(e,t,null,n)},qt.prototype.logEventWithTimestamp=function(e,t,n,r){return this._apiKeySet("logEvent()")&&M.validateInput(e,"eventType","string")&&!M.isEmptyString(e)?this._logEvent(e,t,null,null,null,n,r):("function"===A(r)&&r(0,"No request sent"),-1)},qt.prototype.logEventWithGroups=function(e,t,n,r){return this._apiKeySet("logEventWithGroup()")&&M.validateInput(e,"eventType","string")?this._logEvent(e,t,null,null,n,null,r):("function"===A(r)&&r(0,"No request sent"),-1)};var $t=function(e){return!isNaN(parseFloat(e))&&isFinite(e)};qt.prototype.logRevenueV2=function(e){if(this._apiKeySet("logRevenueV2()"))if("object"===A(e)&&e.hasOwnProperty("_q")&&(e=Jt(new Ft,e)),e instanceof Ft){if(e&&e._isValidRevenue())return this.logEvent(f.REVENUE_EVENT,e._toJSONObject())}else M.log.error("Invalid revenue input type. Expected Revenue object but saw "+A(e))},qt.prototype.logRevenue=function(e,t,n){return this._apiKeySet("logRevenue()")&&$t(e)&&(void 0===t||$t(t))?this._logEvent(f.REVENUE_EVENT,{},{productId:n,special:"revenue_amount",quantity:t||1,price:e},null,null,null,null):-1},qt.prototype.removeEvents=function(e,t){Wt(this,"_unsentEvents",e),Wt(this,"_unsentIdentifys",t)};var Wt=function(e,t,n){if(!(n<0)){for(var r=[],o=0;on&&r.push(e[t][o]);e[t]=r}};qt.prototype.sendEvents=function(e){if(!this._apiKeySet("sendEvents()")||this._sending||this.options.optOut||0===this._unsentCount())"function"===A(e)&&e(0,"No request sent");else{this._sending=!0;var t=(this.options.forceHttps?"https":"https:"===window.location.protocol?"https":"http")+"://"+this.options.apiEndpoint+"/",n=Math.min(this._unsentCount(),this.options.uploadBatchSize),r=this._mergeEventsAndIdentifys(n),o=r.maxEventId,i=r.maxIdentifyId,s=JSON.stringify(r.eventsToSend),a=(new Date).getTime(),u={client:this.options.apiKey,e:s,v:f.API_VERSION,upload_time:a,checksum:X(f.API_VERSION+this.options.apiKey+s+a)},c=this;new Pt(t,u).send(function(t,r){c._sending=!1;try{200===t&&"success"===r?(c.removeEvents(o,i),c.options.saveEvents&&c.saveEvents(),c._sendEventsIfReady(e)||"function"!==A(e)||e(t,r)):413===t?(1===c.options.uploadBatchSize&&c.removeEvents(o,i),c.options.uploadBatchSize=Math.ceil(n/2),c.sendEvents(e)):"function"===A(e)&&e(t,r)}catch(e){}})}},qt.prototype._mergeEventsAndIdentifys=function(e){for(var t=[],n=0,r=-1,o=0,i=-1;t.length=this._unsentIdentifys.length,u=n>=this._unsentEvents.length;if(u&&a){M.log.error("Merging Events and Identifys, less events and identifys than expected");break}a?r=(s=this._unsentEvents[n++]).event_id:u?i=(s=this._unsentIdentifys[o++]).event_id:!("sequence_number"in this._unsentEvents[n])||this._unsentEvents[n].sequence_number= now); assert.isTrue(app1._lastEventTime >= now); assert.equal(app1._eventId, 0); @@ -274,7 +274,7 @@ describe('Amplitude', function() { it('should set cookie', function() { amplitude.init(apiKey, userId); - var stored = cookie.get(amplitude.options.cookieName); + var stored = cookie.get(amplitude.options.cookieName + '_' + apiKey); assert.property(stored, 'deviceId'); assert.propertyVal(stored, 'userId', userId); assert.lengthOf(stored.deviceId, 37); // increase deviceId length by 1 for 'R' character @@ -318,7 +318,7 @@ describe('Amplitude', function() { assert.equal(amplitude.options.userId, userId); assert.isTrue(amplitude.options.optOut); - var cookieData = cookie.get(amplitude.options.cookieName); + var cookieData = cookie.get(amplitude.options.cookieName + '_' + apiKey); assert.equal(cookieData.deviceId, deviceId); assert.equal(cookieData.userId, userId); assert.isTrue(cookieData.optOut); @@ -342,7 +342,7 @@ describe('Amplitude', function() { assert.equal(amplitude.getInstance()._identifyId, 4000); assert.equal(amplitude.getInstance()._sequenceNumber, 5000); - var cookieData = cookie.get(amplitude.options.cookieName); + var cookieData = cookie.get(amplitude.options.cookieName + '_' + apiKey); assert.equal(cookieData.sessionId, now); assert.equal(cookieData.lastEventTime, amplitude.getInstance()._lastEventTime); assert.equal(cookieData.eventId, 3000); @@ -363,7 +363,7 @@ describe('Amplitude', function() { identifyId: 60 } - cookie.set(amplitude.options.cookieName, cookieData); + cookie.set(amplitude.options.cookieName + '_' + apiKey, cookieData); localStorage.setItem('amplitude_deviceId' + keySuffix, 'old_device_id'); localStorage.setItem('amplitude_userId' + keySuffix, 'fake_user_id'); localStorage.setItem('amplitude_optOut' + keySuffix, true); @@ -387,7 +387,7 @@ describe('Amplitude', function() { it('should skip the migration if the new cookie already has deviceId, sessionId, lastEventTime', function() { var now = new Date().getTime(); - cookie.set(amplitude.options.cookieName, { + cookie.set(amplitude.options.cookieName + '_' + apiKey, { deviceId: 'new_device_id', sessionId: now, lastEventTime: now @@ -493,18 +493,45 @@ describe('Amplitude', function() { assert.equal(amplitude2.getInstance()._sequenceNumber, 70); }); + it('should load saved events from legacy localStorage', function() { + var existingEvent = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769146589,' + + '"event_id":49,"session_id":1453763315544,"event_type":"clicked","version_name":"Web","platform":"Web"' + + ',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' + + '"event_properties":{},"user_properties":{},"uuid":"3c508faa-a5c9-45fa-9da7-9f4f3b992fb0","library"' + + ':{"name":"amplitude-js","version":"2.9.0"},"sequence_number":130,"groups":{}}]'; + var existingIdentify = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769338995,' + + '"event_id":82,"session_id":1453763315544,"event_type":"$identify","version_name":"Web","platform":"Web"' + + ',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' + + '"event_properties":{},"user_properties":{"$set":{"age":30,"city":"San Francisco, CA"}},"uuid":"' + + 'c50e1be4-7976-436a-aa25-d9ee38951082","library":{"name":"amplitude-js","version":"2.9.0"},"sequence_number"' + + ':131,"groups":{}}]'; + localStorage.setItem('amplitude_unsent', existingEvent); + localStorage.setItem('amplitude_unsent_identify', existingIdentify); + + var amplitude2 = new Amplitude(); + amplitude2.init(apiKey, null, {batchEvents: true}); + + // check event loaded into memory + assert.deepEqual(amplitude2.getInstance()._unsentEvents, JSON.parse(existingEvent)); + assert.deepEqual(amplitude2.getInstance()._unsentIdentifys, JSON.parse(existingIdentify)); + + // check local storage keys are still same for default instance + assert.equal(localStorage.getItem('amplitude_unsent_' + apiKey), existingEvent); + assert.equal(localStorage.getItem('amplitude_unsent_identify_' + apiKey), existingIdentify); + }); + it('should load saved events from localStorage', function() { var existingEvent = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769146589,' + '"event_id":49,"session_id":1453763315544,"event_type":"clicked","version_name":"Web","platform":"Web"' + ',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' + '"event_properties":{},"user_properties":{},"uuid":"3c508faa-a5c9-45fa-9da7-9f4f3b992fb0","library"' + - ':{"name":"amplitude-js","version":"2.9.0"},"sequence_number":130, "groups":{}}]'; + ':{"name":"amplitude-js","version":"2.9.0"},"sequence_number":130,"groups":{}}]'; var existingIdentify = '[{"device_id":"test_device_id","user_id":"test_user_id","timestamp":1453769338995,' + '"event_id":82,"session_id":1453763315544,"event_type":"$identify","version_name":"Web","platform":"Web"' + ',"os_name":"Chrome","os_version":"47","device_model":"Mac","language":"en-US","api_properties":{},' + '"event_properties":{},"user_properties":{"$set":{"age":30,"city":"San Francisco, CA"}},"uuid":"' + 'c50e1be4-7976-436a-aa25-d9ee38951082","library":{"name":"amplitude-js","version":"2.9.0"},"sequence_number"' + - ':131, "groups":{}}]'; + ':131,"groups":{}}]'; localStorage.setItem('amplitude_unsent', existingEvent); localStorage.setItem('amplitude_unsent_identify', existingIdentify); @@ -516,8 +543,8 @@ describe('Amplitude', function() { assert.deepEqual(amplitude2.getInstance()._unsentIdentifys, JSON.parse(existingIdentify)); // check local storage keys are still same for default instance - assert.equal(localStorage.getItem('amplitude_unsent'), existingEvent); - assert.equal(localStorage.getItem('amplitude_unsent_identify'), existingIdentify); + assert.equal(localStorage.getItem('amplitude_unsent_' + apiKey), existingEvent); + assert.equal(localStorage.getItem('amplitude_unsent_identify_' + apiKey), existingIdentify); }); it('should validate event properties when loading saved events from localStorage', function() { @@ -606,8 +633,8 @@ describe('Amplitude', function() { assert.deepEqual(amplitude2.getInstance()._unsentIdentifys, []); // check local storage keys are still same - assert.equal(localStorage.getItem('amplitude_unsent'), JSON.stringify([])); - assert.equal(localStorage.getItem('amplitude_unsent_identify'), JSON.stringify([])); + assert.equal(localStorage.getItem('amplitude_unsent_' + apiKey), JSON.stringify([])); + assert.equal(localStorage.getItem('amplitude_unsent_identify_' + apiKey), JSON.stringify([])); // check request assert.lengthOf(server.requests, 1); @@ -873,7 +900,7 @@ describe('setVersionName', function() { it('should store device id in cookie', function() { amplitude.init(apiKey, null, {'deviceId': 'fakeDeviceId'}); amplitude.setDeviceId('deviceId'); - var stored = cookie.get(amplitude.options.cookieName); + var stored = cookie.get(amplitude.options.cookieName + '_' + apiKey); assert.propertyVal(stored, 'deviceId', 'deviceId'); }); }); @@ -1886,7 +1913,7 @@ describe('setVersionName', function() { clock.tick(20); amplitude2.setUserProperties({'key':'value'}); // identify event at time 30 - var cookieData = JSON.parse(localStorage.getItem('amp_cookiestore_amplitude_id')); + var cookieData = JSON.parse(localStorage.getItem('amp_cookiestore_amplitude_id_' + apiKey)); assert.deepEqual(cookieData, { 'deviceId': deviceId, 'userId': null, diff --git a/yarn.lock b/yarn.lock index 3d9cb527..8bc09627 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2186,6 +2186,12 @@ karma-sinon@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/karma-sinon/-/karma-sinon-1.0.5.tgz#4e3443f2830fdecff624d3747163f1217daa2a9a" +karma-sourcemap-loader@^0.3.7: + version "0.3.7" + resolved "https://registry.yarnpkg.com/karma-sourcemap-loader/-/karma-sourcemap-loader-0.3.7.tgz#91322c77f8f13d46fed062b042e1009d4c4505d8" + dependencies: + graceful-fs "^4.1.2" + karma@^1.7.1: version "1.7.1" resolved "https://registry.yarnpkg.com/karma/-/karma-1.7.1.tgz#85cc08e9e0a22d7ce9cca37c4a1be824f6a2b1ae"