diff --git a/build/moesif.amd.js b/build/moesif.amd.js index 05a73c5..33fe261 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.1' + LIB_VERSION: '1.8.2' }; // since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file @@ -3291,6 +3291,17 @@ define(function () { 'use strict'; this._companyId = getFromPersistence(STORAGE_CONSTANTS.STORED_COMPANY_ID, ops); this._anonymousId = getAnonymousId(this._persist, ops); 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) { + var anonUserObject = {}; + anonUserObject['anonymous_id'] = this._anonymousId; + anonUserObject['campaign'] = this._campaign; + this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback); + } } catch(err) { console.error('error loading saved data from local storage but continue'); } diff --git a/build/moesif.cjs.js b/build/moesif.cjs.js index 4378679..12842b0 100644 --- a/build/moesif.cjs.js +++ b/build/moesif.cjs.js @@ -2,7 +2,7 @@ var Config = { DEBUG: false, - LIB_VERSION: '1.8.1' + LIB_VERSION: '1.8.2' }; // since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file @@ -3291,6 +3291,17 @@ function moesifCreator () { this._companyId = getFromPersistence(STORAGE_CONSTANTS.STORED_COMPANY_ID, ops); this._anonymousId = getAnonymousId(this._persist, ops); 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) { + var anonUserObject = {}; + anonUserObject['anonymous_id'] = this._anonymousId; + anonUserObject['campaign'] = this._campaign; + this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback); + } } catch(err) { console.error('error loading saved data from local storage but continue'); } diff --git a/build/moesif.globals.js b/build/moesif.globals.js index 1d1fbd8..49929cc 100644 --- a/build/moesif.globals.js +++ b/build/moesif.globals.js @@ -3,7 +3,7 @@ var Config = { DEBUG: false, - LIB_VERSION: '1.8.1' + LIB_VERSION: '1.8.2' }; // since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file @@ -3292,6 +3292,17 @@ this._companyId = getFromPersistence(STORAGE_CONSTANTS.STORED_COMPANY_ID, ops); this._anonymousId = getAnonymousId(this._persist, ops); 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) { + var anonUserObject = {}; + anonUserObject['anonymous_id'] = this._anonymousId; + anonUserObject['campaign'] = this._campaign; + this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback); + } } catch(err) { console.error('error loading saved data from local storage but continue'); } diff --git a/build/moesif.umd.js b/build/moesif.umd.js index 16ca13d..4e0c47f 100644 --- a/build/moesif.umd.js +++ b/build/moesif.umd.js @@ -6,7 +6,7 @@ var Config = { DEBUG: false, - LIB_VERSION: '1.8.1' + LIB_VERSION: '1.8.2' }; // since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file @@ -3295,6 +3295,17 @@ this._companyId = getFromPersistence(STORAGE_CONSTANTS.STORED_COMPANY_ID, ops); this._anonymousId = getAnonymousId(this._persist, ops); 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) { + var anonUserObject = {}; + anonUserObject['anonymous_id'] = this._anonymousId; + anonUserObject['campaign'] = this._campaign; + this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback); + } } catch(err) { console.error('error loading saved data from local storage but continue'); } diff --git a/examples/commonjs-browserify/bundle.js b/examples/commonjs-browserify/bundle.js index 71bea07..9dd3f03 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.1' + LIB_VERSION: '1.8.2' }; // since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file @@ -3292,6 +3292,17 @@ function moesifCreator () { this._companyId = getFromPersistence(STORAGE_CONSTANTS.STORED_COMPANY_ID, ops); this._anonymousId = getAnonymousId(this._persist, ops); 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) { + var anonUserObject = {}; + anonUserObject['anonymous_id'] = this._anonymousId; + anonUserObject['campaign'] = this._campaign; + this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback); + } } catch(err) { console.error('error loading saved data from local storage but continue'); } diff --git a/examples/es2015-babelify/bundle.js b/examples/es2015-babelify/bundle.js index 5eedd9c..5713a8b 100644 --- a/examples/es2015-babelify/bundle.js +++ b/examples/es2015-babelify/bundle.js @@ -578,7 +578,7 @@ Object.defineProperty(exports, '__esModule', { }); var Config = { DEBUG: false, - LIB_VERSION: '1.8.1' + LIB_VERSION: '1.8.2' }; exports['default'] = Config; @@ -840,6 +840,17 @@ exports['default'] = function () { this._companyId = (0, _persistence.getFromPersistence)(_persistence.STORAGE_CONSTANTS.STORED_COMPANY_ID, ops); this._anonymousId = (0, _anonymousId.getAnonymousId)(this._persist, ops); this._campaign = (0, _campaign2['default'])(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) { + var anonUserObject = {}; + anonUserObject['anonymous_id'] = this._anonymousId; + anonUserObject['campaign'] = this._campaign; + this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback); + } } catch (err) { _utils.console.error('error loading saved data from local storage but continue'); } diff --git a/examples/umd-webpack/dist/main.js b/examples/umd-webpack/dist/main.js index 508e0e0..96146f0 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 o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.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 o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));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.1"};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,o,i,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,_=e.console,b=e.navigator,w=e.document,S=e.opera,I=e.screen,k=b.userAgent,E=p.bind,O=h.forEach,x=h.indexOf,q=h.map,B=Array.isArray,A={},M={trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},T={log:function(){if(t.DEBUG&&!M.isUndefined(_)&&_)try{_.log.apply(_,arguments)}catch(e){M.each(arguments,(function(e){_.log(e)}))}},error:function(){if(t.DEBUG&&!M.isUndefined(_)&&_){var e=["Moesif error:"].concat(M.toArray(arguments));try{_.error.apply(_,e)}catch(t){M.each(e,(function(e){_.error(e)}))}}},critical:function(){if(!M.isUndefined(_)&&_){var e=["Moesif error:"].concat(M.toArray(arguments));try{_.error.apply(_,e)}catch(t){M.each(e,(function(e){_.error(e)}))}}}},R=function(e,t){return function(){return arguments[0]="["+t+"] "+arguments[0],e.apply(T,arguments)}},C=function(e){return{log:R(T.log,e),error:R(T.error,e),critical:R(T.critical,e)}};M.bind=function(e,t){var r,n;if(E&&e.bind===E)return E.apply(e,m.call(arguments,1));if(!M.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 o={};o.prototype=e.prototype;var i=new o;o.prototype=null;var s=e.apply(i,r.concat(m.call(arguments)));return Object(s)===s?s:i}},M.bind_instance_methods=function(e){for(var t in e)"function"==typeof e[t]&&(e[t]=M.bind(e[t],e))},M.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,o=e.length;n/g,">").replace(/"/g,""").replace(/'/g,"'")),t},M.extend=function(e){return M.each(m.call(arguments,1),(function(t){for(var r in t)void 0!==t[r]&&(e[r]=t[r])})),e},M.isArray=B||function(e){return"[object Array]"===v.call(e)},M.isFunction=function(e){try{return/^\s*\bfunction\b/.test(e)}catch(e){return!1}},M.isArguments=function(e){return!(!e||!y.call(e,"callee"))},M.toArray=function(e){return e?e.toArray?e.toArray():M.isArray(e)||M.isArguments(e)?m.call(e):M.values(e):[]},M.map=function(e,t){if(q&&e.map===q)return e.map(t);var r=[];return M.each(e,(function(e){r.push(t(e))})),r},M.keys=function(e){var t=[];return null===e||M.each(e,(function(e,r){t[t.length]=r})),t},M.values=function(e){var t=[];return null===e||M.each(e,(function(e){t[t.length]=e})),t},M.identity=function(e){return e},M.include=function(e,t){var r=!1;return null===e?r:x&&e.indexOf===x?-1!=e.indexOf(t):(M.each(e,(function(e){if(r||(r=e===t))return A})),r)},M.includes=function(e,t){return-1!==e.indexOf(t)},M.inherit=function(e,t){return e.prototype=new t,e.prototype.constructor=e,e.superclass=t.prototype,e},M.isArrayBuffer=function(e){var t=Object.prototype.toString;return"function"==typeof ArrayBuffer&&(e instanceof ArrayBuffer||"[object ArrayBuffer]"===t.call(e))},M.isObject=function(e){return e===Object(e)&&!M.isArray(e)},M.isEmptyObject=function(e){if(M.isObject(e)){for(var t in e)if(y.call(e,t))return!1;return!0}return!1},M.isEmptyString=function(e){return!e||0===e.length},M.isUndefined=function(e){return void 0===e},M.isString=function(e){return"[object String]"==v.call(e)},M.isDate=function(e){return"[object Date]"==v.call(e)},M.isNumber=function(e){return"[object Number]"==v.call(e)},M.isElement=function(e){return!(!e||1!==e.nodeType)},M.encodeDates=function(e){return M.each(e,(function(t,r){M.isDate(t)?e[r]=M.formatDate(t):M.isObject(t)&&(e[r]=M.encodeDates(t))})),e},M.timestamp=function(){return Date.now=Date.now||function(){return+new Date},Date.now()},M.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())},M.safewrap=function(e){return function(){try{return e.apply(this,arguments)}catch(e){T.critical("Implementation error. Please turn on debug and contact support@Moesif.com."),t.DEBUG&&T.critical(e)}}},M.safewrap_class=function(e,t){for(var r=0;r0&&(t[r]=e)})),t},M.truncate=function(e,t){var r;return"string"==typeof e?r=e.slice(0,t):M.isArray(e)?(r=[],M.each(e,(function(e){r.push(M.truncate(e,t))}))):M.isObject(e)?(r={},M.each(e,(function(e,n){r[n]=M.truncate(e,t)}))):r=e,r},M.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 o="",i=0,s="",a="",c=0,u=o,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(o+=" ",l=[],"[object Array]"===v.apply(f)){for(c=f.length,i=0;i="0"&&o<="9";)t+=o,u();if("."===o)for(t+=".";u()&&o>="0"&&o<="9";)t+=o;if("e"===o||"E"===o)for(t+=o,u(),"-"!==o&&"+"!==o||(t+=o,u());o>="0"&&o<="9";)t+=o,u();if(e=+t,isFinite(e))return e;c("Bad number")},f=function(){var e,t,r,n="";if('"'===o)for(;u();){if('"'===o)return u(),n;if("\\"===o)if(u(),"u"===o){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[o])break;n+=a[o]}else n+=o}c("Bad string")},d=function(){for(;o&&o<=" ";)u()},s=function(){switch(d(),o){case"{":return function(){var e,t={};if("{"===o){if(u("{"),d(),"}"===o)return u("}"),t;for(;o;){if(e=f(),d(),u(":"),Object.hasOwnProperty.call(t,e)&&c('Duplicate key "'+e+'"'),t[e]=s(),d(),"}"===o)return u("}"),t;u(","),d()}}c("Bad object")}();case"[":return function(){var e=[];if("["===o){if(u("["),d(),"]"===o)return u("]"),e;for(;o;){if(e.push(s()),d(),"]"===o)return u("]"),e;u(","),d()}}c("Bad array")}();case'"':return f();case"-":return l();default:return o>="0"&&o<="9"?l():function(){switch(o){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 "'+o+'"')}()}},function(e){var t;return i=e,n=0,o=" ",t=s(),d(),o&&c("Syntax error"),t}),M.base64Encode=function(e){var t,r,n,o,i,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,c=0,u="",l=[];if(!e)return e;e=M.utf8Encode(e);do{t=(i=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,r=i>>12&63,n=i>>6&63,o=63&i,l[c++]=s.charAt(t)+s.charAt(r)+s.charAt(n)+s.charAt(o)}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&&(i+=e.substring(t,r)),i+=a,t=r=o+1)}return r>t&&(i+=e.substring(t,e.length)),i},M.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=[],o=0;function i(e,t){var r,o=0;for(r=0;r=4&&(o=i(o,n),n=[]);return n.length>0&&(o=i(o,n)),o.toString(16)}()+"-"+e},M.isBlockedUA=function(e){return!!/(google web preview|baiduspider|yandexbot|bingbot|googlebot|yahoo! slurp)/i.test(e)},M.HTTPBuildQuery=function(e,t){var r,n,o=[];return M.isUndefined(t)&&(t="&"),M.each(e,(function(e,t){r=encodeURIComponent(e.toString()),n=encodeURIComponent(t),o[o.length]=n+"="+r})),o.join(t)},M.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," "))},M.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){T.error("Skipping decoding for malformed query param: "+n)}return n.replace(/\+/g," ")},M.getHashParam=function(e,t){var r=e.match(new RegExp(t+"=([^&]*)"));return r?r[1]:null},M.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,o,i,s,a,c,u,l,f,d,h=t.split(" "),p=[w];for(c=0;c-1){i=(o=n.split("#"))[0];var g=o[1],m=w.getElementById(g);if(!m||i&&m.nodeName.toLowerCase()!=i)return[];p=[m]}else if(n.indexOf(".")>-1){i=(o=n.split("."))[0];var v=o[1];for(i||(i="*"),s=[],a=0,u=0;u-1};break;default:_=function(e){return e.getAttribute(b)}}for(p=[],d=0,u=0;u=3?t[2]:""},properties:function(){return M.extend(M.strip_empty_properties({$os:M.info.os(),$browser:M.info.browser(k,b.vendor,S),$referrer:w.referrer,$referring_domain:M.info.referringDomain(w.referrer),$device:M.info.device(k)}),{$current_url:e.location.href,$browser_version:M.info.browserVersion(k,b.vendor,S),$screen_height:I.height,$screen_width:I.width,mp_lib:"web",$lib_version:t.LIB_VERSION,$insert_id:F(),time:M.timestamp()/1e3})},people_properties:function(){return M.extend(M.strip_empty_properties({$os:M.info.os(),$browser:M.info.browser(k,b.vendor,S)}),{$browser_version:M.info.browserVersion(k,b.vendor,S)})},pageviewInfo:function(e){return M.strip_empty_properties({mp_page:e,mp_referrer:w.referrer,mp_browser:M.info.browser(k,b.vendor,S),mp_platform:M.info.os()})}};var F=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=(M.safewrap((function(e,t,r){e+=t;for(var n=5381,o=0;o>>0)%1004||"com"===n||"org"===n)&&(t=N);var o=e.match(t);return o?o[0]:""},H=null,L=null;"undefined"!=typeof JSON&&(H=JSON.stringify,L=JSON.parse),H=H||M.JSONEncode,L=L||M.JSONDecode,M.toArray=M.toArray,M.isObject=M.isObject,M.JSONEncode=M.JSONEncode,M.JSONDecode=M.JSONDecode,M.isBlockedUA=M.isBlockedUA,M.isEmptyObject=M.isEmptyObject,M.isEmptyString=M.isEmptyString,M.info=M.info,M.info.device=M.info.device,M.info.browser=M.info.browser,M.info.browserVersion=M.info.browserVersion,M.info.properties=M.info.properties;var W=C("parsers"),J=function(e){try{return{body:M.JSONDecode(e)}}catch(t){return W.log("JSON decode failed"),W.log(t),{transfer_encoding:"base64",body:M.base64Encode(e)}}},$=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:M.JSONDecode(t)}}catch(e){return W.error(e),{transfer_encoding:"base64",body:M.base64Encode(t)}}}catch(t){return W.error(t),W.log(e),{transfer_encoding:"base64",body:"can not be decoded"}}},Q=C("capture"),K="http:"===(document&&document.location.protocol)?"http://":"https://";function V(e,t,r){Q.log("processResponse for"+e._url);var n=(new Date).toISOString();if(r){var o=e._url?e._url.toLowerCase():e._url;if(o&&o.indexOf("moesif.com")<0&&o.indexOf("apirequest.io")<0){var i={uri:X(e._url),verb:e._method,time:e._startTime,headers:e._requestHeaders};if(t)if("string"==typeof t){Q.log("request post data is string"),Q.log(t);var s=J(t);i.transfer_encoding=s.transfer_encoding,i.body=s.body}else("object"==typeof t||Array.isArray(t)||"number"==typeof t||"boolean"==typeof t)&&(i.body=t);var a=e.getAllResponseHeaders();Q.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=o.substring(0,i);t[s]=o.substring(i+2)}}return t}(a),u=e.status;1223===u&&(u=204);var l={status:u,time:n,headers:c};Q.log("responseType: "+e.responseType),Q.log("responseText: "+e.responseText),Q.log("response: "+e.response);var f=e.responseText,d={};f?(d=J(f),l.body=d.body,l.transfer_encoding=d.transfer_encoding):e.response&&(Q.log("no responseText trying with xhr.response"),M.isString(e.response)?(Q.log("response is string. attempt to parse"),d=J(e.response),l.body=d.body,l.transfer_encoding=d.transfer_encoding):M.isArrayBuffer(e.response)?(Q.log("response is arraybuffer. attempt to parse"),d=$(e.response),l.body=d.body,l.transfer_encoding=d.transfer_encoding):(M.isArray(e.response)||M.isObject(e.response))&&(l.body=e.response)),r({request:i,response:l})}}}function X(e){if(e&&"string"==typeof e){var t=M.trim(e);return 0!==t.indexOf("http")?K+window.location.host+"/"+t.replace(/^\./,"").replace(/^\//,""):e}return e}var G=C("web3capture");function Y(e){return e&&e.host?e.host:"/"}function Z(e,t,r,n,o,i){var s={uri:Y(e),verb:"POST",time:t,headers:{}};if(e.headers){var a={};M.each(e.headers,(function(e){a[e.name]=e.value})),s.headers=a}if(n)if("string"==typeof n){G.log("request post data is string"),G.log(n);try{s.body=M.JSONDecode(n)}catch(e){G.log("JSON decode failed"),G.log(e),s.transfer_encoding="base64",s.body=M.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:{}};o?c.body=o:i&&(c.body={error:i});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 ee(e,t,r){if(e.currentProvider){G.log("found my currentProvider, patching it");var n=e.currentProvider,o=n.send,i=n.sendAsync;return n.send=function(e){G.log("patched send is called"),G.log(e);var r=(new Date).toISOString(),i=o.apply(n,arguments);G.log("patch send result is back"),G.log(i);var s=(new Date).toISOString();return t&&t(Z(n,r,s,e,i)),i},n.sendAsync=function(e,r){G.log("patched sendAsync is called"),G.log(e);var o=(new Date).toISOString(),s=n;i.apply(n,[e,function(n,i){var a=(new Date).toISOString();G.log("inside patched callback"),G.log(i),t&&t(Z(s,o,a,e,i,n)),r&&r(n,i)}])},function(){n.send=o,n.sendAsync=i}}return null}var te=C("capture fetch");function re(e){var t={};te.log("parseheaders is called");for(var r=e.entries(),n=r.next();!n.done;)te.log(n.value),t[n.value[0]]=n.value[1],n=r.next();return t}function ne(e,t,r,n){var o=null;try{o=new Request(r,n)}catch(e){}var i=(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,o){try{setTimeout((function(){if(te.log("interception is here."),te.log(e),te.log(t),e&&t)try{Promise.all([e.arrayBuffer(),t.arrayBuffer()]).then((function(i){var s=i.map($),a=Object.assign(s[0],{uri:e.url,verb:e.method,time:r,headers:re(e.headers)}),c=Object.assign(s[1],{status:t.status,time:n,headers:re(t.headers)});te.log(a),te.log(c),o({request:a,response:c})}))}catch(e){te.error("error processing body")}else te.log("savedRequest")}),50)}catch(e){te.error("error processing saved fetch request and response, but move on anyways."),te.log(e)}}(o,c,i,s,e),t}))}function oe(e){if(M.isEmptyString(e))return null;var t=e.split("/");return t.length>=3?t[2]:null}function ie(){var e=document&&document.referrer;if(!M.isEmptyString(e))return{referrer:e,referring_domain:oe(e)}}var se=C("utm"),ae={UTM_SOURCE:"utm_source",UTM_MEDIUM:"utm_medium",UTM_CAMPAIGN:"utm_campaign",UTM_TERM:"utm_term",UTM_CONTENT:"utm_content"};function ce(e,t){return e=location&&location.search,function(e,t){var r=e?"?"+e.split(".").slice(-1)[0].replace(/\|/g,"&"):"";se.log("cookie"),se.log(r);var n=function(e,t,r,n){return M.getQueryParamByName(e,t)||M.getQueryParamByName(r,n)},o=n(ae.UTM_SOURCE,t,"utmcsr",r),i=n(ae.UTM_MEDIUM,t,"utmcmd",r),s=n(ae.UTM_CAMPAIGN,t,"utmccn",r),a=n(ae.UTM_TERM,t,"utmctr",r),c=n(ae.UTM_CONTENT,t,"utmcct",r),u={},l=function(e,t){M.isEmptyString(t)||(u[e]=t)};return l(ae.UTM_SOURCE,o),l(ae.UTM_MEDIUM,i),l(ae.UTM_CAMPAIGN,s),l(ae.UTM_TERM,a),l(ae.UTM_CONTENT,c),u}(M.cookie.get("__utmz"),e)}var ue="moesif_stored_user_id",le="moesif_stored_company_id",fe="moesif_stored_session_id",de="moesif_anonymous_id",he="moesif_campaign_data";function pe(e,t){return t&&0===e.indexOf("moesif_")?e.replace("moesif_",t):e}function ge(e,t){var r=t&&t.persistence,n=pe(e,t&&t.persistence_key_prefix);if(M.localStorage.is_supported()){var o=M.localStorage.get(n),i=M.cookie.get(n);return!o&&i&&"localStorage"===r&&M.localStorage.set(n,i),o||i}return M.cookie.get(n)}function me(e){var t=e&&e.persistence_key_prefix;M.cookie.remove(pe(ue,t)),M.cookie.remove(pe(le,t)),M.cookie.remove(pe(de,t)),M.cookie.remove(pe(fe,t)),M.cookie.remove(pe(he,t))}function ve(e){var t=e&&e.persistence_key_prefix;M.localStorage.remove(pe(ue,t)),M.localStorage.remove(pe(le,t)),M.localStorage.remove(pe(de,t)),M.localStorage.remove(pe(fe,t)),M.localStorage.remove(pe(he,t))}var ye=C("campaign");function _e(e){try{var t={};if(e.disableUtm||(t=ce()||{}),!e.disableReferer){var r=ie();r&&(t.referrer=r.referrer,t.referring_domain=r.referring_domain)}if(!e.disableRGclid){var n=function(e){var t=M.getQueryParamByName("gclid",e);if(!M.isEmptyString(t))return t}(location&&location.search);n&&(t.gclid=n)}return t}catch(e){ye.log(e)}}function be(e,t){var r=null,n=null;try{(n=ge(he,t))&&"null"!==n&&(r=M.JSONDecode(n))}catch(e){ye.error("failed to decode campaign data "+n),ye.error(e)}var o=_e(t);ye.log("current campaignData"),ye.log(M.JSONEncode(o));var i=function(e,t){if(!t)return e;if(!e)return t;var r=M.extend({},e,t);if(t&&t[ae.UTM_SOURCE])for(var n in ae)r[ae[n]]=t[ae[n]];return r}(r,o);ye.log("merged campaignData"),ye.log(M.JSONEncode(i));try{e&&i&&"null"!==i&&e(he,M.JSONEncode(i))}catch(e){ye.error("failed to persist campaign data"),ye.error(e)}return i}var we=C("lock"),Se=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||window.localStorage,this.pollIntervalMS=t.pollIntervalMS||100,this.timeoutMS=t.timeoutMS||2e3};Se.prototype.withLock=function(e,t,r){r||"function"==typeof t||(r=t,t=null);var n=r||(new Date).getTime()+"|"+Math.random(),o=(new Date).getTime(),i=this.storageKey,s=this.pollIntervalMS,a=this.timeoutMS,c=this.storage,u=i+":X",l=i+":Y",f=i+":Z",d=function(e){t&&t(e)},h=function(e){if((new Date).getTime()-o>a)return we.error("Timeout waiting for mutex on "+i+"; 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 Ie=C("batch"),ke=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||window.localStorage,this.lock=new Se(e,{storage:this.storage}),this.pid=t.pid||null,this.memQueue=[]};ke.prototype.enqueue=function(e,t,r){var n={id:F(),flushAfter:(new Date).getTime()+2*t,payload:e};this.lock.withLock(M.bind((function(){var t;try{var o=this.readFromStorage();o.push(n),(t=this.saveToStorage(o))&&(Ie.log("succeeded saving to storage"),this.memQueue.push(n))}catch(r){Ie.error("Error enqueueing item",e),t=!1}r&&r(t)}),this),(function(e){Ie.error("Error acquiring storage lock",e),r&&r(!1)}),this.pid)},ke.prototype.fillBatch=function(e){var t=this.memQueue.slice(0,e);if(t.lengthi.flushAfter&&!n[i.id]&&(t.push(i),t.length>=e))break}}}return t};var Ee=function(e,t){var r=[];return M.each(e,(function(e){e.id&&!t[e.id]&&r.push(e)})),r};ke.prototype.removeItemsByID=function(e,t){var r={};M.each(e,(function(e){r[e]=!0})),this.memQueue=Ee(this.memQueue,r),this.lock.withLock(M.bind((function(){var n;try{var o=this.readFromStorage();o=Ee(o,r),Ie.log(o.length),n=this.saveToStorage(o)}catch(t){Ie.error("Error removing items",e),n=!1}t&&(Ie.log("triggering callback of removalItems"),t(n))}),this),(function(e){Ie.error("Error acquiring storage lock",e),t&&t(!1)}),this.pid)},ke.prototype.readFromStorage=function(){var e;try{Ie.log("trying to get storage with storage key "+this.storageKey),(e=this.storage.getItem(this.storageKey))?(e=L(e),M.isArray(e)||(Ie.error("Invalid storage entry:",e),e=null)):Ie.log("storageEntry is empty")}catch(t){Ie.error("Error retrieving queue",t),e=null}return e||[]},ke.prototype.saveToStorage=function(e){try{return this.storage.setItem(this.storageKey,H(e)),!0}catch(e){return Ie.error("Error saving queue",e),!1}},ke.prototype.clear=function(){this.memQueue=[],this.storage.removeItem(this.storageKey)};var Oe=C("batch"),xe=function(e,t,r){this.queue=new ke(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};function qe(e){var t=M.UUID();return e&&e(de,t),t}xe.prototype.enqueue=function(e,t){this.queue.enqueue(e,this.flushInterval,t)},xe.prototype.start=function(){this.stopped=!1,this.flush()},xe.prototype.stop=function(){this.stopped=!0,this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null)},xe.prototype.clear=function(){this.queue.clear()},xe.prototype.resetBatchSize=function(){this.batchSize=this.libConfig.batch_size},xe.prototype.resetFlush=function(){this.scheduleFlush(this.libConfig.batch_flush_interval_ms)},xe.prototype.scheduleFlush=function(e){this.flushInterval=e,this.stopped||(this.timeoutID=setTimeout(M.bind(this.flush,this),this.flushInterval))},xe.prototype.flush=function(e){try{if(this.requestInProgress)return void Oe.log("Flush: Request already in progress");e=e||{};var t=this.batchSize,r=this.queue.fillBatch(t);if(Oe.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,o=(new Date).getTime(),i=M.map(r,(function(e){return e.payload})),s=M.bind((function(e){this.requestInProgress=!1;try{var i=!1;if(M.isObject(e)&&"timeout"===e.error&&(new Date).getTime()-o>=n)Oe.error("Network timeout; retrying"),this.flush();else if(M.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),Oe.error("Error; retry in "+s+" ms"),this.scheduleFlush(s)}else if(M.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),Oe.error("413 response; reducing batch size to "+this.batchSize),this.resetFlush()}else Oe.error("Single-event request too large; dropping",r),this.resetBatchSize(),i=!0;else i=!0;i&&this.queue.removeItemsByID(M.map(r,(function(e){return e.id})),M.bind(this.flush,this))}catch(e){Oe.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"),Oe.log("Moesif Request:",this.endpoint,i),this.sendRequest(this.endpoint,i,a,s)}catch(e){Oe.error("Error flushing request queue",e),this.resetFlush()}};var Be="api.moesif.net",Ae="/v1/events",Me="/v1/events/batch",Te="/v1/actions",Re="/v1/actions/batch",Ce="/v1/users",De="/v1/companies",Ue=window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,Pe=(!Ue&&-1===k.indexOf("MSIE")&&k.indexOf("Mozilla"),null);navigator.sendBeacon&&(Pe=function(){return navigator.sendBeacon.apply(navigator,arguments)});var Fe="http:"===(document&&document.location.protocol)?"http://":"https://";function Ne(e){try{return e.request.headers["X-Moesif-SDK"]}catch(e){return!1}}function je(){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-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&&!M.isFunction(e.getTags))throw new Error("getTags should be a function");if(e.getMetadata&&!M.isFunction(e.getMetadata))throw new Error("getMetadata should be a function");if(e.getApiVersion&&!M.isFunction(e.getApiVersion))throw new Error("identifyUser should be a function");if(e.maskContent&&!M.isFunction(e.maskContent))throw new Error("maskContent should be a function");if(e.skip&&!M.isFunction(e.skip))throw new Error("skip should be a function")}(e);var r,n={};n.getTags=e.getTags||function(){},n.maskContent=e.maskContent||function(e){return e},n.getMetadata=e.getMetadata||function(){},n.skip=e.skip||function(){return!1},n.debug=e.debug,n.callback=e.callback,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||Be,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.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&&(T.critical("Unknown persistence type "+r+"; falling back to cookie"),r=t.persistence="localStorage");var n=e.persistence_key_prefix,o=function(t,r){var o=pe(t,n);M.localStorage.set(o,r),M.cookie.set(o,r,e.cookie_expiration,e.cross_subdomain_cookie,e.secure_cookie,e.cross_site_cookie,e.cookie_domain)};return"cookie"!==r&&M.localStorage.is_supported()||(o=function(t,r){var o=pe(t,n);M.cookie.set(o,r,e.cookie_expiration,e.cross_subdomain_cookie,e.secure_cookie,e.cross_site_cookie,e.cookie_domain)}),"none"===r&&(o=function(){}),o}(n);try{this._userId=ge(ue,n),this._session=ge(fe,n),this._companyId=ge(le,n),this._anonymousId=(r=this._persist,ge(de,n)||qe(r)),this._campaign=be(this._persist,n)}catch(e){T.error("error loading saved data from local storage but continue")}return n.batchEnabled&&(U&&Ue?(this.initBatching(),Pe&&window.addEventListener&&window.addEventListener("unload",M.bind((function(){this.requestBatchers.events.flush({sendBeacon:!0})}),this))):(n.batchEnabled=!1,T.log("Turning off batch processing because it needs XHR and localStorage"))),T.log("moesif initiated"),this},_executeRequest:function(e,r,n,o){var i=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",i),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(o){var t=XMLHttpRequest.responseText;o(t)}}else e=a.timeout&&!a.status&&(new Date).getTime()-c>=a.timeout?"timeout":"Bad HTTP status: "+a.status+" "+a.statusText,T.error(e),o&&o({status:0,error:e,xhr_req:a})},a.send(H(r))}catch(e){T.error("failed to send event to moesif"+event.request.uri),T.error(e),o&&o({status:0,error:e})}},initBatching:function(){var e=this._options.applicationId,t=this._options.host;if(T.log("does requestBatch.events exists? "+this.requestBatchers.events),!this.requestBatchers.events){var r={libConfig:this._options,sendRequestFunc:M.bind((function(e,t,r,n){this._executeRequest(e,t,r,n)}),this)},n=new xe("__mf_"+e+"_ev",Fe+t+Me,r),o=new xe("__mf_"+e+"_ac",Fe+t+Re,r);this.requestBatchers={events:n,actions:o}}M.each(this.requestBatchers,(function(e){e.start()}))},_sendOrBatch:function(e,t,r,n,o){var i=!0;if(this._options.batchEnabled&&n)T.log("current batcher storage key is "+n.queue.storageKey),n.enqueue(e);else{var s={applicationId:t};i=this._executeRequest(r,e,s,o)}return i},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,t){var r=XMLHttpRequest.prototype,n=t&&t.eagerBodyLogging,o=r.open,i=r.send,s=r.setRequestHeader;return r.open=function(e,t){return Q.log("XHR open triggered"),this._method=e,this._url=t,this._requestHeaders={},this._startTime=(new Date).toISOString(),o.apply(this,arguments)},r.setRequestHeader=function(e,t){return this._requestHeaders[e]=t,s.apply(this,arguments)},r.send=function(t){Q.log("XHR send started for "+this._url);var r=this;if(n||!this.addEventListener){var o=this.onreadystatechange;this.onreadystatechange=function(){var n=r.readyState;if(Q.log("readyState "+n),n===XMLHttpRequest.DONE&&(Q.log("XHR onreadystatechange DONE triggered for "+r._url),V(r,t,e)),o&&M.isFunction(o))return Q.log("trigger old onreadystatechange"),o.apply(this,arguments)}}else this.addEventListener("loadend",(function(){Q.log("XHR loadend triggered for "+r._url),V(r,t,e)}));return i.apply(this,arguments)},function(){r.open=o,r.send=i,r.setRequestHeader=s}}(r,this._options),this._options.disableFetch||(T.log("also instrumenting fetch API"),this._stopFetchRecording=function(e,t){var r,n=t||window||self;if(n.fetch){if(te.log("found fetch method."),n.fetch.polyfill)return te.log("skip patching fetch since it is polyfilled"),null;var o=n.fetch;return te.log("fetch is not polyfilled so instrumenting it"),n.fetch=(r=n.fetch,function(t,n){return ne(e,r,t,n)}),function(){n.fetch=o}}te.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=ee(e,r,this._options):window.web3&&(T.log("found global web3, will capture from it"),this._stopWeb3Recording=ee(window.web3,r,this._options)),!!this._stopWeb3Recording},updateUser:function(e,t,r,n){this._executeRequest(Fe+r+Ce,e,{applicationId:t},n)},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),r.anonymous_id=this._anonymousId,this.updateUser(r,this._options.applicationId,this._options.host,this._options.callback);try{e&&this._persist(ue,e)}catch(e){T.error("error saving to local storage")}},updateCompany:function(e,t,r,n){this._executeRequest(Fe+r+De,e,{applicationId:t},n)},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.host,this._options.callback);try{e&&this._persist(le,e)}catch(e){T.error("error saving to local storage")}},identifySession:function(e){if(this._session=e,e)try{this._persist(fe,e)}catch(e){T.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},t&&(r.metadata=t);var n=Fe+this._options.host+Te;return T.log("sending or queuing: "+e),this._sendOrBatch(r,this._options.applicationId,n,this.requestBatchers.actions,this._options.callback)},recordEvent:function(e){if(Ne(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():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),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)||Ne(e))T.log("skipped logging for "+e.request.uri);else{T.log("sending or queuing: "+e.request.uri);var n=Fe+this._options.host+Ae;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(){me(this._options)},clearStorage:function(){ve(this._options)},resetAnonymousId:function(){return this._anonymousId=qe(this._persist),this._anonymousId},reset:function(){me(this._options),ve(this._options),this._anonymousId=qe(this._persist),this._companyId=null,this._userId=null,this._session=null,this._campaign=null}}}return je()}()},function(e,t,r){!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,r),o.loaded=!0,o.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,o,i,s,a,c,u,l,f,d,h,p=Array.prototype,g=Function.prototype,m=Object.prototype,v=p.slice,y=m.toString,_=m.hasOwnProperty,b=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,"")}},M={log:function(){if(t&&!A.isUndefined(b)&&b)try{b.log.apply(b,arguments)}catch(e){A.each(arguments,(function(e){b.log(e)}))}},error:function(){if(t&&!A.isUndefined(b)&&b){var e=["Moesif error:"].concat(A.toArray(arguments));try{b.error.apply(b,e)}catch(t){A.each(e,(function(e){b.error(e)}))}}},critical:function(){if(!A.isUndefined(b)&&b){var e=["Moesif error:"].concat(A.toArray(arguments));try{b.error.apply(b,e)}catch(t){A.each(e,(function(e){b.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 o={};o.prototype=e.prototype;var i=new o;o.prototype=null;var s=e.apply(i,r.concat(v.call(arguments)));return Object(s)===s?s:i}},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,o=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||!_.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(_.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){M.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 o="",i=0,s="",a="",c=0,u=o,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(o+=" ",l=[],"[object Array]"===y.apply(f)){for(c=f.length,i=0;i="0"&&i<="9";)t+=i,l();if("."===i)for(t+=".";l()&&i>="0"&&i<="9";)t+=i;if("e"===i||"E"===i)for(t+=i,l(),"-"!==i&&"+"!==i||(t+=i,l());i>="0"&&i<="9";)t+=i,l();if(e=+t,isFinite(e))return e;u("Bad number")},d=function(){var e,t,r,n="";if('"'===i)for(;l();){if('"'===i)return l(),n;if("\\"===i)if(l(),"u"===i){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[i])break;n+=c[i]}else n+=i}u("Bad string")},h=function(){for(;i&&i<=" ";)l()},a=function(){switch(h(),i){case"{":return function(){var e,t={};if("{"===i){if(l("{"),h(),"}"===i)return l("}"),t;for(;i;){if(e=d(),h(),l(":"),Object.hasOwnProperty.call(t,e)&&u('Duplicate key "'+e+'"'),t[e]=a(),h(),"}"===i)return l("}"),t;l(","),h()}}u("Bad object")}();case"[":return function(){var e=[];if("["===i){if(l("["),h(),"]"===i)return l("]"),e;for(;i;){if(e.push(a()),h(),"]"===i)return l("]"),e;l(","),h()}}u("Bad array")}();case'"':return d();case"-":return f();default:return i>="0"&&i<="9"?f():function(){switch(i){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 "'+i+'"')}()}},function(e){var t;return s=e,o=0,i=" ",t=a(),h(),i&&u("Syntax error"),t}),A.base64Encode=function(e){var t,r,n,o,i,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,c=0,u="",l=[];if(!e)return e;e=A.utf8Encode(e);do{t=(i=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,r=i>>12&63,n=i>>6&63,o=63&i,l[c++]=s.charAt(t)+s.charAt(r)+s.charAt(n)+s.charAt(o)}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&&(i+=e.substring(t,r)),i+=a,t=r=o+1)}return r>t&&(i+=e.substring(t,e.length)),i},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=[],o=0;function i(e,t){var r,o=0;for(r=0;r=4&&(o=i(o,n),n=[]);return n.length>0&&(o=i(o,n)),o.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,o=[];return A.isUndefined(t)&&(t="&"),A.each(e,(function(e,t){r=encodeURIComponent(e.toString()),n=encodeURIComponent(t),o[o.length]=n+"="+r})),o.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,o,i,s,a,c,u,l,f,d,h=t.split(" "),p=[S];for(c=0;c-1){i=(o=n.split("#"))[0];var g=o[1],m=S.getElementById(g);if(!m||i&&m.nodeName.toLowerCase()!=i)return[];p=[m]}else if(n.indexOf(".")>-1){i=(o=n.split("."))[0];var v=o[1];for(i||(i="*"),s=[],a=0,u=0;u-1};break;default:_=function(e){return e.getAttribute(b)}}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(M,arguments)}},U=function(e){return{log:D(M.log,e),error:D(M.error,e),critical:D(M.critical,e)}},P=null,F=null;"undefined"!=typeof JSON&&(P=JSON.stringify,F=JSON.parse),P=P||A.JSONEncode,F=F||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[o.substring(0,i)]=o.substring(i+2))}return t}function H(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 L=U("web3capture");function W(e){return e&&e.host?e.host:"/"}function J(e,t,r,n,o,i){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){L.log("request post data is string"),L.log(n);try{s.body=A.JSONDecode(n)}catch(e){L.log("JSON decode failed"),L.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:{}};o?c.body=o:i&&(c.body={error:i});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){L.log("found my currentProvider, patching it");var n=e.currentProvider,o=n.send,i=n.sendAsync;return n.send=function(e){L.log("patched send is called"),L.log(e);var r=(new Date).toISOString(),i=o.apply(n,arguments);L.log("patch send result is back"),L.log(i);var s=(new Date).toISOString();return t&&t(J(n,r,s,e,i)),i},n.sendAsync=function(e,r){L.log("patched sendAsync is called"),L.log(e);var o=(new Date).toISOString(),s=n;i.apply(n,[e,function(n,i){var a=(new Date).toISOString();L.log("inside patched callback"),L.log(i),t&&t(J(s,o,a,e,i,n)),r&&r(n,i)}])},function(){n.send=o,n.sendAsync=i}}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 o=null;try{o=new Request(r,n)}catch(e){}var i=(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,o){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(i){var s=i.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),o({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)}}(o,c,i,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",oe="utm_content";function ie(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)},o=n(ee,t,"utmcsr",r),i=n(te,t,"utmcmd",r),s=n(re,t,"utmccn",r),a=n(ne,t,"utmctr",r),c=n(oe,t,"utmcct",r),u={},l=function(e,t){A.isEmptyString(t)||(u[e]=t)};return l(ee,o),l(te,i),l(re,s),l(ne,a),l(oe,c),u}(A.cookie.get("__utmz"),e)}var se=U("campaign");function ae(e){try{var t={};if(e.disableUtm||(t=ie()||{}),!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(),o=(new Date).getTime(),i=this.storageKey,s=this.pollIntervalMS,a=this.timeoutMS,c=this.storage,u=i+":X",l=i+":Y",f=i+":Z",d=function(e){t&&t(e)},h=function(e){if((new Date).getTime()-o>a)return ce.error("Timeout waiting for mutex on "+i+"; 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 o=this.readFromStorage();o.push(n),(t=this.saveToStorage(o))&&(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.lengthi.flushAfter&&!n[i.id]&&(t.push(i),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 o=this.readFromStorage();o=de(o,r),le.log(o.length),n=this.saveToStorage(o)}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=F(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 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,o=(new Date).getTime(),i=A.map(r,(function(e){return e.payload})),s=A.bind((function(e){this.requestInProgress=!1;try{var i=!1;if(A.isObject(e)&&"timeout"===e.error&&(new Date).getTime()-o>=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(),i=!0;else i=!0;i&&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,i),this.sendRequest(this.endpoint,i,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",_e="/v1/actions/batch",be="/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 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-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){M.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,M.log("Turning off batch processing because it needs XHR and localStorage"))),M.log("moesif initiated"),this},_executeRequest:function(e,t,n,o){var i=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",i),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(o){var t=XMLHttpRequest.responseText;o(t)}}else e=a.timeout&&!a.status&&(new Date).getTime()-c>=a.timeout?"timeout":"Bad HTTP status: "+a.status+" "+a.statusText,M.error(e),o&&o({status:0,error:e,xhr_req:a})},a.send(P(t))}catch(e){M.error("failed to send event to moesif"+event.request.uri),M.error(e),o&&o({status:0,error:e})}},initBatching:function(){var e=this._options.applicationId;if(M.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+_e,t);this.requestBatchers={events:r,actions:n}}A.each(this.requestBatchers,(function(e){e.start()}))},_sendOrBatch:function(e,t,r,n,o){var i=!0;if(this._options.batch&&n)M.log("current batcher storage key is "+n.queue.storageKey),n.enqueue(e);else{var s={applicationId:t};i=this._executeRequest(r,e,s,o)}return i},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){var t=XMLHttpRequest.prototype,r=t.open,n=t.send,o=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,o.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 o={uri:H(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{o.body=A.JSONDecode(t)}catch(e){N.log("JSON decode failed"),N.log(e),o.transfer_encoding="base64",o.body=A.base64Encode(t)}}else("object"==typeof t||Array.isArray(t)||"number"==typeof t||"boolean"==typeof t)&&(o.body=t);var i=z(this.getAllResponseHeaders()),s={status:this.status,time:r,headers:i};if(this.responseText)try{s.body=A.JSONDecode(this.responseText)}catch(e){s.transfer_encoding="base64",s.body=A.base64Encode(this.responseText)}e({request:o,response:s})}}})),n.apply(this,arguments)},function(){t.open=r,t.send=n,t.setRequestHeader=o}}(r),this._options.disableFetch||(M.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 o=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=o}}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&&(M.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+be,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){M.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){M.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 M.log("sending or queuing: "+e),this._sendOrBatch(r,this._options.applicationId,n,this.requestBatchers.actions,this._options.callback)},recordEvent:function(e){if(qe(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()),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))M.log("skipped logging for "+e.request.uri);else{M.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 o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.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 o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));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.2"};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,o,i,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,_=e.console,b=e.navigator,w=e.document,S=e.opera,I=e.screen,k=b.userAgent,E=p.bind,O=h.forEach,x=h.indexOf,q=h.map,B=Array.isArray,A={},M={trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},T={log:function(){if(t.DEBUG&&!M.isUndefined(_)&&_)try{_.log.apply(_,arguments)}catch(e){M.each(arguments,(function(e){_.log(e)}))}},error:function(){if(t.DEBUG&&!M.isUndefined(_)&&_){var e=["Moesif error:"].concat(M.toArray(arguments));try{_.error.apply(_,e)}catch(t){M.each(e,(function(e){_.error(e)}))}}},critical:function(){if(!M.isUndefined(_)&&_){var e=["Moesif error:"].concat(M.toArray(arguments));try{_.error.apply(_,e)}catch(t){M.each(e,(function(e){_.error(e)}))}}}},R=function(e,t){return function(){return arguments[0]="["+t+"] "+arguments[0],e.apply(T,arguments)}},C=function(e){return{log:R(T.log,e),error:R(T.error,e),critical:R(T.critical,e)}};M.bind=function(e,t){var r,n;if(E&&e.bind===E)return E.apply(e,m.call(arguments,1));if(!M.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 o={};o.prototype=e.prototype;var i=new o;o.prototype=null;var s=e.apply(i,r.concat(m.call(arguments)));return Object(s)===s?s:i}},M.bind_instance_methods=function(e){for(var t in e)"function"==typeof e[t]&&(e[t]=M.bind(e[t],e))},M.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,o=e.length;n/g,">").replace(/"/g,""").replace(/'/g,"'")),t},M.extend=function(e){return M.each(m.call(arguments,1),(function(t){for(var r in t)void 0!==t[r]&&(e[r]=t[r])})),e},M.isArray=B||function(e){return"[object Array]"===v.call(e)},M.isFunction=function(e){try{return/^\s*\bfunction\b/.test(e)}catch(e){return!1}},M.isArguments=function(e){return!(!e||!y.call(e,"callee"))},M.toArray=function(e){return e?e.toArray?e.toArray():M.isArray(e)||M.isArguments(e)?m.call(e):M.values(e):[]},M.map=function(e,t){if(q&&e.map===q)return e.map(t);var r=[];return M.each(e,(function(e){r.push(t(e))})),r},M.keys=function(e){var t=[];return null===e||M.each(e,(function(e,r){t[t.length]=r})),t},M.values=function(e){var t=[];return null===e||M.each(e,(function(e){t[t.length]=e})),t},M.identity=function(e){return e},M.include=function(e,t){var r=!1;return null===e?r:x&&e.indexOf===x?-1!=e.indexOf(t):(M.each(e,(function(e){if(r||(r=e===t))return A})),r)},M.includes=function(e,t){return-1!==e.indexOf(t)},M.inherit=function(e,t){return e.prototype=new t,e.prototype.constructor=e,e.superclass=t.prototype,e},M.isArrayBuffer=function(e){var t=Object.prototype.toString;return"function"==typeof ArrayBuffer&&(e instanceof ArrayBuffer||"[object ArrayBuffer]"===t.call(e))},M.isObject=function(e){return e===Object(e)&&!M.isArray(e)},M.isEmptyObject=function(e){if(M.isObject(e)){for(var t in e)if(y.call(e,t))return!1;return!0}return!1},M.isEmptyString=function(e){return!e||0===e.length},M.isUndefined=function(e){return void 0===e},M.isString=function(e){return"[object String]"==v.call(e)},M.isDate=function(e){return"[object Date]"==v.call(e)},M.isNumber=function(e){return"[object Number]"==v.call(e)},M.isElement=function(e){return!(!e||1!==e.nodeType)},M.encodeDates=function(e){return M.each(e,(function(t,r){M.isDate(t)?e[r]=M.formatDate(t):M.isObject(t)&&(e[r]=M.encodeDates(t))})),e},M.timestamp=function(){return Date.now=Date.now||function(){return+new Date},Date.now()},M.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())},M.safewrap=function(e){return function(){try{return e.apply(this,arguments)}catch(e){T.critical("Implementation error. Please turn on debug and contact support@Moesif.com."),t.DEBUG&&T.critical(e)}}},M.safewrap_class=function(e,t){for(var r=0;r0&&(t[r]=e)})),t},M.truncate=function(e,t){var r;return"string"==typeof e?r=e.slice(0,t):M.isArray(e)?(r=[],M.each(e,(function(e){r.push(M.truncate(e,t))}))):M.isObject(e)?(r={},M.each(e,(function(e,n){r[n]=M.truncate(e,t)}))):r=e,r},M.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 o="",i=0,s="",a="",c=0,u=o,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(o+=" ",l=[],"[object Array]"===v.apply(f)){for(c=f.length,i=0;i="0"&&o<="9";)t+=o,u();if("."===o)for(t+=".";u()&&o>="0"&&o<="9";)t+=o;if("e"===o||"E"===o)for(t+=o,u(),"-"!==o&&"+"!==o||(t+=o,u());o>="0"&&o<="9";)t+=o,u();if(e=+t,isFinite(e))return e;c("Bad number")},f=function(){var e,t,r,n="";if('"'===o)for(;u();){if('"'===o)return u(),n;if("\\"===o)if(u(),"u"===o){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[o])break;n+=a[o]}else n+=o}c("Bad string")},d=function(){for(;o&&o<=" ";)u()},s=function(){switch(d(),o){case"{":return function(){var e,t={};if("{"===o){if(u("{"),d(),"}"===o)return u("}"),t;for(;o;){if(e=f(),d(),u(":"),Object.hasOwnProperty.call(t,e)&&c('Duplicate key "'+e+'"'),t[e]=s(),d(),"}"===o)return u("}"),t;u(","),d()}}c("Bad object")}();case"[":return function(){var e=[];if("["===o){if(u("["),d(),"]"===o)return u("]"),e;for(;o;){if(e.push(s()),d(),"]"===o)return u("]"),e;u(","),d()}}c("Bad array")}();case'"':return f();case"-":return l();default:return o>="0"&&o<="9"?l():function(){switch(o){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 "'+o+'"')}()}},function(e){var t;return i=e,n=0,o=" ",t=s(),d(),o&&c("Syntax error"),t}),M.base64Encode=function(e){var t,r,n,o,i,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,c=0,u="",l=[];if(!e)return e;e=M.utf8Encode(e);do{t=(i=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,r=i>>12&63,n=i>>6&63,o=63&i,l[c++]=s.charAt(t)+s.charAt(r)+s.charAt(n)+s.charAt(o)}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&&(i+=e.substring(t,r)),i+=a,t=r=o+1)}return r>t&&(i+=e.substring(t,e.length)),i},M.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=[],o=0;function i(e,t){var r,o=0;for(r=0;r=4&&(o=i(o,n),n=[]);return n.length>0&&(o=i(o,n)),o.toString(16)}()+"-"+e},M.isBlockedUA=function(e){return!!/(google web preview|baiduspider|yandexbot|bingbot|googlebot|yahoo! slurp)/i.test(e)},M.HTTPBuildQuery=function(e,t){var r,n,o=[];return M.isUndefined(t)&&(t="&"),M.each(e,(function(e,t){r=encodeURIComponent(e.toString()),n=encodeURIComponent(t),o[o.length]=n+"="+r})),o.join(t)},M.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," "))},M.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){T.error("Skipping decoding for malformed query param: "+n)}return n.replace(/\+/g," ")},M.getHashParam=function(e,t){var r=e.match(new RegExp(t+"=([^&]*)"));return r?r[1]:null},M.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,o,i,s,a,c,u,l,f,d,h=t.split(" "),p=[w];for(c=0;c-1){i=(o=n.split("#"))[0];var g=o[1],m=w.getElementById(g);if(!m||i&&m.nodeName.toLowerCase()!=i)return[];p=[m]}else if(n.indexOf(".")>-1){i=(o=n.split("."))[0];var v=o[1];for(i||(i="*"),s=[],a=0,u=0;u-1};break;default:_=function(e){return e.getAttribute(b)}}for(p=[],d=0,u=0;u=3?t[2]:""},properties:function(){return M.extend(M.strip_empty_properties({$os:M.info.os(),$browser:M.info.browser(k,b.vendor,S),$referrer:w.referrer,$referring_domain:M.info.referringDomain(w.referrer),$device:M.info.device(k)}),{$current_url:e.location.href,$browser_version:M.info.browserVersion(k,b.vendor,S),$screen_height:I.height,$screen_width:I.width,mp_lib:"web",$lib_version:t.LIB_VERSION,$insert_id:F(),time:M.timestamp()/1e3})},people_properties:function(){return M.extend(M.strip_empty_properties({$os:M.info.os(),$browser:M.info.browser(k,b.vendor,S)}),{$browser_version:M.info.browserVersion(k,b.vendor,S)})},pageviewInfo:function(e){return M.strip_empty_properties({mp_page:e,mp_referrer:w.referrer,mp_browser:M.info.browser(k,b.vendor,S),mp_platform:M.info.os()})}};var F=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=(M.safewrap((function(e,t,r){e+=t;for(var n=5381,o=0;o>>0)%1004||"com"===n||"org"===n)&&(t=N);var o=e.match(t);return o?o[0]:""},H=null,L=null;"undefined"!=typeof JSON&&(H=JSON.stringify,L=JSON.parse),H=H||M.JSONEncode,L=L||M.JSONDecode,M.toArray=M.toArray,M.isObject=M.isObject,M.JSONEncode=M.JSONEncode,M.JSONDecode=M.JSONDecode,M.isBlockedUA=M.isBlockedUA,M.isEmptyObject=M.isEmptyObject,M.isEmptyString=M.isEmptyString,M.info=M.info,M.info.device=M.info.device,M.info.browser=M.info.browser,M.info.browserVersion=M.info.browserVersion,M.info.properties=M.info.properties;var W=C("parsers"),J=function(e){try{return{body:M.JSONDecode(e)}}catch(t){return W.log("JSON decode failed"),W.log(t),{transfer_encoding:"base64",body:M.base64Encode(e)}}},$=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:M.JSONDecode(t)}}catch(e){return W.error(e),{transfer_encoding:"base64",body:M.base64Encode(t)}}}catch(t){return W.error(t),W.log(e),{transfer_encoding:"base64",body:"can not be decoded"}}},Q=C("capture"),K="http:"===(document&&document.location.protocol)?"http://":"https://";function V(e,t,r){Q.log("processResponse for"+e._url);var n=(new Date).toISOString();if(r){var o=e._url?e._url.toLowerCase():e._url;if(o&&o.indexOf("moesif.com")<0&&o.indexOf("apirequest.io")<0){var i={uri:X(e._url),verb:e._method,time:e._startTime,headers:e._requestHeaders};if(t)if("string"==typeof t){Q.log("request post data is string"),Q.log(t);var s=J(t);i.transfer_encoding=s.transfer_encoding,i.body=s.body}else("object"==typeof t||Array.isArray(t)||"number"==typeof t||"boolean"==typeof t)&&(i.body=t);var a=e.getAllResponseHeaders();Q.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=o.substring(0,i);t[s]=o.substring(i+2)}}return t}(a),u=e.status;1223===u&&(u=204);var l={status:u,time:n,headers:c};Q.log("responseType: "+e.responseType),Q.log("responseText: "+e.responseText),Q.log("response: "+e.response);var f=e.responseText,d={};f?(d=J(f),l.body=d.body,l.transfer_encoding=d.transfer_encoding):e.response&&(Q.log("no responseText trying with xhr.response"),M.isString(e.response)?(Q.log("response is string. attempt to parse"),d=J(e.response),l.body=d.body,l.transfer_encoding=d.transfer_encoding):M.isArrayBuffer(e.response)?(Q.log("response is arraybuffer. attempt to parse"),d=$(e.response),l.body=d.body,l.transfer_encoding=d.transfer_encoding):(M.isArray(e.response)||M.isObject(e.response))&&(l.body=e.response)),r({request:i,response:l})}}}function X(e){if(e&&"string"==typeof e){var t=M.trim(e);return 0!==t.indexOf("http")?K+window.location.host+"/"+t.replace(/^\./,"").replace(/^\//,""):e}return e}var G=C("web3capture");function Y(e){return e&&e.host?e.host:"/"}function Z(e,t,r,n,o,i){var s={uri:Y(e),verb:"POST",time:t,headers:{}};if(e.headers){var a={};M.each(e.headers,(function(e){a[e.name]=e.value})),s.headers=a}if(n)if("string"==typeof n){G.log("request post data is string"),G.log(n);try{s.body=M.JSONDecode(n)}catch(e){G.log("JSON decode failed"),G.log(e),s.transfer_encoding="base64",s.body=M.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:{}};o?c.body=o:i&&(c.body={error:i});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 ee(e,t,r){if(e.currentProvider){G.log("found my currentProvider, patching it");var n=e.currentProvider,o=n.send,i=n.sendAsync;return n.send=function(e){G.log("patched send is called"),G.log(e);var r=(new Date).toISOString(),i=o.apply(n,arguments);G.log("patch send result is back"),G.log(i);var s=(new Date).toISOString();return t&&t(Z(n,r,s,e,i)),i},n.sendAsync=function(e,r){G.log("patched sendAsync is called"),G.log(e);var o=(new Date).toISOString(),s=n;i.apply(n,[e,function(n,i){var a=(new Date).toISOString();G.log("inside patched callback"),G.log(i),t&&t(Z(s,o,a,e,i,n)),r&&r(n,i)}])},function(){n.send=o,n.sendAsync=i}}return null}var te=C("capture fetch");function re(e){var t={};te.log("parseheaders is called");for(var r=e.entries(),n=r.next();!n.done;)te.log(n.value),t[n.value[0]]=n.value[1],n=r.next();return t}function ne(e,t,r,n){var o=null;try{o=new Request(r,n)}catch(e){}var i=(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,o){try{setTimeout((function(){if(te.log("interception is here."),te.log(e),te.log(t),e&&t)try{Promise.all([e.arrayBuffer(),t.arrayBuffer()]).then((function(i){var s=i.map($),a=Object.assign(s[0],{uri:e.url,verb:e.method,time:r,headers:re(e.headers)}),c=Object.assign(s[1],{status:t.status,time:n,headers:re(t.headers)});te.log(a),te.log(c),o({request:a,response:c})}))}catch(e){te.error("error processing body")}else te.log("savedRequest")}),50)}catch(e){te.error("error processing saved fetch request and response, but move on anyways."),te.log(e)}}(o,c,i,s,e),t}))}function oe(e){if(M.isEmptyString(e))return null;var t=e.split("/");return t.length>=3?t[2]:null}function ie(){var e=document&&document.referrer;if(!M.isEmptyString(e))return{referrer:e,referring_domain:oe(e)}}var se=C("utm"),ae={UTM_SOURCE:"utm_source",UTM_MEDIUM:"utm_medium",UTM_CAMPAIGN:"utm_campaign",UTM_TERM:"utm_term",UTM_CONTENT:"utm_content"};function ce(e,t){return e=location&&location.search,function(e,t){var r=e?"?"+e.split(".").slice(-1)[0].replace(/\|/g,"&"):"";se.log("cookie"),se.log(r);var n=function(e,t,r,n){return M.getQueryParamByName(e,t)||M.getQueryParamByName(r,n)},o=n(ae.UTM_SOURCE,t,"utmcsr",r),i=n(ae.UTM_MEDIUM,t,"utmcmd",r),s=n(ae.UTM_CAMPAIGN,t,"utmccn",r),a=n(ae.UTM_TERM,t,"utmctr",r),c=n(ae.UTM_CONTENT,t,"utmcct",r),u={},l=function(e,t){M.isEmptyString(t)||(u[e]=t)};return l(ae.UTM_SOURCE,o),l(ae.UTM_MEDIUM,i),l(ae.UTM_CAMPAIGN,s),l(ae.UTM_TERM,a),l(ae.UTM_CONTENT,c),u}(M.cookie.get("__utmz"),e)}var ue="moesif_stored_user_id",le="moesif_stored_company_id",fe="moesif_stored_session_id",de="moesif_anonymous_id",he="moesif_campaign_data";function pe(e,t){return t&&0===e.indexOf("moesif_")?e.replace("moesif_",t):e}function ge(e,t){var r=t&&t.persistence,n=pe(e,t&&t.persistence_key_prefix);if(M.localStorage.is_supported()){var o=M.localStorage.get(n),i=M.cookie.get(n);return!o&&i&&"localStorage"===r&&M.localStorage.set(n,i),o||i}return M.cookie.get(n)}function me(e){var t=e&&e.persistence_key_prefix;M.cookie.remove(pe(ue,t)),M.cookie.remove(pe(le,t)),M.cookie.remove(pe(de,t)),M.cookie.remove(pe(fe,t)),M.cookie.remove(pe(he,t))}function ve(e){var t=e&&e.persistence_key_prefix;M.localStorage.remove(pe(ue,t)),M.localStorage.remove(pe(le,t)),M.localStorage.remove(pe(de,t)),M.localStorage.remove(pe(fe,t)),M.localStorage.remove(pe(he,t))}var ye=C("campaign");function _e(e){try{var t={};if(e.disableUtm||(t=ce()||{}),!e.disableReferer){var r=ie();r&&(t.referrer=r.referrer,t.referring_domain=r.referring_domain)}if(!e.disableRGclid){var n=function(e){var t=M.getQueryParamByName("gclid",e);if(!M.isEmptyString(t))return t}(location&&location.search);n&&(t.gclid=n)}return t}catch(e){ye.log(e)}}function be(e,t){var r=null,n=null;try{(n=ge(he,t))&&"null"!==n&&(r=M.JSONDecode(n))}catch(e){ye.error("failed to decode campaign data "+n),ye.error(e)}var o=_e(t);ye.log("current campaignData"),ye.log(M.JSONEncode(o));var i=function(e,t){if(!t)return e;if(!e)return t;var r=M.extend({},e,t);if(t&&t[ae.UTM_SOURCE])for(var n in ae)r[ae[n]]=t[ae[n]];return r}(r,o);ye.log("merged campaignData"),ye.log(M.JSONEncode(i));try{e&&i&&"null"!==i&&e(he,M.JSONEncode(i))}catch(e){ye.error("failed to persist campaign data"),ye.error(e)}return i}var we=C("lock"),Se=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||window.localStorage,this.pollIntervalMS=t.pollIntervalMS||100,this.timeoutMS=t.timeoutMS||2e3};Se.prototype.withLock=function(e,t,r){r||"function"==typeof t||(r=t,t=null);var n=r||(new Date).getTime()+"|"+Math.random(),o=(new Date).getTime(),i=this.storageKey,s=this.pollIntervalMS,a=this.timeoutMS,c=this.storage,u=i+":X",l=i+":Y",f=i+":Z",d=function(e){t&&t(e)},h=function(e){if((new Date).getTime()-o>a)return we.error("Timeout waiting for mutex on "+i+"; 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 Ie=C("batch"),ke=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||window.localStorage,this.lock=new Se(e,{storage:this.storage}),this.pid=t.pid||null,this.memQueue=[]};ke.prototype.enqueue=function(e,t,r){var n={id:F(),flushAfter:(new Date).getTime()+2*t,payload:e};this.lock.withLock(M.bind((function(){var t;try{var o=this.readFromStorage();o.push(n),(t=this.saveToStorage(o))&&(Ie.log("succeeded saving to storage"),this.memQueue.push(n))}catch(r){Ie.error("Error enqueueing item",e),t=!1}r&&r(t)}),this),(function(e){Ie.error("Error acquiring storage lock",e),r&&r(!1)}),this.pid)},ke.prototype.fillBatch=function(e){var t=this.memQueue.slice(0,e);if(t.lengthi.flushAfter&&!n[i.id]&&(t.push(i),t.length>=e))break}}}return t};var Ee=function(e,t){var r=[];return M.each(e,(function(e){e.id&&!t[e.id]&&r.push(e)})),r};ke.prototype.removeItemsByID=function(e,t){var r={};M.each(e,(function(e){r[e]=!0})),this.memQueue=Ee(this.memQueue,r),this.lock.withLock(M.bind((function(){var n;try{var o=this.readFromStorage();o=Ee(o,r),Ie.log(o.length),n=this.saveToStorage(o)}catch(t){Ie.error("Error removing items",e),n=!1}t&&(Ie.log("triggering callback of removalItems"),t(n))}),this),(function(e){Ie.error("Error acquiring storage lock",e),t&&t(!1)}),this.pid)},ke.prototype.readFromStorage=function(){var e;try{Ie.log("trying to get storage with storage key "+this.storageKey),(e=this.storage.getItem(this.storageKey))?(e=L(e),M.isArray(e)||(Ie.error("Invalid storage entry:",e),e=null)):Ie.log("storageEntry is empty")}catch(t){Ie.error("Error retrieving queue",t),e=null}return e||[]},ke.prototype.saveToStorage=function(e){try{return this.storage.setItem(this.storageKey,H(e)),!0}catch(e){return Ie.error("Error saving queue",e),!1}},ke.prototype.clear=function(){this.memQueue=[],this.storage.removeItem(this.storageKey)};var Oe=C("batch"),xe=function(e,t,r){this.queue=new ke(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};function qe(e){var t=M.UUID();return e&&e(de,t),t}xe.prototype.enqueue=function(e,t){this.queue.enqueue(e,this.flushInterval,t)},xe.prototype.start=function(){this.stopped=!1,this.flush()},xe.prototype.stop=function(){this.stopped=!0,this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null)},xe.prototype.clear=function(){this.queue.clear()},xe.prototype.resetBatchSize=function(){this.batchSize=this.libConfig.batch_size},xe.prototype.resetFlush=function(){this.scheduleFlush(this.libConfig.batch_flush_interval_ms)},xe.prototype.scheduleFlush=function(e){this.flushInterval=e,this.stopped||(this.timeoutID=setTimeout(M.bind(this.flush,this),this.flushInterval))},xe.prototype.flush=function(e){try{if(this.requestInProgress)return void Oe.log("Flush: Request already in progress");e=e||{};var t=this.batchSize,r=this.queue.fillBatch(t);if(Oe.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,o=(new Date).getTime(),i=M.map(r,(function(e){return e.payload})),s=M.bind((function(e){this.requestInProgress=!1;try{var i=!1;if(M.isObject(e)&&"timeout"===e.error&&(new Date).getTime()-o>=n)Oe.error("Network timeout; retrying"),this.flush();else if(M.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),Oe.error("Error; retry in "+s+" ms"),this.scheduleFlush(s)}else if(M.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),Oe.error("413 response; reducing batch size to "+this.batchSize),this.resetFlush()}else Oe.error("Single-event request too large; dropping",r),this.resetBatchSize(),i=!0;else i=!0;i&&this.queue.removeItemsByID(M.map(r,(function(e){return e.id})),M.bind(this.flush,this))}catch(e){Oe.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"),Oe.log("Moesif Request:",this.endpoint,i),this.sendRequest(this.endpoint,i,a,s)}catch(e){Oe.error("Error flushing request queue",e),this.resetFlush()}};var Be="api.moesif.net",Ae="/v1/events",Me="/v1/events/batch",Te="/v1/actions",Re="/v1/actions/batch",Ce="/v1/users",De="/v1/companies",Ue=window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,Pe=(!Ue&&-1===k.indexOf("MSIE")&&k.indexOf("Mozilla"),null);navigator.sendBeacon&&(Pe=function(){return navigator.sendBeacon.apply(navigator,arguments)});var Fe="http:"===(document&&document.location.protocol)?"http://":"https://";function Ne(e){try{return e.request.headers["X-Moesif-SDK"]}catch(e){return!1}}function je(){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-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&&!M.isFunction(e.getTags))throw new Error("getTags should be a function");if(e.getMetadata&&!M.isFunction(e.getMetadata))throw new Error("getMetadata should be a function");if(e.getApiVersion&&!M.isFunction(e.getApiVersion))throw new Error("identifyUser should be a function");if(e.maskContent&&!M.isFunction(e.maskContent))throw new Error("maskContent should be a function");if(e.skip&&!M.isFunction(e.skip))throw new Error("skip should be a function")}(e);var r,n={};n.getTags=e.getTags||function(){},n.maskContent=e.maskContent||function(e){return e},n.getMetadata=e.getMetadata||function(){},n.skip=e.skip||function(){return!1},n.debug=e.debug,n.callback=e.callback,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||Be,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.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&&(T.critical("Unknown persistence type "+r+"; falling back to cookie"),r=t.persistence="localStorage");var n=e.persistence_key_prefix,o=function(t,r){var o=pe(t,n);M.localStorage.set(o,r),M.cookie.set(o,r,e.cookie_expiration,e.cross_subdomain_cookie,e.secure_cookie,e.cross_site_cookie,e.cookie_domain)};return"cookie"!==r&&M.localStorage.is_supported()||(o=function(t,r){var o=pe(t,n);M.cookie.set(o,r,e.cookie_expiration,e.cross_subdomain_cookie,e.secure_cookie,e.cross_site_cookie,e.cookie_domain)}),"none"===r&&(o=function(){}),o}(n);try{if(this._userId=ge(ue,n),this._session=ge(fe,n),this._companyId=ge(le,n),this._anonymousId=(r=this._persist,ge(de,n)||qe(r)),this._campaign=be(this._persist,n),this._campaign&&!this._userId){var o={};o.anonymous_id=this._anonymousId,o.campaign=this._campaign,this.updateUser(o,this._options.applicationId,this._options.host,this._options.callback)}}catch(e){T.error("error loading saved data from local storage but continue")}return n.batchEnabled&&(U&&Ue?(this.initBatching(),Pe&&window.addEventListener&&window.addEventListener("unload",M.bind((function(){this.requestBatchers.events.flush({sendBeacon:!0})}),this))):(n.batchEnabled=!1,T.log("Turning off batch processing because it needs XHR and localStorage"))),T.log("moesif initiated"),this},_executeRequest:function(e,r,n,o){var i=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",i),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(o){var t=XMLHttpRequest.responseText;o(t)}}else e=a.timeout&&!a.status&&(new Date).getTime()-c>=a.timeout?"timeout":"Bad HTTP status: "+a.status+" "+a.statusText,T.error(e),o&&o({status:0,error:e,xhr_req:a})},a.send(H(r))}catch(e){T.error("failed to send event to moesif"+event.request.uri),T.error(e),o&&o({status:0,error:e})}},initBatching:function(){var e=this._options.applicationId,t=this._options.host;if(T.log("does requestBatch.events exists? "+this.requestBatchers.events),!this.requestBatchers.events){var r={libConfig:this._options,sendRequestFunc:M.bind((function(e,t,r,n){this._executeRequest(e,t,r,n)}),this)},n=new xe("__mf_"+e+"_ev",Fe+t+Me,r),o=new xe("__mf_"+e+"_ac",Fe+t+Re,r);this.requestBatchers={events:n,actions:o}}M.each(this.requestBatchers,(function(e){e.start()}))},_sendOrBatch:function(e,t,r,n,o){var i=!0;if(this._options.batchEnabled&&n)T.log("current batcher storage key is "+n.queue.storageKey),n.enqueue(e);else{var s={applicationId:t};i=this._executeRequest(r,e,s,o)}return i},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,t){var r=XMLHttpRequest.prototype,n=t&&t.eagerBodyLogging,o=r.open,i=r.send,s=r.setRequestHeader;return r.open=function(e,t){return Q.log("XHR open triggered"),this._method=e,this._url=t,this._requestHeaders={},this._startTime=(new Date).toISOString(),o.apply(this,arguments)},r.setRequestHeader=function(e,t){return this._requestHeaders[e]=t,s.apply(this,arguments)},r.send=function(t){Q.log("XHR send started for "+this._url);var r=this;if(n||!this.addEventListener){var o=this.onreadystatechange;this.onreadystatechange=function(){var n=r.readyState;if(Q.log("readyState "+n),n===XMLHttpRequest.DONE&&(Q.log("XHR onreadystatechange DONE triggered for "+r._url),V(r,t,e)),o&&M.isFunction(o))return Q.log("trigger old onreadystatechange"),o.apply(this,arguments)}}else this.addEventListener("loadend",(function(){Q.log("XHR loadend triggered for "+r._url),V(r,t,e)}));return i.apply(this,arguments)},function(){r.open=o,r.send=i,r.setRequestHeader=s}}(r,this._options),this._options.disableFetch||(T.log("also instrumenting fetch API"),this._stopFetchRecording=function(e,t){var r,n=t||window||self;if(n.fetch){if(te.log("found fetch method."),n.fetch.polyfill)return te.log("skip patching fetch since it is polyfilled"),null;var o=n.fetch;return te.log("fetch is not polyfilled so instrumenting it"),n.fetch=(r=n.fetch,function(t,n){return ne(e,r,t,n)}),function(){n.fetch=o}}te.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=ee(e,r,this._options):window.web3&&(T.log("found global web3, will capture from it"),this._stopWeb3Recording=ee(window.web3,r,this._options)),!!this._stopWeb3Recording},updateUser:function(e,t,r,n){this._executeRequest(Fe+r+Ce,e,{applicationId:t},n)},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),r.anonymous_id=this._anonymousId,this.updateUser(r,this._options.applicationId,this._options.host,this._options.callback);try{e&&this._persist(ue,e)}catch(e){T.error("error saving to local storage")}},updateCompany:function(e,t,r,n){this._executeRequest(Fe+r+De,e,{applicationId:t},n)},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.host,this._options.callback);try{e&&this._persist(le,e)}catch(e){T.error("error saving to local storage")}},identifySession:function(e){if(this._session=e,e)try{this._persist(fe,e)}catch(e){T.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},t&&(r.metadata=t);var n=Fe+this._options.host+Te;return T.log("sending or queuing: "+e),this._sendOrBatch(r,this._options.applicationId,n,this.requestBatchers.actions,this._options.callback)},recordEvent:function(e){if(Ne(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():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),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)||Ne(e))T.log("skipped logging for "+e.request.uri);else{T.log("sending or queuing: "+e.request.uri);var n=Fe+this._options.host+Ae;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(){me(this._options)},clearStorage:function(){ve(this._options)},resetAnonymousId:function(){return this._anonymousId=qe(this._persist),this._anonymousId},reset:function(){me(this._options),ve(this._options),this._anonymousId=qe(this._persist),this._companyId=null,this._userId=null,this._session=null,this._campaign=null}}}return je()}()},function(e,t,r){!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,r),o.loaded=!0,o.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,o,i,s,a,c,u,l,f,d,h,p=Array.prototype,g=Function.prototype,m=Object.prototype,v=p.slice,y=m.toString,_=m.hasOwnProperty,b=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,"")}},M={log:function(){if(t&&!A.isUndefined(b)&&b)try{b.log.apply(b,arguments)}catch(e){A.each(arguments,(function(e){b.log(e)}))}},error:function(){if(t&&!A.isUndefined(b)&&b){var e=["Moesif error:"].concat(A.toArray(arguments));try{b.error.apply(b,e)}catch(t){A.each(e,(function(e){b.error(e)}))}}},critical:function(){if(!A.isUndefined(b)&&b){var e=["Moesif error:"].concat(A.toArray(arguments));try{b.error.apply(b,e)}catch(t){A.each(e,(function(e){b.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 o={};o.prototype=e.prototype;var i=new o;o.prototype=null;var s=e.apply(i,r.concat(v.call(arguments)));return Object(s)===s?s:i}},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,o=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||!_.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(_.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){M.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 o="",i=0,s="",a="",c=0,u=o,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(o+=" ",l=[],"[object Array]"===y.apply(f)){for(c=f.length,i=0;i="0"&&i<="9";)t+=i,l();if("."===i)for(t+=".";l()&&i>="0"&&i<="9";)t+=i;if("e"===i||"E"===i)for(t+=i,l(),"-"!==i&&"+"!==i||(t+=i,l());i>="0"&&i<="9";)t+=i,l();if(e=+t,isFinite(e))return e;u("Bad number")},d=function(){var e,t,r,n="";if('"'===i)for(;l();){if('"'===i)return l(),n;if("\\"===i)if(l(),"u"===i){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[i])break;n+=c[i]}else n+=i}u("Bad string")},h=function(){for(;i&&i<=" ";)l()},a=function(){switch(h(),i){case"{":return function(){var e,t={};if("{"===i){if(l("{"),h(),"}"===i)return l("}"),t;for(;i;){if(e=d(),h(),l(":"),Object.hasOwnProperty.call(t,e)&&u('Duplicate key "'+e+'"'),t[e]=a(),h(),"}"===i)return l("}"),t;l(","),h()}}u("Bad object")}();case"[":return function(){var e=[];if("["===i){if(l("["),h(),"]"===i)return l("]"),e;for(;i;){if(e.push(a()),h(),"]"===i)return l("]"),e;l(","),h()}}u("Bad array")}();case'"':return d();case"-":return f();default:return i>="0"&&i<="9"?f():function(){switch(i){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 "'+i+'"')}()}},function(e){var t;return s=e,o=0,i=" ",t=a(),h(),i&&u("Syntax error"),t}),A.base64Encode=function(e){var t,r,n,o,i,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,c=0,u="",l=[];if(!e)return e;e=A.utf8Encode(e);do{t=(i=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,r=i>>12&63,n=i>>6&63,o=63&i,l[c++]=s.charAt(t)+s.charAt(r)+s.charAt(n)+s.charAt(o)}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&&(i+=e.substring(t,r)),i+=a,t=r=o+1)}return r>t&&(i+=e.substring(t,e.length)),i},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=[],o=0;function i(e,t){var r,o=0;for(r=0;r=4&&(o=i(o,n),n=[]);return n.length>0&&(o=i(o,n)),o.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,o=[];return A.isUndefined(t)&&(t="&"),A.each(e,(function(e,t){r=encodeURIComponent(e.toString()),n=encodeURIComponent(t),o[o.length]=n+"="+r})),o.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,o,i,s,a,c,u,l,f,d,h=t.split(" "),p=[S];for(c=0;c-1){i=(o=n.split("#"))[0];var g=o[1],m=S.getElementById(g);if(!m||i&&m.nodeName.toLowerCase()!=i)return[];p=[m]}else if(n.indexOf(".")>-1){i=(o=n.split("."))[0];var v=o[1];for(i||(i="*"),s=[],a=0,u=0;u-1};break;default:_=function(e){return e.getAttribute(b)}}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(M,arguments)}},U=function(e){return{log:D(M.log,e),error:D(M.error,e),critical:D(M.critical,e)}},P=null,F=null;"undefined"!=typeof JSON&&(P=JSON.stringify,F=JSON.parse),P=P||A.JSONEncode,F=F||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[o.substring(0,i)]=o.substring(i+2))}return t}function H(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 L=U("web3capture");function W(e){return e&&e.host?e.host:"/"}function J(e,t,r,n,o,i){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){L.log("request post data is string"),L.log(n);try{s.body=A.JSONDecode(n)}catch(e){L.log("JSON decode failed"),L.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:{}};o?c.body=o:i&&(c.body={error:i});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){L.log("found my currentProvider, patching it");var n=e.currentProvider,o=n.send,i=n.sendAsync;return n.send=function(e){L.log("patched send is called"),L.log(e);var r=(new Date).toISOString(),i=o.apply(n,arguments);L.log("patch send result is back"),L.log(i);var s=(new Date).toISOString();return t&&t(J(n,r,s,e,i)),i},n.sendAsync=function(e,r){L.log("patched sendAsync is called"),L.log(e);var o=(new Date).toISOString(),s=n;i.apply(n,[e,function(n,i){var a=(new Date).toISOString();L.log("inside patched callback"),L.log(i),t&&t(J(s,o,a,e,i,n)),r&&r(n,i)}])},function(){n.send=o,n.sendAsync=i}}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 o=null;try{o=new Request(r,n)}catch(e){}var i=(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,o){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(i){var s=i.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),o({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)}}(o,c,i,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",oe="utm_content";function ie(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)},o=n(ee,t,"utmcsr",r),i=n(te,t,"utmcmd",r),s=n(re,t,"utmccn",r),a=n(ne,t,"utmctr",r),c=n(oe,t,"utmcct",r),u={},l=function(e,t){A.isEmptyString(t)||(u[e]=t)};return l(ee,o),l(te,i),l(re,s),l(ne,a),l(oe,c),u}(A.cookie.get("__utmz"),e)}var se=U("campaign");function ae(e){try{var t={};if(e.disableUtm||(t=ie()||{}),!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(),o=(new Date).getTime(),i=this.storageKey,s=this.pollIntervalMS,a=this.timeoutMS,c=this.storage,u=i+":X",l=i+":Y",f=i+":Z",d=function(e){t&&t(e)},h=function(e){if((new Date).getTime()-o>a)return ce.error("Timeout waiting for mutex on "+i+"; 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 o=this.readFromStorage();o.push(n),(t=this.saveToStorage(o))&&(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.lengthi.flushAfter&&!n[i.id]&&(t.push(i),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 o=this.readFromStorage();o=de(o,r),le.log(o.length),n=this.saveToStorage(o)}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=F(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 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,o=(new Date).getTime(),i=A.map(r,(function(e){return e.payload})),s=A.bind((function(e){this.requestInProgress=!1;try{var i=!1;if(A.isObject(e)&&"timeout"===e.error&&(new Date).getTime()-o>=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(),i=!0;else i=!0;i&&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,i),this.sendRequest(this.endpoint,i,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",_e="/v1/actions/batch",be="/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 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-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){M.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,M.log("Turning off batch processing because it needs XHR and localStorage"))),M.log("moesif initiated"),this},_executeRequest:function(e,t,n,o){var i=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",i),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(o){var t=XMLHttpRequest.responseText;o(t)}}else e=a.timeout&&!a.status&&(new Date).getTime()-c>=a.timeout?"timeout":"Bad HTTP status: "+a.status+" "+a.statusText,M.error(e),o&&o({status:0,error:e,xhr_req:a})},a.send(P(t))}catch(e){M.error("failed to send event to moesif"+event.request.uri),M.error(e),o&&o({status:0,error:e})}},initBatching:function(){var e=this._options.applicationId;if(M.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+_e,t);this.requestBatchers={events:r,actions:n}}A.each(this.requestBatchers,(function(e){e.start()}))},_sendOrBatch:function(e,t,r,n,o){var i=!0;if(this._options.batch&&n)M.log("current batcher storage key is "+n.queue.storageKey),n.enqueue(e);else{var s={applicationId:t};i=this._executeRequest(r,e,s,o)}return i},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){var t=XMLHttpRequest.prototype,r=t.open,n=t.send,o=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,o.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 o={uri:H(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{o.body=A.JSONDecode(t)}catch(e){N.log("JSON decode failed"),N.log(e),o.transfer_encoding="base64",o.body=A.base64Encode(t)}}else("object"==typeof t||Array.isArray(t)||"number"==typeof t||"boolean"==typeof t)&&(o.body=t);var i=z(this.getAllResponseHeaders()),s={status:this.status,time:r,headers:i};if(this.responseText)try{s.body=A.JSONDecode(this.responseText)}catch(e){s.transfer_encoding="base64",s.body=A.base64Encode(this.responseText)}e({request:o,response:s})}}})),n.apply(this,arguments)},function(){t.open=r,t.send=n,t.setRequestHeader=o}}(r),this._options.disableFetch||(M.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 o=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=o}}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&&(M.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+be,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){M.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){M.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 M.log("sending or queuing: "+e),this._sendOrBatch(r,this._options.applicationId,n,this.requestBatchers.actions,this._options.callback)},recordEvent:function(e){if(qe(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()),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))M.log("skipped logging for "+e.request.uri);else{M.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 1e74c2e..dccbd9b 100644 --- a/moesif.min.js +++ b/moesif.min.js @@ -16,7 +16,7 @@ c.localStorage.get(f),e=c.cookie.get(f);!h&&e&&"localStorage"===d&&c.localStorag null,f=null;try{(f=P(O,b))&&"null"!==f&&(d=c.JSONDecode(f))}catch(h){A.error("failed to decode campaign data "+f),A.error(h)}var e;a:{try{f={};if(!b.disableUtm)var i=void 0,j=void 0,i=location&&location.search,j=c.cookie.get("__utmz"),f=Aa(j,i)||{};if(!b.disableReferer){var g;var l=document&&document.referrer;if(c.isEmptyString(l))g=void 0;else{var m;if(c.isEmptyString(l))m=null;else{var p=l.split("/");m=3<=p.length?p[2]:null}g={referrer:l,referring_domain:m}}if(g)f.referrer=g.referrer,f.referring_domain= g.referring_domain}if(!b.disableRGclid){var k,la=c.getQueryParamByName("gclid",location&&location.search);(k=c.isEmptyString(la)?void 0:la)&&(f.gclid=k)}e=f;break a}catch(n){A.log(n)}e=void 0}A.log("current campaignData");A.log(c.JSONEncode(e));var t;if(e)if(d){d=c.extend({},d,e);if(e&&e[s.UTM_SOURCE])for(t in s)d[s[t]]=e[s[t]];t=d}else t=e;else t=d;A.log("merged campaignData");A.log(c.JSONEncode(t));try{a&&t&&"null"!==t&&a(O,c.JSONEncode(t))}catch(o){A.error("failed to persist campaign data"),A.error(o)}return t} function Y(a){var b=c.UUID();a&&a(M,b);return b}function Da(a,b){var d=P(M,b);return d?d:Y(a)}function ma(a){try{return a.request.headers["X-Moesif-SDK"]}catch(b){return!1}}function Ea(a){if(!a)throw Error("options are required by moesif-browser-js middleware");if(!a.applicationId)throw Error("A moesif application id is required. Please obtain it through your settings at www.moesif.com");if(a.getTags&&!c.isFunction(a.getTags))throw Error("getTags should be a function");if(a.getMetadata&&!c.isFunction(a.getMetadata))throw Error("getMetadata should be a function"); -if(a.getApiVersion&&!c.isFunction(a.getApiVersion))throw Error("identifyUser should be a function");if(a.maskContent&&!c.isFunction(a.maskContent))throw Error("maskContent should be a function");if(a.skip&&!c.isFunction(a.skip))throw Error("skip should be a function");}var G={DEBUG:!1,LIB_VERSION:"1.8.1"},D;if("undefined"===typeof window){var B={hostname:""};D={navigator:{userAgent:""},document:{location:B,referrer:""},screen:{width:0,height:0},location:B}}else D=window;var B=Array.prototype,x=Object.prototype, +if(a.getApiVersion&&!c.isFunction(a.getApiVersion))throw Error("identifyUser should be a function");if(a.maskContent&&!c.isFunction(a.maskContent))throw Error("maskContent should be a function");if(a.skip&&!c.isFunction(a.skip))throw Error("skip should be a function");}var G={DEBUG:!1,LIB_VERSION:"1.8.2"},D;if("undefined"===typeof window){var B={hostname:""};D={navigator:{userAgent:""},document:{location:B,referrer:""},screen:{width:0,height:0},location:B}}else D=window;var B=Array.prototype,x=Object.prototype, H=B.slice,Q=x.toString,T=x.hasOwnProperty,q=D.console,I=D.navigator,y=D.document,R=D.opera,U=D.screen,n=I.userAgent,Z=Function.prototype.bind,na=B.forEach,oa=B.indexOf,pa=B.map,B=Array.isArray,$={},c={trim:function(a){return a.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},k={log:function(){if(G.DEBUG&&!c.isUndefined(q)&&q)try{q.log.apply(q,arguments)}catch(a){c.each(arguments,function(a){q.log(a)})}},error:function(){if(G.DEBUG&&!c.isUndefined(q)&&q){var a=["Moesif error:"].concat(c.toArray(arguments)); try{q.error.apply(q,a)}catch(b){c.each(a,function(a){q.error(a)})}}},critical:function(){if(!c.isUndefined(q)&&q){var a=["Moesif error:"].concat(c.toArray(arguments));try{q.error.apply(q,a)}catch(b){c.each(a,function(a){q.error(a)})}}}},aa=function(a,b){return function(){arguments[0]="["+b+"] "+arguments[0];return a.apply(k,arguments)}},x=function(a){return{log:aa(k.log,a),error:aa(k.error,a),critical:aa(k.critical,a)}};c.bind=function(a,b){var d,f;if(Z&&a.bind===Z)return Z.apply(a,H.call(arguments, 1));if(!c.isFunction(a))throw new TypeError;d=H.call(arguments,2);return f=function(){if(!(this instanceof f))return a.apply(b,d.concat(H.call(arguments)));var c={};c.prototype=a.prototype;var e=new c;c.prototype=null;c=a.apply(e,d.concat(H.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(na&&a.forEach===na)a.forEach(b,d);else if(a.length===+a.length)for(var c= @@ -68,17 +68,18 @@ else{var a=a||{},b=this.batchSize,d=this.queue.fillBatch(b);C.log("current batch d),this.resetBatchSize(),e=!0;else e=!0;e&&this.queue.removeItemsByID(c.map(d,function(a){return a.id}),c.bind(this.flush,this))}catch(n){C.error("Error handling API response",n),this.resetFlush()}},this),j={method:"POST",verbose:!0,ignore_json_errors:!0,timeout_ms:f};if(a.sendBeacon)j.transport="sendBeacon";C.log("Moesif Request:",this.endpoint,e);this.sendRequest(this.endpoint,e,j,i)}}}catch(g){C.error("Error flushing request queue",g),this.resetFlush()}};var ta=window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest;!ta&&-1===n.indexOf("MSIE")&&n.indexOf("Mozilla");var ua=null;navigator.sendBeacon&&(ua=function(){return navigator.sendBeacon.apply(navigator,arguments)});var J="http:"===(document&&document.location.protocol)?"http://":"https://";window.moesif=function(){k.log("moesif object creator is called");return{init:function(a){window||k.critical("Warning, this library need to be initiated on the client side");Ea(a);var b={};b.getTags=a.getTags||function(){};b.maskContent=a.maskContent|| function(a){return a};b.getMetadata=a.getMetadata||function(){};b.skip=a.skip||function(){return!1};b.debug=a.debug;b.callback=a.callback;b.applicationId=a.applicationId;b.apiVersion=a.apiVersion;b.disableFetch=a.disableFetch;b.disableReferrer=a.disableReferrer;b.disableGclid=a.disableGclid;b.disableUtm=a.disableUtm;b.eagerBodyLogging=a.eagerBodyLogging;b.host=a.host||"api.moesif.net";b.batchEnabled=a.batchEnabled||!1;b.batch_size=a.batchSize||25;b.batch_flush_interval_ms=a.batchMaxTime||2500;b.batch_request_timeout_ms= -a.batchTimeout||9E4;b.persistence=a.persistence||"localStorage";b.cross_site_cookie=a.crossSiteCookie||!1;b.cross_subdomain_cookie=!1===a.crossSubdomainCookie?!1:!0;b.cookie_expiration=a.cookieExpiration||365;b.secure_cookie=a.secureCookie||!1;b.cookie_domain=a.cookieDomain||"";b.persistence_key_prefix=a.persistenceKeyPrefix;this.requestBatchers={};this._options=b;this._persist=Ba(b);try{this._userId=P(K,b),this._session=P(N,b),this._companyId=P(L,b),this._anonymousId=Da(this._persist,b),this._campaign= -Ca(this._persist,b)}catch(d){k.error("error loading saved data from local storage but continue")}if(b.batchEnabled)!V||!ta?(b.batchEnabled=!1,k.log("Turning off batch processing because it needs XHR and localStorage")):(this.initBatching(),ua&&window.addEventListener&&window.addEventListener("unload",c.bind(function(){this.requestBatchers.events.flush({sendBeacon:!0})},this)));k.log("moesif initiated");return this},_executeRequest:function(a,b,c,f){var h=c&&c.applicationId||this._options.applicationId, -e=c&&c.method||"POST";try{var i=new XMLHttpRequest;i.open(e,a);i.setRequestHeader("Content-Type","application/json");i.setRequestHeader("X-Moesif-Application-Id",h);i.setRequestHeader("X-Moesif-SDK","moesif-browser-js/"+G.LIB_VERSION);if(c.timeout_ms&&"undefined"!==typeof i.timeout){i.timeout=c.timeout_ms;var j=(new Date).getTime()}i.onreadystatechange=function(){if(4===i.readyState)if(200<=i.status&&300>=i.status)f&&f(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);f&&f({status:0,error:a,xhr_req:i})}};i.send(S(b))}catch(g){k.error("failed to send event to moesif"+event.request.uri),k.error(g),f&&f({status:0,error:g})}},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,c,d){this._executeRequest(a, -b,c,d)},this)},f=new z("__mf_"+a+"_ev",J+b+"/v1/events/batch",d),a=new z("__mf_"+a+"_ac",J+b+"/v1/actions/batch",d);this.requestBatchers={events:f,actions:a}}c.each(this.requestBatchers,function(a){a.start()})},_sendOrBatch:function(a,b,c,f,h){var e=!0;this._options.batchEnabled&&f?(k.log("current batcher storage key is "+f.queue.storageKey),f.enqueue(a)):e=this._executeRequest(c,a,{applicationId:b},h);return e},start:function(a){function b(a){c.recordEvent(a)}var c=this;if(this._stopRecording|| -this._stopWeb3Recording)return k.log("recording has already started, please call stop first."),!1;k.log("moesif starting");this._stopRecording=wa(b,this._options);if(!this._options.disableFetch)k.log("also instrumenting fetch API"),this._stopFetchRecording=za(b);this.useWeb3(a);return!0},useWeb3:function(a){function b(a){c.recordEvent(a)}var c=this;if(this._stopWeb3Recording)this._stopWeb3Recording(),this._stopWeb3Recording=null;if(a)this._stopWeb3Recording=ga(a,b,this._options);else if(window.web3)k.log("found global web3, will capture from it"), -this._stopWeb3Recording=ga(window.web3,b,this._options);return this._stopWeb3Recording?!0:!1},updateUser:function(a,b,c,f){this._executeRequest(J+c+"/v1/users",a,{applicationId:b},f)},identifyUser:function(a,b){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 c={user_id:a};b&&(c.metadata=b);if(this._session)c.session_token=this._session;if(this._campaign)c.campaign=this._campaign;if(this._companyId)c.company_id= -this._companyId;c.anonymous_id=this._anonymousId;this.updateUser(c,this._options.applicationId,this._options.host,this._options.callback);try{a&&this._persist(K,a)}catch(f){k.error("error saving to local storage")}},updateCompany:function(a,b,c,f){this._executeRequest(J+c+"/v1/companies",a,{applicationId:b},f)},identifyCompany:function(a,b,c){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};c&&(f.company_domain=c);b&&(f.metadata=b);if(this._session)f.session_token=this._session;if(this._campaign)f.campaign=this._campaign;this.updateCompany(f,this._options.applicationId,this._options.host,this._options.callback);try{a&&this._persist(L,a)}catch(h){k.error("error saving to local storage")}},identifySession:function(a){if(this._session=a)try{this._persist(N,a)}catch(b){k.error("local storage error")}},track:function(a,b){if(!a)throw Error("track name must have action Name defined"); -var c={action_name:a};if(this._companyId)c.company_id=this._companyId;this._userId?c.user_id=this._userId:c.anonymous_id=this._anonymousId;if(this._session)c.session_token=this._session;c.request={uri:document.location.href,verb:"GET",user_agent_string:navigator.userAgent};b&&(c.metadata=b);var f=J+this._options.host+"/v1/actions";k.log("sending or queuing: "+a);return this._sendOrBatch(c,this._options.applicationId,f,this.requestBatchers.actions,this._options.callback)},recordEvent:function(a){if(ma(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;this._options.maskContent&&(b=this._options.maskContent(b));if(this._options.getMetadata)if(b.metadata){var c=this._options.getMetadata(b); -b.metadata=Object.assign(b.metadata,c)}else b.metadata=this._options.getMetadata(b);!this._options.skip(a)&&!ma(a)?(k.log("sending or queuing: "+a.request.uri),this._sendOrBatch(b,this._options.applicationId,J+this._options.host+"/v1/events",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(){ja(this._options)},clearStorage:function(){ka(this._options)},resetAnonymousId:function(){return this._anonymousId=Y(this._persist)},reset:function(){ja(this._options);ka(this._options);this._anonymousId=Y(this._persist);this._campaign=this._session=this._userId=this._companyId=null}}}()})(); +a.batchTimeout||9E4;b.persistence=a.persistence||"localStorage";b.cross_site_cookie=a.crossSiteCookie||!1;b.cross_subdomain_cookie=!1===a.crossSubdomainCookie?!1:!0;b.cookie_expiration=a.cookieExpiration||365;b.secure_cookie=a.secureCookie||!1;b.cookie_domain=a.cookieDomain||"";b.persistence_key_prefix=a.persistenceKeyPrefix;this.requestBatchers={};this._options=b;this._persist=Ba(b);try{if(this._userId=P(K,b),this._session=P(N,b),this._companyId=P(L,b),this._anonymousId=Da(this._persist,b),(this._campaign= +Ca(this._persist,b))&&!this._userId)a={},a.anonymous_id=this._anonymousId,a.campaign=this._campaign,this.updateUser(a,this._options.applicationId,this._options.host,this._options.callback)}catch(d){k.error("error loading saved data from local storage but continue")}if(b.batchEnabled)!V||!ta?(b.batchEnabled=!1,k.log("Turning off batch processing because it needs XHR and localStorage")):(this.initBatching(),ua&&window.addEventListener&&window.addEventListener("unload",c.bind(function(){this.requestBatchers.events.flush({sendBeacon:!0})}, +this)));k.log("moesif initiated");return this},_executeRequest:function(a,b,c,f){var h=c&&c.applicationId||this._options.applicationId,e=c&&c.method||"POST";try{var i=new XMLHttpRequest;i.open(e,a);i.setRequestHeader("Content-Type","application/json");i.setRequestHeader("X-Moesif-Application-Id",h);i.setRequestHeader("X-Moesif-SDK","moesif-browser-js/"+G.LIB_VERSION);if(c.timeout_ms&&"undefined"!==typeof i.timeout){i.timeout=c.timeout_ms;var j=(new Date).getTime()}i.onreadystatechange=function(){if(4=== +i.readyState)if(200<=i.status&&300>=i.status)f&&f(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);f&&f({status:0,error:a,xhr_req:i})}};i.send(S(b))}catch(g){k.error("failed to send event to moesif"+event.request.uri),k.error(g),f&&f({status:0,error:g})}},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,c,d){this._executeRequest(a,b,c,d)},this)},f=new z("__mf_"+a+"_ev",J+b+"/v1/events/batch",d),a=new z("__mf_"+a+"_ac",J+b+"/v1/actions/batch",d);this.requestBatchers={events:f,actions:a}}c.each(this.requestBatchers,function(a){a.start()})},_sendOrBatch:function(a,b,c,f,h){var e=!0;this._options.batchEnabled&&f?(k.log("current batcher storage key is "+f.queue.storageKey),f.enqueue(a)):e=this._executeRequest(c, +a,{applicationId:b},h);return e},start:function(a){function b(a){c.recordEvent(a)}var c=this;if(this._stopRecording||this._stopWeb3Recording)return k.log("recording has already started, please call stop first."),!1;k.log("moesif starting");this._stopRecording=wa(b,this._options);if(!this._options.disableFetch)k.log("also instrumenting fetch API"),this._stopFetchRecording=za(b);this.useWeb3(a);return!0},useWeb3:function(a){function b(a){c.recordEvent(a)}var c=this;if(this._stopWeb3Recording)this._stopWeb3Recording(), +this._stopWeb3Recording=null;if(a)this._stopWeb3Recording=ga(a,b,this._options);else if(window.web3)k.log("found global web3, will capture from it"),this._stopWeb3Recording=ga(window.web3,b,this._options);return this._stopWeb3Recording?!0:!1},updateUser:function(a,b,c,f){this._executeRequest(J+c+"/v1/users",a,{applicationId:b},f)},identifyUser:function(a,b){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 c={user_id:a};b&&(c.metadata=b);if(this._session)c.session_token=this._session;if(this._campaign)c.campaign=this._campaign;if(this._companyId)c.company_id=this._companyId;c.anonymous_id=this._anonymousId;this.updateUser(c,this._options.applicationId,this._options.host,this._options.callback);try{a&&this._persist(K,a)}catch(f){k.error("error saving to local storage")}},updateCompany:function(a,b,c,f){this._executeRequest(J+c+"/v1/companies",a,{applicationId:b},f)},identifyCompany:function(a,b, +c){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};c&&(f.company_domain=c);b&&(f.metadata=b);if(this._session)f.session_token=this._session;if(this._campaign)f.campaign=this._campaign;this.updateCompany(f,this._options.applicationId,this._options.host,this._options.callback);try{a&&this._persist(L,a)}catch(h){k.error("error saving to local storage")}},identifySession:function(a){if(this._session= +a)try{this._persist(N,a)}catch(b){k.error("local storage error")}},track:function(a,b){if(!a)throw Error("track name must have action Name defined");var c={action_name:a};if(this._companyId)c.company_id=this._companyId;this._userId?c.user_id=this._userId:c.anonymous_id=this._anonymousId;if(this._session)c.session_token=this._session;c.request={uri:document.location.href,verb:"GET",user_agent_string:navigator.userAgent};b&&(c.metadata=b);var f=J+this._options.host+"/v1/actions";k.log("sending or queuing: "+ +a);return this._sendOrBatch(c,this._options.applicationId,f,this.requestBatchers.actions,this._options.callback)},recordEvent:function(a){if(ma(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;this._options.maskContent&&(b=this._options.maskContent(b));if(this._options.getMetadata)if(b.metadata){var c=this._options.getMetadata(b);b.metadata=Object.assign(b.metadata,c)}else b.metadata=this._options.getMetadata(b);!this._options.skip(a)&&!ma(a)?(k.log("sending or queuing: "+a.request.uri),this._sendOrBatch(b,this._options.applicationId,J+this._options.host+"/v1/events",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(){ja(this._options)},clearStorage:function(){ka(this._options)}, +resetAnonymousId:function(){return this._anonymousId=Y(this._persist)},reset:function(){ja(this._options);ka(this._options);this._anonymousId=Y(this._persist);this._campaign=this._session=this._userId=this._companyId=null}}}()})(); })(); diff --git a/package-lock.json b/package-lock.json index b5df664..4437058 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "moesif-browser-js", - "version": "1.8.1", + "version": "1.8.2", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index b0f2c8d..4146151 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "moesif-browser-js", - "version": "1.8.1", + "version": "1.8.2", "description": "Moesif AJAX Client Javascript. This is designed to log and capture AJAX REST API calls from web apps for error analysis in Moesif.", "main": "build/moesif.cjs.js", "directories": { diff --git a/src/config.js b/src/config.js index f095de2..e4af9a7 100644 --- a/src/config.js +++ b/src/config.js @@ -1,6 +1,6 @@ var Config = { DEBUG: false, - LIB_VERSION: '1.8.1' + LIB_VERSION: '1.8.2' }; export default Config; diff --git a/src/moesif.js b/src/moesif.js index c5d2a0d..9ff5bd5 100644 --- a/src/moesif.js +++ b/src/moesif.js @@ -164,6 +164,17 @@ export default function () { this._companyId = getFromPersistence(STORAGE_CONSTANTS.STORED_COMPANY_ID, ops); this._anonymousId = getAnonymousId(this._persist, ops); 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) { + var anonUserObject = {}; + anonUserObject['anonymous_id'] = this._anonymousId; + anonUserObject['campaign'] = this._campaign; + this.updateUser(anonUserObject, this._options.applicationId, this._options.host, this._options.callback); + } } catch(err) { console.error('error loading saved data from local storage but continue'); }