1 line
56 KiB
JavaScript
1 line
56 KiB
JavaScript
"use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}var Config={LIB_VERSION:"3.0.1",LIB_NAME:"MG"},_={},ArrayProto=Array.prototype,ObjProto=Object.prototype,slice=ArrayProto.slice,nativeToString=ObjProto.toString,nativeHasOwnProperty=Object.prototype.hasOwnProperty,nativeForEach=ArrayProto.forEach,nativeIsArray=Array.isArray,breaker={},utmTypes=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"];_.each=function(e,t,n){if(null==e)return!1;if(nativeForEach&&e.forEach===nativeForEach)e.forEach(t,n);else if(e.length===+e.length){for(var i=0,r=e.length;i<r;i++)if(i in e&&t.call(n,e[i],i,e)===breaker)return!1}else for(var a in e)if(nativeHasOwnProperty.call(e,a)&&t.call(n,e[a],a,e)===breaker)return!1},_.extend=function(n){return _.each(slice.call(arguments,1),function(e){for(var t in e)void 0!==e[t]&&(n[t]=e[t])}),n},_.extend2Layers=function(n){return _.each(slice.call(arguments,1),function(e){for(var t in e)void 0!==e[t]&&(_.isObject(e[t])&&_.isObject(n[t])?_.extend(n[t],e[t]):n[t]=e[t])}),n},_.isArray=nativeIsArray||function(e){return"[object Array]"===nativeToString.call(e)},_.isFunction=function(e){try{return"function"==typeof e}catch(e){return!1}},_.isPromise=function(e){return"[object Promise]"===nativeToString.call(e)&&null!=e},_.isObject=function(e){return"[object Object]"===nativeToString.call(e)&&null!=e},_.isEmptyObject=function(e){if(_.isObject(e)){for(var t in e)if(nativeHasOwnProperty.call(e,t))return!1;return!0}return!1},_.isUndefined=function(e){return void 0===e},_.isString=function(e){return"[object String]"===nativeToString.call(e)},_.isDate=function(e){return"[object Date]"===nativeToString.call(e)},_.isBoolean=function(e){return"[object Boolean]"===nativeToString.call(e)},_.isNumber=function(e){return"[object Number]"===nativeToString.call(e)&&/[\d\.]+/.test(String(e))},_.isJSONString=function(e){try{JSON.parse(e)}catch(e){return!1}return!0},_.decodeURIComponent=function(t){var n="";try{n=decodeURIComponent(t)}catch(e){n=t}return n},_.encodeURIComponent=function(t){var n="";try{n=encodeURIComponent(t)}catch(e){n=t}return n},_.utf8Encode=function(e){for(var t,n="",i=t=0,r=(e=(e+"").replace(/\r\n/g,"\n").replace(/\r/g,"\n")).length,a=0;a<r;a++){var s=e.charCodeAt(a),o=null;s<128?t++:o=127<s&&s<2048?String.fromCharCode(s>>6|192,63&s|128):String.fromCharCode(s>>12|224,s>>6&63|128,63&s|128),null!==o&&(i<t&&(n+=e.substring(i,t)),n+=o,i=t=a+1)}return i<t&&(n+=e.substring(i,e.length)),n},_.base64Encode=function(e){var t,n,i,r,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",s=0,o=0,c="",u=[];if(!e)return e;for(e=_.utf8Encode(e);t=(r=e.charCodeAt(s++)<<16|e.charCodeAt(s++)<<8|e.charCodeAt(s++))>>18&63,n=r>>12&63,i=r>>6&63,r=63&r,u[o++]=a.charAt(t)+a.charAt(n)+a.charAt(i)+a.charAt(r),s<e.length;);switch(c=u.join(""),e.length%3){case 1:c=c.slice(0,-2)+"==";break;case 2:c=c.slice(0,-1)+"="}return c},_.encodeDates=function(i){return _.each(i,function(e,t){if(_.isDate(e))i[t]=_.formatDate(e);else if(_.isObject(e))i[t]=_.encodeDates(e);else if(_.isArray(e))for(var n=0;n<e.length;n++)_.isDate(e[n])&&(i[t][n]=_.formatDate(e[n]))}),i},_.formatDate=function(e){function t(e){return e<10?"0"+e:e}return e.getFullYear()+"-"+t(e.getMonth()+1)+"-"+t(e.getDate())+" "+t(e.getHours())+":"+t(e.getMinutes())+":"+t(e.getSeconds())+"."+((n=e.getMilliseconds())<100&&9<n?"0"+n:n<10?"00"+n:n);var n},_.searchObjDate=function(n){try{(_.isObject(n)||_.isArray(n))&&_.each(n,function(e,t){_.isObject(e)||_.isArray(e)?_.searchObjDate(n[t]):_.isDate(e)&&(n[t]=_.formatDate(e))})}catch(e){logger.warn(e)}},_.UUID=function(){var e=(new Date).getTime();return String(Math.random()).replace(".","").slice(1,11)+"-"+e},_.UUIDv4=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})},_.setMpPlatform=function(e){_.mpPlatform=e},_.getMpPlatform=function(){return _.mpPlatform},_.createExtraHeaders=function(){return{"TA-Integration-Type":Config.LIB_NAME,"TA-Integration-Version":Config.LIB_VERSION,"TA-Integration-Count":"1","TA-Integration-Extra":_.getMpPlatform()}},_.checkAppId=function(e){return e=e.replace(/\s*/g,"")},_.checkUrl=function(e){return e=e.replace(/\s*/g,""),e=_.url("basic",e)},_.url=function(){function r(){return new RegExp(/(.*?)\.?([^.]*?)\.(com|net|org|biz|ws|in|me|co\.uk|co|org\.uk|ltd\.uk|plc\.uk|me\.uk|edu|mil|br\.com|cn\.com|eu\.com|hu\.com|no\.com|qc\.com|sa\.com|se\.com|se\.net|us\.com|uy\.com|ac|co\.ac|gv\.ac|or\.ac|ac\.ac|af|am|as|at|ac\.at|co\.at|gv\.at|or\.at|asn\.au|com\.au|edu\.au|org\.au|net\.au|id\.au|be|ac\.be|adm\.br|adv\.br|am\.br|arq\.br|art\.br|bio\.br|cng\.br|cnt\.br|com\.br|ecn\.br|eng\.br|esp\.br|etc\.br|eti\.br|fm\.br|fot\.br|fst\.br|g12\.br|gov\.br|ind\.br|inf\.br|jor\.br|lel\.br|med\.br|mil\.br|net\.br|nom\.br|ntr\.br|odo\.br|org\.br|ppg\.br|pro\.br|psc\.br|psi\.br|rec\.br|slg\.br|tmp\.br|tur\.br|tv\.br|vet\.br|zlg\.br|br|ab\.ca|bc\.ca|mb\.ca|nb\.ca|nf\.ca|ns\.ca|nt\.ca|on\.ca|pe\.ca|qc\.ca|sk\.ca|yk\.ca|ca|cc|ac\.cn|net\.cn|com\.cn|edu\.cn|gov\.cn|org\.cn|bj\.cn|sh\.cn|tj\.cn|cq\.cn|he\.cn|nm\.cn|ln\.cn|jl\.cn|hl\.cn|js\.cn|zj\.cn|ah\.cn|gd\.cn|gx\.cn|hi\.cn|sc\.cn|gz\.cn|yn\.cn|xz\.cn|sn\.cn|gs\.cn|qh\.cn|nx\.cn|xj\.cn|tw\.cn|hk\.cn|mo\.cn|cn|cx|cz|de|dk|fo|com\.ec|tm\.fr|com\.fr|asso\.fr|presse\.fr|fr|gf|gs|co\.il|net\.il|ac\.il|k12\.il|gov\.il|muni\.il|ac\.in|co\.in|org\.in|ernet\.in|gov\.in|net\.in|res\.in|is|it|ac\.jp|co\.jp|go\.jp|or\.jp|ne\.jp|ac\.kr|co\.kr|go\.kr|ne\.kr|nm\.kr|or\.kr|li|lt|lu|asso\.mc|tm\.mc|com\.mm|org\.mm|net\.mm|edu\.mm|gov\.mm|ms|nl|no|nu|pl|ro|org\.ro|store\.ro|tm\.ro|firm\.ro|www\.ro|arts\.ro|rec\.ro|info\.ro|nom\.ro|nt\.ro|se|si|com\.sg|org\.sg|net\.sg|gov\.sg|sk|st|tf|ac\.th|co\.th|go\.th|mi\.th|net\.th|or\.th|tm|to|com\.tr|edu\.tr|gov\.tr|k12\.tr|net\.tr|org\.tr|com\.tw|org\.tw|net\.tw|ac\.uk|uk\.com|uk\.net|gb\.com|gb\.net|vg|sh|kz|ch|info|ua|gov|name|pro|ie|hk|com\.hk|org\.hk|net\.hk|edu\.hk|us|tk|cd|by|ad|lv|eu\.lv|bz|es|jp|cl|ag|mobi|eu|co\.nz|org\.nz|net\.nz|maori\.nz|iwi\.nz|io|la|md|sc|sg|vc|tw|travel|my|se|tv|pt|com\.pt|edu\.pt|asia|fi|com\.ve|net\.ve|fi|org\.ve|web\.ve|info\.ve|co\.ve|tel|im|gr|ru|net\.ru|org\.ru|hr|com\.hr|ly|xyz)$/)}function a(e,t){var n=e.charAt(0),t=t.split(n);return n===e?t:t[(e=parseInt(e.substring(1),10))<0?t.length+e:e-1]}function s(e,t){for(var n,i,r=e.charAt(0),a=t.split("&"),s=[],o={},c=e.substring(1),u=0,l=a.length;u<l;u++)if(""!==(s=(s=a[u].match(/(.*?)=(.*)/))||[a[u],a[u],""])[1].replace(/\s/g,"")){if(s[2]=(i=s[2]||"",_.decodeURIComponent(i.replace(/\+/g," "))),c===s[1])return s[2];(n=s[1].match(/(.*)\[([0-9]+)\]/))?(o[n[1]]=o[n[1]]||[],o[n[1]][n[2]]=s[2]):o[s[1]]=s[2]}return r===e?o:o[c]}return function(e,t){var n={};if("tld?"===e)return r();if(t=t||window.location.toString(),!e)return t;if(e=e.toString(),t.match(/^mailto:([^/].+)/))i=t.match(/^mailto:([^/].+)/),n.protocol="mailto",n.email=i[1];else{if(t.match(/(.*?)\/#!(.*)/)&&(t=(i=t.match(/(.*?)\/#!(.*)/))[1]+i[2]),t.match(/(.*?)#(.*)/)&&(i=t.match(/(.*?)#(.*)/),n.hash=i[2],t=i[1]),n.hash&&e.match(/^#/))return s(e,n.hash);if(t.match(/(.*?)\?(.*)/)&&(i=t.match(/(.*?)\?(.*)/),n.query=i[2],t=i[1]),n.query&&e.match(/^\?/))return s(e,n.query);if(t.match(/(.*?):?\/\/(.*)/)&&(i=t.match(/(.*?):?\/\/(.*)/),n.protocol=i[1].toLowerCase(),t=i[2]),t.match(/(.*?)(\/.*)/)&&(i=t.match(/(.*?)(\/.*)/),n.path=i[2],t=i[1]),n.path=(n.path||"").replace(/^([^/])/,"/$1").replace(/\/$/,""),e.match(/^[-0-9]+$/)&&(e=e.replace(/^([^/])/,"/$1")),e.match(/^\//))return a(e,n.path.substring(1));if((i=(i=a("/-1",n.path.substring(1)))&&i.match(/(.*?)\.(.*)/))&&(n.file=i[0],n.filename=i[1],n.fileext=i[2]),t.match(/(.*):([0-9]+)$/)&&(i=t.match(/(.*):([0-9]+)$/),n.port=i[2],t=i[1]),t.match(/(.*?)@(.*)/)&&(i=t.match(/(.*?)@(.*)/),n.auth=i[1],t=i[2]),n.auth&&(i=n.auth.match(/(.*):(.*)/),n.user=i?i[1]:n.auth,n.pass=i?i[2]:void 0),n.hostname=t.toLowerCase(),"."===e.charAt(0))return a(e,n.hostname);r()&&(i=n.hostname.match(r()))&&(n.tld=i[3],n.domain=i[2]?i[2]+"."+i[3]:void 0,n.sub=i[1]||void 0);var i=n.port?":"+n.port:"";n.protocol=n.protocol||window.location.protocol.replace(":",""),n.port=n.port||("https"===n.protocol?"443":"80"),n.protocol=n.protocol||("443"===n.port?"https":"http"),n.basic=n.protocol+"://"+n.hostname+i}return e in n?n[e]:"{}"===e?n:""}}(),_.createString=function(e){for(var t=e,n=Math.random().toString(36).substr(2);n.length<t;)n+=Math.random().toString(36).substr(2);return n=n.substr(0,e)},_.createAesKey=function(){return _.createString(16)},_.generateEncryptyData=function(e,t){if(void 0===t)return e;var n=t.publicKey,i=t.version;if(void 0===n||void 0===i)return e;if("undefined"==typeof CryptoJS||"undefined"==typeof JSEncrypt)return e;var r=_.createAesKey();try{var a=CryptoJS.enc.Utf8.parse(r),s=CryptoJS.enc.Utf8.parse(JSON.stringify(e)),o=_.isUndefined(CryptoJS.pad.Pkcs7)?CryptoJS.pad.PKCS7:CryptoJS.pad.Pkcs7,a=CryptoJS.AES.encrypt(s,a,{mode:CryptoJS.mode.ECB,padding:o}).toString(),o=new JSEncrypt;o.setPublicKey(n);o=o.encrypt(r);return!1===o?(logger.warn("Encryption failed, return the original data"),e):{pkv:i,ekey:o,payload:a}}catch(e){logger.warn("Encryption failed, return the original data: "+e)}return e},_.getUtm=function(){var n={};return _.each(utmTypes,function(e){try{var t=_.getQueryParam(location.href,e);t.length&&(n[e]=t)}catch(e){logger.warn("get utm fail: "+e)}}),JSON.stringify(n)},_.getQueryParam=function(e,t){t=t.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]"),e=_.decodeURIComponent(e);e=new RegExp("[\\?&]"+t+"=([^&#]*)").exec(e);return null===e||e&&"string"!=typeof e[1]&&e[1].length?"":_.decodeURIComponent(e[1])},_.getUtmFromQuery=function(t){var n={};return _.each(utmTypes,function(e){t[e]&&(n[e]=t[e])}),JSON.stringify(n)},_.indexOf=function(e,t){var n=e.indexOf;if(n)return n.call(e,t);for(var i=0;i<e.length;i++)if(t===e[i])return i;return-1},_.checkCalibration=function(e,t,n){return e};var logger="object"===_typeof(logger)?logger:{};logger.info=function(){if("object"===("undefined"==typeof console?"undefined":_typeof(console))&&console.log&&logger.enabled)try{return arguments[0]="[ThinkingData] Info: "+arguments[0],console.log.apply(console,arguments)}catch(e){console.log("[ThinkingData] Info: "+arguments[0])}},logger.warn=function(){if("object"===("undefined"==typeof console?"undefined":_typeof(console))&&console.log&&logger.enabled)try{return arguments[0]="[ThinkingData] Warning: "+arguments[0],console.warn.apply(console,arguments)}catch(e){console.warn("[ThinkingData] Warning: "+arguments[0])}};var KEY_NAME_MATCH_REGEX=/^[a-zA-Z][a-zA-Z0-9_]{0,49}$/,PropertyChecker=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"stripProperties",value:function(e){return _.isObject(e)&&_.each(e,function(e,t){_.isString(e)||_.isNumber(e)||_.isDate(e)||_.isBoolean(e)||_.isArray(e)||_.isObject(e)||logger.warn("Your data -",t,e,"- format does not meet requirements and may not be stored correctly. Attribute values only support String, Number, Date, Boolean, Array, Object")}),e}},{key:"_checkPropertiesKey",value:function(e){var n=!0;return _.each(e,function(e,t){KEY_NAME_MATCH_REGEX.test(t)||(logger.warn("Invalid KEY: "+t),n=!1)}),n}},{key:"event",value:function(e){return!(!_.isString(e)||!KEY_NAME_MATCH_REGEX.test(e))||(logger.warn("Check the parameter format. The eventName must start with an English letter and contain no more than 50 characters including letters, digits, and underscores: "+e),!1)}},{key:"propertyName",value:function(e){return!(!_.isString(e)||!KEY_NAME_MATCH_REGEX.test(e))||(logger.warn("Check the parameter format. PropertyName must start with a letter and contain letters, digits, and underscores (_). The value is a string of no more than 50 characters: "+e),!1)}},{key:"properties",value:function(e){return this.stripProperties(e),!e||(_.isObject(e)?!!this._checkPropertiesKey(e)||(logger.warn("Check the parameter format. The properties key must start with a letter, contain digits, letters, and underscores (_), and contain a maximum of 50 characters"),!1):(logger.warn("properties can be none, but it must be an object"),!1))}},{key:"propertiesMust",value:function(e){return this.stripProperties(e),void 0===e||!_.isObject(e)||_.isEmptyObject(e)?(logger.warn("properties must be an object with a value"),!1):!!this._checkPropertiesKey(e)||(logger.warn("Check the parameter format. The properties key must start with a letter, contain digits, letters, and underscores (_), and contain a maximum of 50 characters"),!1)}},{key:"userId",value:function(e){return!(!_.isString(e)||!/^.{1,64}$/.test(e))||(logger.warn("The user ID must be a string of less than 64 characters and cannot be null"),!1)}},{key:"userAddProperties",value:function(e){if(!this.propertiesMust(e))return!1;for(var t in e)if(!_.isNumber(e[t]))return logger.warn("The attributes of userAdd need to be Number"),!1;return!0}},{key:"userAppendProperties",value:function(e){if(!this.propertiesMust(e))return!1;for(var t in e)if(!_.isArray(e[t]))return logger.warn("The attribute of userAppend must be Array"),!1;return!0}}]),e}(),PlatformProxy=function(){function e(){_classCallCheck(this,e),this.config={persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_mg"}}return _createClass(e,[{key:"getConfig",value:function(){return this.config}},{key:"getStorage",value:function(e,t,n){e=localStorage.getItem(e);if(!t)return _.isJSONString(e)?JSON.parse(e):{};_.isJSONString(e)?n(JSON.parse(e)):n({})}},{key:"setStorage",value:function(e,t){localStorage.setItem(e,t)}},{key:"removeStorage",value:function(e){localStorage.removeItem(e)}},{key:"_setSystemProxy",value:function(e){this._sysCallback=e}},{key:"getSystemInfo",value:function(e){var t={mp_platform:"web",system:this._getOs(),screenWidth:window.screen.width,screenHeight:window.screen.height,systemLanguage:navigator.language};this._sysCallback&&(t=_.extend(t,this._sysCallback(e))),e.success(t),e.complete()}},{key:"_getOs",value:function(){var e=navigator.userAgent;return/Windows/i.test(e)?/Phone/.test(e)||/WPDesktop/.test(e)?"Windows Phone":"Windows":/(iPhone|iPad|iPod)/.test(e)?"iOS":/Android/.test(e)?"Android":/(BlackBerry|PlayBook|BB10)/i.test(e)?"BlackBerry":/Mac/i.test(e)?"MacOS":/Linux/.test(e)?"Linux":/CrOS/.test(e)?"ChromeOS":""}},{key:"getNetworkType",value:function(e){e.complete()}},{key:"onNetworkStatusChange",value:function(){}},{key:"request",value:function(e){var t={},n=new XMLHttpRequest;if(n.open(e.method,e.url),e.header)for(var i in e.header)n.setRequestHeader(i,e.header[i]);return n.onreadystatechange=function(){4===n.readyState&&200===n.status?(t.statusCode=200,_.isJSONString(n.responseText)&&(t.data=JSON.parse(n.responseText)),e.success(t)):200!==n.status&&(t.errMsg="network error",e.fail(t))},n.ontimeout=function(){t.errMsg="timeout",e.fail(t)},n.send(e.data),n}},{key:"initAutoTrackInstance",value:function(e,t){this.instance=e,this.autoTrack=t.autoTrack;var n=this;n.onPageShow(),n.autoTrack.appHide&&n.instance.timeEvent("ta_page_hide"),"onvisibilitychange"in document&&(document.onvisibilitychange=function(){document.hidden?n.onPageHide(!0):(n.onPageShow(),n.autoTrack.appHide&&n.instance.timeEvent("ta_page_hide"))})}},{key:"setGlobal",value:function(e,t){window[t]=e}},{key:"getAppOptions",value:function(){}},{key:"showToast",value:function(){}},{key:"onPageShow",value:function(){var e;this.autoTrack.appShow&&(e={},_.extend(e,this.autoTrack.properties),_.isFunction(this.autoTrack.callback)&&_.extend(e,this.autoTrack.callback("appShow")),this.instance._internalTrack("ta_page_show",e))}},{key:"onPageHide",value:function(e){var t;this.autoTrack.appHide&&(t={},_.extend(t,this.autoTrack.properties),_.isFunction(this.autoTrack.callback)&&_.extend(t,this.autoTrack.callback("appHide")),this.instance._internalTrack("ta_page_hide",t,new Date,null,e))}}],[{key:"createInstance",value:function(){return new e}}]),e}(),AutoTrackBridge=function(){function n(e,t){_classCallCheck(this,n),this.taInstance=e,this.config=t||{},this.referrer="Directly open",this.config.isPlugin?(e.App=function(){App.apply(this,arguments)},inension(e.Page)):(e=App,App=this._initAppExtention(e),e=Page,Page=this._initPageExtension(e))}return _createClass(n,[{key:"_initPageExtension",value:function(i){var r=this;return function(e){var t=e.onShow,n=e.onShareAppMessage;return e.onShow=function(e){r.onPageShow(),"function"==typeof t&&t.call(this,e)},"function"==typeof n&&(e.onShareAppMessage=function(e){e=n.call(this,e);return r.onPageShare(e)}),i(e)}}},{key:"_initAppExtention",value:function(r){var a=this;return function(e){var t=e.onLaunch,n=e.onShow,i=e.onHide;return e.onLaunch=function(e){a.onAppLaunch(e,this),"function"==typeof t&&t.call(this,e)},e.onShow=function(e){a.onAppShow(e),"function"==typeof n&&n.call(this,e)},e.onHide=function(){a.onAppHide(),"function"==typeof i&&i.call(this)},r(e)}}},{key:"onAppLaunch",value:function(e,t){this._setAutoTrackProperties(e),_.isUndefined(t)||(t[this.taInstance.name]=this.taInstance),this.config.appLaunch&&(t={},e&&e.path&&(t["#url_path"]=this._getPath(e.path)),e&&e.query&&(t["#utm"]=_.getUtmFromQuery(e.query)),this.taInstance._internalTrack("ta_mp_launch",t))}},{key:"onAppShow",value:function(e){var t;this.config.appHide&&this.taInstance.timeEvent("ta_mp_hide"),this._setAutoTrackProperties(e),this.config.appShow&&(t={},e&&e.path&&(t["#url_path"]=this._getPath(e.path)),e&&e.query&&(t["#utm"]=_.getUtmFromQuery(e.query)),_.extend(t,this.config.properties),_.isFunction(this.config.callback)&&_.extend(t,this.config.callback("appShow")),this.taInstance._internalTrack("ta_mp_show",t))}},{key:"onAppHide",value:function(){var e;this.config.appHide&&(e={"#url_path":this._getCurrentPath()},_.extend(e,this.config.properties),_.isFunction(this.config.callback)&&_.extend(e,this.config.callback("appHide")),this.taInstance._internalTrack("ta_mp_hide",e))}},{key:"_getCurrentPath",value:function(){var e="Not to get";try{var t=getCurrentPages(),e=t[t.length-1].route}catch(e){logger.info(e)}return e}},{key:"_setAutoTrackProperties",value:function(e){e={"#scene":e.scene};this.taInstance._setAutoTrackProperties(e)}},{key:"_getPath",value:function(e){return"string"==typeof e?e.replace(/^\//,""):"Abnormal values"}},{key:"onPageShare",value:function(e){return this.config.pageShare&&this.taInstance._internalTrack("ta_mp_share",{"#url_path":this._getCurrentPath()}),_.isObject(e)?e:{}}},{key:"onPageShow",value:function(){var e,t;this.config.pageShow&&(t={"#url_path":(e=this._getCurrentPath())||"The system did not get a value","#referrer":this.referrer},this.referrer=e,this.taInstance._internalTrack("ta_mp_view",t))}}]),n}(),AutoTrackBridge$1=function(){function r(e,t,n){var i=this;_classCallCheck(this,r),this.taInstance=e,this.config=t||{};t=n.getLaunchOptionsSync();this._onShow(t),this.startTracked=!0,n.onShow(function(e){i._onShow(e)}),n.onHide(function(){var e;i.startTracked=!1,i.config.appHide&&(e={},_.extend(e,i.config.properties),_.isFunction(i.config.callback)&&_.extend(e,i.config.callback("appHide")),i.taInstance._internalTrack("ta_mg_hide",e))})}return _createClass(r,[{key:"_onShow",value:function(e){this.startTracked||(this.config.appHide&&this.taInstance.timeEvent("ta_mg_hide"),e&&e.scene&&this.taInstance._setAutoTrackProperties({"#scene":e.scene}),this.config.appShow&&(e={},_.extend(e,this.config.properties),_.isFunction(this.config.callback)&&_.extend(e,this.config.callback("appShow")),this.taInstance._internalTrack("ta_mg_show",e)))}}]),r}(),PlatformProxy$1=function(){function i(e,t,n){_classCallCheck(this,i),this.api=e,this.config=t,this._config=n}return _createClass(i,[{key:"getConfig",value:function(){return this.config}},{key:"getStorage",value:function(e,t,n){if(!t){if("dd_mp"===this._config.platform){var i=this.api.getStorageSync({key:e});return _.isJSONString(i.data)?JSON.parse(i.data):{}}i=this.api.getStorageSync(e);return _.isJSONString(i)?JSON.parse(i):{}}this.api.getStorage({key:e,success:function(e){e=_.isJSONString(e.data)?JSON.parse(e.data):{};n(e)},fail:function(){logger.warn("getStorage faild"),n({})}})}},{key:"setStorage",value:function(e,t){"ali_mp"===this._config.platform||"tb_mp"===this._config.platform||"dd_mp"===this._config.platform?this.api.setStorageSync({key:e,data:t}):this.api.setStorageSync(e,t)}},{key:"removeStorage",value:function(e){_.isFunction(this.api.removeStorage)?this.api.removeStorage({key:e}):_.isFunction(this.api.deleteStorage)&&this.api.deleteStorage({key:e})}},{key:"_getPlatform",value:function(){return""}},{key:"getSystemInfo",value:function(t){var n=this._config.mpPlatform;this.api.getSystemInfo({success:function(e){_.isFunction(n)?e.mp_platform=n(e):e.mp_platform=n,t.success(e),"wechat"===n&&t.complete()},complete:function(){t.complete()}})}},{key:"getNetworkType",value:function(t){_.isFunction(this.api.getNetworkType)?this.api.getNetworkType({success:function(e){t.success(e)},complete:function(){t.complete()}}):(t.success({}),t.complete())}},{key:"onNetworkStatusChange",value:function(e){_.isFunction(this.api.onNetworkStatusChange)?this.api.onNetworkStatusChange(e):e({})}},{key:"request",value:function(t){if("ali_mp"!==this._config.platform&&"dd_mp"!==this._config.platform)return this.api.request(t);var e=_.extend({},t);return e.headers=t.header,e.success=function(e){e.statusCode=e.status,t.success(e)},e.fail=function(e){e.errMsg=e.errorMessage,t.fail(e)},"dd_mp"===this._config.platform?this.api.httpRequest(e):this.api.request(e)}},{key:"initAutoTrackInstance",value:function(e,t){return _.isObject(t.autoTrack)&&(t.autoTrack.isPlugin=t.is_plugin),new(this._config.mp?AutoTrackBridge:AutoTrackBridge$1)(e,t.autoTrack,this.api)}},{key:"setGlobal",value:function(e,t){this._config.mp?logger.warn("ThinkingAnalytics: we do not set global name for TA instance when you do not enable auto track."):GameGlobal[t]=e}},{key:"getAppOptions",value:function(e){var t={};try{t=this.api.getLaunchOptionsSync()}catch(e){logger.warn("Cannot get launch options.")}if(_.isFunction(e))try{this._config.mp?this.api.onAppShow(e):this.api.onShow(e)}catch(e){logger.warn("Cannot register onShow callback.")}return t}},{key:"showToast",value:function(e){var t;_.isFunction(this.api.showToast)&&(t={title:e},"dd_mp"!==this._config.platform&&"ali_mp"!==this._config.platform||(t.content=e),this.api.showToast(t))}}],[{key:"createInstance",value:function(){return this._createInstance("wechat_mg")}},{key:"_createInstance",value:function(e){switch(e){case"wechat_mp":return new i(wx,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_wechat"},{mpPlatform:"wechat",mp:!0,platform:e});case"wechat_mg":return new i(wx,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_wechat_game"},{mpPlatform:"wechat",platform:e});case"qq_mp":return new i(qq,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_qq"},{mpPlatform:"qq",mp:!0,platform:e});case"qq_mg":return new i(qq,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_qq_game"},{mpPlatform:"qq",platform:e});case"baidu_mp":return new i(swan,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_swan"},{mpPlatform:function(e){return e.host},mp:!0,platform:e});case"baidu_mg":return new i(swan,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_swan_game"},{mpPlatform:function(e){return e.host},platform:e});case"tt_mg":return new i(tt,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_tt_game"},{mpPlatform:function(e){return e.appName},platform:e});case"tt_mp":return new i(tt,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_tt"},{mpPlatform:function(e){return e.appName},mp:!0,platform:e});case"ali_mp":return new i(my,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_ali"},{mpPlatform:function(e){return e.app},mp:!0,platform:e});case"dd_mp":return new i(dd,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_dd"},{mpPlatform:"dingding",mp:!0,platform:e});case"bl_mg":return new i(bl,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_mg"},{mpPlatform:"bilibili",platform:e});case"kuaishou_mp":return new i(ks,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_kuaishou"},{mpPlatform:"kuaishou",mp:!0,platform:e});case"qh360_mg":return new i(qh,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_qh360"},{mpPlatform:"qh360",platform:e});case"tb_mp":return new i(my,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_tb"},{mpPlatform:"tb",mp:!0,platform:e});case"jd_mp":return new i(jd,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_jd"},{mpPlatform:"jd",mp:!0,platform:e});case"qh360_mp":return new i(qh,{persistenceName:"thinkingdata",persistenceNameOld:"thinkingdata_qh360"},{mpPlatform:"qh360",mp:!0,platform:e});case"WEB":return new PlatformProxy.createInstance}}}]),i}(),PlatformAPI=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"_getCurrentPlatform",value:function(){return this.currentPlatform||(this.currentPlatform=PlatformProxy$1.createInstance())}},{key:"getConfig",value:function(){return this._getCurrentPlatform().getConfig()}},{key:"getStorage",value:function(e,t,n){return this._getCurrentPlatform().getStorage(e,t,n)}},{key:"setStorage",value:function(e,t){return this._getCurrentPlatform().setStorage(e,t)}},{key:"removeStorage",value:function(e){return this._getCurrentPlatform().removeStorage(e)}},{key:"getSystemInfo",value:function(e){return this._getCurrentPlatform().getSystemInfo(e)}},{key:"getNetworkType",value:function(e){return this._getCurrentPlatform().getNetworkType(e)}},{key:"onNetworkStatusChange",value:function(e){this._getCurrentPlatform().onNetworkStatusChange(e)}},{key:"request",value:function(e){return this._getCurrentPlatform().request(e)}},{key:"initAutoTrackInstance",value:function(e,t){return this._getCurrentPlatform().initAutoTrackInstance(e,t)}},{key:"setGlobal",value:function(e,t){e&&t&&this._getCurrentPlatform().setGlobal(e,t)}},{key:"getAppOptions",value:function(e){return this._getCurrentPlatform().getAppOptions(e)}},{key:"showDebugToast",value:function(e){this._getCurrentPlatform().showToast(e)}}]),e}(),HttpTask=function(){function a(e,t,n,i,r){_classCallCheck(this,a),this.data=e,this.serverUrl=t,this.callback=r,this.tryCount=_.isNumber(n)?n:1,this.timeout=_.isNumber(i)?i:3e3,this.taClassName="HttpTask"}return _createClass(a,[{key:"run",value:function(){var t=this,e=_.createExtraHeaders();e["content-type"]="application/json";var n=PlatformAPI.request({url:this.serverUrl,method:"POST",data:this.data,header:e,success:function(e){t.onSuccess(e),clearTimeout(i)},fail:function(e){t.onFailed(e),clearTimeout(i)}}),i=setTimeout(function(){(_.isObject(n)||_.isPromise(n))&&_.isFunction(n.abort)&&n.abort()},this.timeout)}},{key:"onSuccess",value:function(e){if(200===e.statusCode){var t;switch(e.data.code){case 0:t="success";break;case-1:t="invalid data";break;case-2:t="invalid APP ID";break;default:t="Unknown return code"}this.callback({code:e.data.code,msg:t})}else this.callback({code:-3,msg:e.statusCode})}},{key:"onFailed",value:function(e){0<--this.tryCount?this.run():this.callback({code:-3,msg:e.errMsg})}}]),a}(),HttpTaskDebug=function(){function o(e,t,n,i,r,a,s){_classCallCheck(this,o),this.data=e,this.serverDebugUrl=t,this.callback=s,this.tryCount=_.isNumber(n)?n:1,this.timeout=_.isNumber(i)?i:3e3,this.dryrun=r,this.deviceId=a,this.taClassName="HttpTaskDebug"}return _createClass(o,[{key:"run",value:function(){var t=this,e="appid="+this.data["#app_id"]+"&source=client&dryRun="+this.dryrun+"&deviceId="+this.deviceId+"&data="+encodeURIComponent(JSON.stringify(this.data.data[0])),n=_.createExtraHeaders();n["content-type"]="application/x-www-form-urlencoded";var i=PlatformAPI.request({url:this.serverDebugUrl,method:"POST",data:e,header:n,success:function(e){t.onSuccess(e),clearTimeout(r)},fail:function(e){t.onFailed(e),clearTimeout(r)}}),r=setTimeout(function(){(_.isObject(i)||_.isPromise(i))&&_.isFunction(i.abort)&&i.abort()},this.timeout)}},{key:"onSuccess",value:function(e){if(200===e.statusCode){var t;if(0===e.data.errorLevel)t="Verify data success.";else if(1===e.data.errorLevel){for(var n=e.data.errorProperties,i="",r=0;r<n.length;r++)var a=n[r].errorReason,i=i+" propertyName:"+n[r].propertyName+" errorReasons:"+a+"\n";t="Debug data error. errorLevel:"+e.data.errorLevel+" reason:"+i}else 2!==e.data.errorLevel&&-1!==e.data.errorLevel||(t="Debug data error. errorLevel:"+e.data.errorLevel+" reason:"+e.data.errorReasons);logger.info(t),this.callback({code:e.data.errorLevel,msg:t})}else this.callback({code:-3,msg:e.statusCode})}},{key:"onFailed",value:function(e){0<--this.tryCount?this.run():this.callback({code:-3,msg:e.errMsg})}}]),o}(),SenderQueue=function(){function e(){_classCallCheck(this,e),this.items=[],this.isRunning=!1,this.showDebug=!1}return _createClass(e,[{key:"enqueue",value:function(e,t,n,i){var i=!(3<arguments.length&&void 0!==i)||i,r=this,t="debug"===n.debugMode?new HttpTaskDebug(e,t,n.maxRetries,n.sendTimeout,0,n.deviceId,function(e){r.isRunning=!1,_.isFunction(n.callback)&&n.callback(e),r._runNext(),!1===r.showDebug&&(0!==e.code&&1!==e.code&&2!==e.code||(r.showDebug=!0,_.isFunction(PlatformAPI.showDebugToast)&&PlatformAPI.showDebugToast("The current mode is Debug")))}):"debugOnly"===n.debugMode?new HttpTaskDebug(e,t,n.maxRetries,n.sendTimeout,1,n.deviceId,function(e){r.isRunning=!1,_.isFunction(n.callback)&&n.callback(e),r._runNext(),!1===r.showDebug&&(0!==e.code&&1!==e.code&&2!==e.code||(r.showDebug=!0,_.isFunction(PlatformAPI.showDebugToast)&&PlatformAPI.showDebugToast("The current mode is debugOnly")))}):new HttpTask(JSON.stringify(e),t,n.maxRetries,n.sendTimeout,function(e){r.isRunning=!1,_.isFunction(n.callback)&&n.callback(e),r._runNext()});!0===i?(this.items.push(t),this._runNext()):t.run()}},{key:"_dequeue",value:function(){return this.items.shift()}},{key:"_runNext",value:function(){if(0<this.items.length&&!this.isRunning)if(this.isRunning=!0,"HttpTask"!==this.items[0].taClassName)this._dequeue().run();else{var e=this.items.splice(0,this.items.length),t=e[0],n=JSON.parse(t.data),i=n["#app_id"],r=[];r.push(t.callback);for(var a=1;a<e.length;a++){var s=e[a],o=JSON.parse(s.data);o["#app_id"]===i&&t.serverUrl===s.serverUrl?(n.data=n.data.concat(o.data),r.push(s.callback)):this.items.push(s)}var c=(new Date).getTime();n["#flush_time"]=c,new HttpTask(JSON.stringify(n),t.serverUrl,t.tryCount,t.timeout,function(e){for(var t in r)Object.hasOwnProperty.call(r,t)&&(0,r[t])(e)}).run()}}}]),e}(),senderQueue=new SenderQueue,DEFAULT_CONFIG={name:"thinkingdata",is_plugin:!1,maxRetries:3,sendTimeout:3e3,enablePersistence:!0,asyncPersistence:!1,enableLog:!0,strict:!1,debugMode:"none",enableCalibrationTime:!1},systemInformation={properties:{"#lib":Config.LIB_NAME,"#lib_version":Config.LIB_VERSION},initDeviceId:function(e){_.isString(e)&&(this.properties["#device_id"]=e)},getSystemInfo:function(e){var n=this;PlatformAPI.onNetworkStatusChange(function(e){n.properties["#network_type"]=e.networkType}),PlatformAPI.getNetworkType({success:function(e){n.properties["#network_type"]=e.networkType},complete:function(){PlatformAPI.getSystemInfo({success:function(e){var t=e.system?e.system.replace(/\s+/g," ").split(" "):[],t={"#manufacturer":e.brand,"#device_model":e.model,"#screen_width":Number(e.screenWidth),"#screen_height":Number(e.screenHeight),"#os":t[0],"#os_version":t[1],"#mp_platform":e.mp_platform,"#system_language":e.systemLanguage};_.extend(n.properties,t),_.setMpPlatform(e.mp_platform)},complete:function(){e()}})}})}},ThinkingDataPersistence=function(){function e(t,n){var i=this;_classCallCheck(this,e),this.enabled=t.enablePersistence,this.enabled?(t.isChildInstance?(this.name=t.persistenceName+"_"+t.name,this.nameOld=t.persistenceNameOld+"_"+t.name):(this.name=t.persistenceName,this.nameOld=t.persistenceNameOld),t.asyncPersistence?(this._state={},PlatformAPI.getStorage(this.name,!0,function(e){_.isEmptyObject(e)?PlatformAPI.getStorage(i.nameOld,!0,function(e){i._state=_.extend2Layers({},e,i._state),i._init(t,n),i._save()}):(i._state=_.extend2Layers({},e,i._state),i._init(t,n),i._save())})):(this._state=PlatformAPI.getStorage(this.name)||{},_.isEmptyObject(this._state)&&(this._state=PlatformAPI.getStorage(this.nameOld)||{}),this._init(t,n))):(this._state={},this._init(t,n))}return _createClass(e,[{key:"_init",value:function(e,t){this.getDistinctId()||this.setDistinctId(_.UUID()),e.isChildInstance||(this.getDeviceId()||this._setDeviceId(_.UUID()),systemInformation.initDeviceId(this.getDeviceId())),this.initComplete=!0,"function"==typeof t&&t(),this._save()}},{key:"_save",value:function(){this.enabled&&this.initComplete&&PlatformAPI.setStorage(this.name,JSON.stringify(this._state))}},{key:"_set",value:function(e,t){var n,i=this;"string"==typeof e?(n={})[e]=t:"object"===_typeof(e)&&(n=e),_.each(n,function(e,t){i._state[t]=e}),this._save()}},{key:"_get",value:function(e){return this._state[e]}},{key:"setEventTimer",value:function(e,t){var n=this._state.event_timers||{};n[e]=t,this._set("event_timers",n)}},{key:"removeEventTimer",value:function(e){var t=(this._state.event_timers||{})[e];return _.isUndefined(t)||(delete this._state.event_timers[e],this._save()),t}},{key:"getDeviceId",value:function(){return this._state.device_id}},{key:"_setDeviceId",value:function(e){this.getDeviceId()?logger.warn("cannot modify the device id."):this._set("device_id",e)}},{key:"getDistinctId",value:function(){return this._state.distinct_id}},{key:"setDistinctId",value:function(e){this._set("distinct_id",e)}},{key:"getAccountId",value:function(){return this._state.account_id}},{key:"setAccountId",value:function(e){this._set("account_id",e)}},{key:"getSuperProperties",value:function(){return this._state.props||{}}},{key:"setSuperProperties",value:function(e,t){e=t?e:_.extend(this.getSuperProperties(),e);this._set("props",e)}}]),e}(),dataStoragePrefix="tampsdk_",tabStoragePrefix="tab_tampsdk_",BatchConsumer=function(){function n(e,t){_classCallCheck(this,n),this.config=e,this.ta=t,this.timer=null,this.batchConfig=_.extend({size:5,interval:5e3,storageLimit:200},this.config.batchConfig),this.batchConfig.size<1&&(this.batchConfig.size=1),30<this.batchConfig.size&&(this.batchConfig.size=30),this.tabKey=tabStoragePrefix+this.config.appId,this.storageLimit=this.batchConfig.storageLimit,this.isRequest=!1,this.trackList=[],this.needFlush=!1}return _createClass(n,[{key:"batchInterval",value:function(){var e=this;e.timer=setTimeout(function(){e.recycle(),e.send(),clearTimeout(e.timer),e.batchInterval()},this.batchConfig.interval)}},{key:"add",value:function(e){if(this.isRequest)this.trackList.push(e);else{var t=e,n=dataStoragePrefix+this.config.appId+"_"+String(_.UUID()),e=PlatformAPI.getStorage(this.tabKey);if(_.isArray(e)||(e=[]),e.length<=this.storageLimit)e.push(n),PlatformAPI.setStorage(this.tabKey,JSON.stringify(e)),PlatformAPI.setStorage(n,JSON.stringify(t));else{var i=e.splice(0,20);console.log("deleted events data:"+i),e.push(n),PlatformAPI.setStorage(this.tabKey,JSON.stringify(e)),PlatformAPI.setStorage(n,JSON.stringify(t));for(var t={},r=[],a=0;a<i.length;a++){var s=PlatformAPI.getStorage(i[a]);r.push(s)}t.data=r,t["#app_id"]=this.config.appId,this.request(t,i)}}}},{key:"flush",value:function(){clearTimeout(this.timer),this.send(),this.batchInterval()}},{key:"send",value:function(){if(this.isRequest)this.needFlush=!0;else{var e=PlatformAPI.getStorage(this.tabKey);if(e&&e.length){for(var t={},n=[],i=[],r=e.length<this.batchConfig.size?e.length:this.batchConfig.size,a=0;a<r;a++){var s=PlatformAPI.getStorage(e[a]);n.push(s),i.push(e[a])}t.data=n,t["#app_id"]=this.config.appId,this.request(t,i)}}}},{key:"request",value:function(e,n){var i=this;logger.info("Flush data: "+JSON.stringify(e)),i.isRequest=!0,senderQueue.enqueue(e,this.ta.serverUrl,{maxRetries:this.config.maxRetries,sendTimeout:this.config.sendTimeout,callback:function(e){0===e.code&&i.remove(n),i.isRequest=!1;for(var t=0;t<i.trackList.length;t++)i.add(i.trackList[t]);i.trackList=[],i.needFlush&&(i.needFlush=!1,i.flush())},debugMode:this.config.debugMode,deviceId:this.ta.getDeviceId()})}},{key:"remove",value:function(e){var t=PlatformAPI.getStorage(this.tabKey);if(t){for(var n=0;n<e.length;n++){var i=_.indexOf(t,e[n]);-1<i&&t.splice(i,1),PlatformAPI.removeStorage(e[n])}PlatformAPI.setStorage(this.tabKey,JSON.stringify(t))}}},{key:"recycle",value:function(){}}]),n}(),ThinkingDataAPI=function(){function n(e){_classCallCheck(this,n),e.appId=e.appId?_.checkAppId(e.appId):_.checkAppId(e.appid),e.serverUrl=e.serverUrl?_.checkUrl(e.serverUrl):_.checkUrl(e.server_url);var t=_.extend({},DEFAULT_CONFIG,PlatformAPI.getConfig());_.isObject(e)?this.config=_.extend(t,e):this.config=t,this._init(this.config)}return _createClass(n,[{key:"_init",value:function(e){var t=this;this.name=e.name,this.appId=e.appId||e.appid;var n=e.serverUrl||e.server_url;this.serverUrl=n+"/sync_xcx",this.serverDebugUrl=n+"/data_debug",this.configUrl=n+"/config",this.autoTrackProperties={},this._queue=[],this.updateConfig(this.configUrl,this.appId),e.isChildInstance?this._state={}:(logger.enabled=e.enableLog,this.instances=[],this._state={getSystemInfo:!1,initComplete:!1},PlatformAPI.setGlobal(this,this.name)),this.store=new ThinkingDataPersistence(e,function(){t.config.asyncPersistence&&_.isFunction(t.config.persistenceComplete)&&t.config.persistenceComplete(t),t._updateState()}),this.enabled=!_.isBoolean(this.store._get("ta_enabled"))||this.store._get("ta_enabled"),this.isOptOut=!!_.isBoolean(this.store._get("ta_isOptOut"))&&this.store._get("ta_isOptOut"),!e.isChildInstance&&e.autoTrack&&(this.autoTrack=PlatformAPI.initAutoTrackInstance(this,e)),void 0!==this.config.enableBatch&&!1!==this.config.enableBatch&&(this.batchConsumer=new BatchConsumer(this.config,this),this.batchConsumer.batchInterval())}},{key:"initSystemInfo",value:function(){var e=this;this.config.isChildInstance||systemInformation.getSystemInfo(function(){e._updateState({getSystemInfo:!0})})}},{key:"updateConfig",value:function(e,t){var n=this,i=_.createExtraHeaders();i["content-type"]="application/json";var r=PlatformAPI.request({url:e+"?appid="+t,method:"GET",header:i,success:function(e){_.isUndefined(e)||_.isUndefined(e.data)||(logger.info("Get remote config success("+t+") :"+JSON.stringify(e.data)),_.isUndefined(e.data.data)||(n.config.syncBatchSize=e.data.data.sync_batch_size,n.config.syncInterval=e.data.data.sync_interval,n.config.disableEventList=e.data.data.disable_event_list,_.isUndefined(e.data.data.secret_key)||(e=e.data.data.secret_key,n.config.secretKey={publicKey:e.key,version:e.version})))},fail:function(e){logger.info("Get remote config fail("+t+") :"+e.errMsg)}});setTimeout(function(){(_.isObject(r)||_.isPromise(r))&&_.isFunction(r.abort)&&r.abort()},3e3)}},{key:"initInstance",value:function(e,t){if(this.config.isChildInstance)logger.warn("initInstance() cannot be called on child instance");else{if(_.isString(e)&&e!==this.name&&_.isUndefined(this[e])){t=new n(_.extend({},this.config,{enablePersistence:!1,isChildInstance:!0,name:e},t));return this[e]=t,this.instances.push(e),this[e]._state=this._state,t}logger.warn("initInstance() failed due to the name is invalid: "+e)}}},{key:"lightInstance",value:function(e){return this[e]}},{key:"_setAutoTrackProperties",value:function(e){_.extend(this.autoTrackProperties,e)}},{key:"init",value:function(){if(this.initSystemInfo(),this._state.initComplete)return!1;this._updateState({initComplete:!0}),logger.info("TDAnalytics SDK initialize success, AppId = "+this.config.appId+", ServerUrl = "+this.config.serverUrl+", Mode = "+this.config.model+", DeviceId = "+this.getDeviceId()+", Lib = "+Config.LIB_NAME+", LibVersion = "+Config.LIB_VERSION)}},{key:"_isReady",value:function(){return this._state.getSystemInfo&&this._state.initComplete&&this.store.initComplete&&this.getDeviceId()}},{key:"_updateState",value:function(e){var t=this;_.isObject(e)&&_.extend(this._state,e),this._onStateChange(),_.each(this.instances,function(e){t[e]._onStateChange()})}},{key:"_onStateChange",value:function(){var t=this;this._isReady()&&this._queue&&0<this._queue.length&&(_.each(this._queue,function(e){t[e[0]].apply(t,slice.call(e[1]))}),this._queue=[])}},{key:"_hasDisabled",value:function(){var e=!this.enabled||this.isOptOut;return e&&logger.info("SDK is Pause or Stop!"),e}},{key:"_sendRequest",value:function(e,t,n){if(!this._hasDisabled())if(_.isUndefined(this.config.disableEventList)||!this.config.disableEventList.includes(e.eventName)){t=_.isDate(t)?t:new Date;var i={data:[{"#type":e.type,"#time":_.formatDate(t),"#distinct_id":this.store.getDistinctId()}]};this.store.getAccountId()&&(i.data[0]["#account_id"]=this.store.getAccountId()),"track"===e.type||"track_update"===e.type||"track_overwrite"===e.type?(i.data[0]["#event_name"]=e.eventName,"track_update"===e.type||"track_overwrite"===e.type?i.data[0]["#event_id"]=e.extraId:e.firstCheckId&&(i.data[0]["#first_check_id"]=e.firstCheckId),i.data[0].properties=_.extend({"#zone_offset":0-t.getTimezoneOffset()/60},systemInformation.properties,this.autoTrackProperties,this.store.getSuperProperties(),this.dynamicProperties?this.dynamicProperties():{}),t=this.store.removeEventTimer(e.eventName),_.isUndefined(t)||(r=(new Date).getTime()-t,86400<(r=parseFloat((r/1e3).toFixed(3)))?r=86400:r<0&&(r=0),i.data[0].properties["#duration"]=r)):i.data[0].properties={},_.isObject(e.properties)&&!_.isEmptyObject(e.properties)&&_.extend(i.data[0].properties,e.properties),_.searchObjDate(i.data[0]),1<this.config.maxRetries&&(i.data[0]["#uuid"]=_.UUIDv4()),i["#app_id"]=this.appId,logger.info("Tracking data, "+JSON.stringify(i,null,4));var r="debug"===this.config.debugMode||"debugOnly"===this.config.debugMode?this.serverDebugUrl:this.serverUrl;if(_.isBoolean(this.config.enableEncrypt)&&!0===this.config.enableEncrypt&&(i.data[0]=_.generateEncryptyData(i.data[0],this.config.secretKey)),this.batchConsumer&&"none"===this.config.debugMode&&!n)return this.batchConsumer.add(i.data[0]),void(_.isFunction(e.onComplete)&&e.onComplete({code:0,msg:"success"}));n?(n=new FormData,"debug"===this.config.debugMode||"debugOnly"===this.config.debugMode?(n.append("source","client"),n.append("appid",this.appId),n.append("dryRun","debugOnly"===this.config.debugMode?1:0),n.append("deviceId",this.getDeviceId()),n.append("data",JSON.stringify(i.data[0])),navigator.sendBeacon(r,n)):(n=(new Date).getTime(),i["#flush_time"]=n,navigator.sendBeacon(r,JSON.stringify(i))),_.isFunction(e.onComplete)&&e.onComplete({statusCode:200})):senderQueue.enqueue(i,r,{maxRetries:this.config.maxRetries,sendTimeout:this.config.sendTimeout,callback:e.onComplete,debugMode:this.config.debugMode,deviceId:this.getDeviceId()})}else logger.info("Disabled Event : "+e.eventName)}},{key:"_isObjectParams",value:function(e){return _.isObject(e)&&_.isFunction(e.onComplete)}},{key:"track",value:function(e,t,n,i){var r;this._hasDisabled()||(this._isObjectParams(e)&&(e=(r=e).eventName,t=r.properties,n=r.time,i=r.onComplete),PropertyChecker.event(e)&&PropertyChecker.properties(t)||!this.config.strict?this._internalTrack(e,t,n,i):_.isFunction(i)&&i({code:-1,msg:"invalid parameters"}))}},{key:"trackUpdate",value:function(e){var t,n;this._hasDisabled()||(e&&e.eventId&&(PropertyChecker.event(e.eventName)&&PropertyChecker.properties(e.properties)||!this.config.strict)?this._isReady()?(t=_.checkCalibration(e.properties,e.time,this.config.enableCalibrationTime),n=_.isDate(e.time)?e.time:new Date,this._sendRequest({type:"track_update",eventName:e.eventName,properties:t,onComplete:e.onComplete,extraId:e.eventId},n)):this._queue.push(["trackUpdate",[e]]):(logger.warn("Invalide parameter for trackUpdate: you should pass an object contains eventId to trackUpdate()"),_.isFunction(e.onComplete)&&e.onComplete({code:-1,msg:"invalid parameters"})))}},{key:"trackOverwrite",value:function(e){var t,n;this._hasDisabled()||(e&&e.eventId&&(PropertyChecker.event(e.eventName)&&PropertyChecker.properties(e.properties)||!this.config.strict)?this._isReady()?(t=_.checkCalibration(e.properties,e.time,this.config.enableCalibrationTime),n=_.isDate(e.time)?e.time:new Date,this._sendRequest({type:"track_overwrite",eventName:e.eventName,properties:t,onComplete:e.onComplete,extraId:e.eventId},n)):this._queue.push(["trackOverwrite",[e]]):(logger.warn("Invalide parameter for trackOverwrite: you should pass an object contains eventId to trackOverwrite()"),_.isFunction(e.onComplete)&&e.onComplete({code:-1,msg:"invalid parameters"})))}},{key:"trackFirstEvent",value:function(e){var t,n;this._hasDisabled()||(e&&e.eventName&&(PropertyChecker.event(e.eventName)&&PropertyChecker.properties(e.properties)||!this.config.strict)?this._isReady()?(t=_.checkCalibration(e.properties,e.time,this.config.enableCalibrationTime),n=_.isDate(e.time)?e.time:new Date,this._sendRequest({type:"track",eventName:e.eventName,properties:t,onComplete:e.onComplete,firstCheckId:e.firstCheckId||this.getDeviceId()},n)):this._queue.push(["trackFirstEvent",[e]]):(logger.warn("Invalide parameter for trackFirstEvent: you should pass an object contains eventName to trackFirstEvent()"),_.isFunction(e.onComplete)&&e.onComplete({code:-1,msg:"invalid parameters"})))}},{key:"_internalTrack",value:function(e,t,n,i,r){var a;this._hasDisabled()||(a=_.checkCalibration(t,n,this.config.enableCalibrationTime),n=_.isDate(n)?n:new Date,this._isReady()?this._sendRequest({type:"track",eventName:e,properties:a,onComplete:i},n,r):this._queue.push(["_internalTrack",[e,t,n,i]]))}},{key:"userSet",value:function(e,t,n){var i;this._hasDisabled()||(this._isObjectParams(e)&&(e=(i=e).properties,t=i.time,n=i.onComplete),PropertyChecker.propertiesMust(e)||!this.config.strict?(t=_.isDate(t)?t:new Date,this._isReady()?this._sendRequest({type:"user_set",properties:e,onComplete:n},t):this._queue.push(["userSet",[e,t,n]])):(logger.warn("calling userSet failed due to invalid arguments"),_.isFunction(n)&&n({code:-1,msg:"invalid parameters"})))}},{key:"userSetOnce",value:function(e,t,n){var i;this._hasDisabled()||(this._isObjectParams(e)&&(e=(i=e).properties,t=i.time,n=i.onComplete),PropertyChecker.propertiesMust(e)||!this.config.strict?(t=_.isDate(t)?t:new Date,this._isReady()?this._sendRequest({type:"user_setOnce",properties:e,onComplete:n},t):this._queue.push(["userSetOnce",[e,t,n]])):(logger.warn("calling userSetOnce failed due to invalid arguments"),_.isFunction(n)&&n({code:-1,msg:"invalid parameters"})))}},{key:"userUnset",value:function(e,t,n){var i;this._hasDisabled()||(this._isObjectParams(i)&&(e=i.property,t=i.time,n=i.onComplete),PropertyChecker.propertyName(e)||!this.config.strict?(t=_.isDate(t)?t:new Date,this._isReady()?((i={})[e]=0,this._sendRequest({type:"user_unset",properties:i,onComplete:n},t)):this._queue.push(["userUnset",[e,n,t]])):(logger.warn("calling userUnset failed due to invalid arguments"),_.isFunction(n)&&n({code:-1,msg:"invalid parameters"})))}},{key:"userDel",value:function(e,t){var n;this._hasDisabled()||(this._isObjectParams(e)&&(e=(n=e).time,t=n.onComplete),e=_.isDate(e)?e:new Date,this._isReady()?this._sendRequest({type:"user_del",onComplete:t},e):this._queue.push(["userDel",[e,t]]))}},{key:"userAdd",value:function(e,t,n){var i;this._hasDisabled()||(this._isObjectParams(e)&&(e=(i=e).properties,t=i.time,n=i.onComplete),PropertyChecker.userAddProperties(e)||!this.config.strict?(t=_.isDate(t)?t:new Date,this._isReady()?this._sendRequest({type:"user_add",properties:e,onComplete:n},t):this._queue.push(["userAdd",[e,t,n]])):(logger.warn("calling userAdd failed due to invalid arguments"),_.isFunction(n)&&n({code:-1,msg:"invalid parameters"})))}},{key:"userAppend",value:function(e,t,n){var i;this._hasDisabled()||(this._isObjectParams(e)&&(e=(i=e).properties,t=i.time,n=i.onComplete),PropertyChecker.userAppendProperties(e)||!this.config.strict?(t=_.isDate(t)?t:new Date,this._isReady()?this._sendRequest({type:"user_append",properties:e,onComplete:n},t):this._queue.push(["userAppend",[e,t,n]])):(logger.warn("calling userAppend failed due to invalid arguments"),_.isFunction(n)&&n({code:-1,msg:"invalid parameters"})))}},{key:"userUniqAppend",value:function(e,t,n){var i;this._hasDisabled()||(this._isObjectParams(e)&&(e=(i=e).properties,t=i.time,n=i.onComplete),PropertyChecker.userAppendProperties(e)||!this.config.strict?(t=_.isDate(t)?t:new Date,this._isReady()?this._sendRequest({type:"user_uniq_append",properties:e,onComplete:n},t):this._queue.push(["userUniqAppend",[e,t,n]])):(logger.warn("calling userAppend failed due to invalid arguments"),_.isFunction(n)&&n({code:-1,msg:"invalid parameters"})))}},{key:"flush",value:function(){this.batchConsumer&&"none"===this.config.debugMode&&this.batchConsumer.flush()}},{key:"authorizeOpenID",value:function(e){this.identify(e)}},{key:"identify",value:function(e){if(!this._hasDisabled()){if("number"==typeof e)e=String(e);else if("string"!=typeof e)return!1;this.store.setDistinctId(e),logger.info("Setting distinct ID, DistinctId = "+e)}}},{key:"getDistinctId",value:function(){return this.store.getDistinctId()}},{key:"login",value:function(e){if(!this._hasDisabled()){if("number"==typeof e)e=String(e);else if("string"!=typeof e)return!1;this.store.setAccountId(e),logger.info("Login SDK, AccountId = "+e)}}},{key:"getAccountId",value:function(){return this.store.getAccountId()}},{key:"logout",value:function(){this._hasDisabled()||(this.store.setAccountId(null),logger.info("Logout SDK"))}},{key:"setSuperProperties",value:function(e){this._hasDisabled()||(PropertyChecker.propertiesMust(e)||!this.config.strict?this.store.setSuperProperties(e):logger.warn("setSuperProperties parameter must be a valid property value"))}},{key:"clearSuperProperties",value:function(){this._hasDisabled()||this.store.setSuperProperties({},!0)}},{key:"unsetSuperProperty",value:function(e){var t;this._hasDisabled()||_.isString(e)&&(delete(t=this.getSuperProperties())[e],this.store.setSuperProperties(t,!0))}},{key:"getSuperProperties",value:function(){return this.store.getSuperProperties()}},{key:"getPresetProperties",value:function(){var e=systemInformation.properties,t={},n=e["#os"];t.os=_.isUndefined(n)?"":n;n=e["#screen_width"];t.screenWidth=_.isUndefined(n)?0:n;n=e["#screen_height"];t.screenHeight=_.isUndefined(n)?0:n;n=e["#network_type"];t.networkType=_.isUndefined(n)?"":n;n=e["#device_model"];t.deviceModel=_.isUndefined(n)?"":n;n=e["#os_version"];t.osVersion=_.isUndefined(n)?"":n,t.deviceId=this.getDeviceId();var i=0-(new Date).getTimezoneOffset()/60;t.zoneOffset=i;e=e["#manufacturer"];return t.manufacturer=_.isUndefined(e)?"":e,t.toEventPresetProperties=function(){return{"#device_model":t.deviceModel,"#device_id":t.deviceId,"#screen_width":t.screenWidth,"#screen_height":t.screenHeight,"#os":t.os,"#os_version":t.osVersion,"#network_type":t.networkType,"#zone_offset":i,"#manufacturer":t.manufacturer}},t}},{key:"setDynamicSuperProperties",value:function(e){this._hasDisabled()||("function"==typeof e?PropertyChecker.properties(e())||!this.config.strict?this.dynamicProperties=e:logger.warn("A dynamic public property must return a valid property value"):logger.warn("setDynamicSuperProperties parameter must be a function type"))}},{key:"timeEvent",value:function(e,t){this._hasDisabled()||(t=_.isDate(t)?t:new Date,this._isReady()?PropertyChecker.event(e)||!this.config.strict?this.store.setEventTimer(e,t.getTime()):logger.warn("calling timeEvent failed due to invalid eventName: "+e):this._queue.push(["timeEvent",[e,t]]))}},{key:"getDeviceId",value:function(){return systemInformation.properties["#device_id"]}},{key:"enableTracking",value:function(e){this.enabled=e,this.store._set("ta_enabled",e)}},{key:"optOutTracking",value:function(){this.store.setSuperProperties({},!0),this.store.setDistinctId(_.UUID()),this.store.setAccountId(null),this._queue.splice(0,this._queue.length),this.isOptOut=!0,this.store._set("ta_isOptOut",!0)}},{key:"optOutTrackingAndDeleteUser",value:function(){var e=new Date;this._sendRequest({type:"user_del"},e),this.optOutTracking()}},{key:"optInTracking",value:function(){this.isOptOut=!1,this.store._set("ta_isOptOut",!1)}},{key:"setTrackStatus",value:function(e){switch(e){case"PAUSE":this.eventSaveOnly=!1,this.optInTracking(),this.enableTracking(!1);break;case"STOP":this.eventSaveOnly=!1,this.optOutTracking(!0);break;case"SAVE_ONLY":break;case"NORMAL":default:this.eventSaveOnly=!1,this.optInTracking(),this.enableTracking(!0)}logger.info("Change Status to "+e)}}]),n}(),TDAnalytics=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"_shareInstance",value:function(e){return void 0!==this._instanceMaps[e]?this._instanceMaps[e]:void 0!==this._defaultInstance?this._defaultInstance:void 0}},{key:"init",value:function(e){var t=new ThinkingDataAPI(e);t.init(),void 0!==t&&(void 0===this._defaultInstance&&(this._defaultInstance=t,this._instanceMaps={}),this._instanceMaps[e.appId]=t)}},{key:"lightInstance",value:function(e){return this._shareInstance(e).lightInstance()}},{key:"track",value:function(e,t){e=0<arguments.length&&void 0!==e?e:{},t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).track(e.eventName,e.properties,e.time,e.onComplete)}},{key:"trackFirst",value:function(e,t){e=0<arguments.length&&void 0!==e?e:{},t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).trackFirstEvent(e)}},{key:"trackUpdate",value:function(e,t){e=0<arguments.length&&void 0!==e?e:{},t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).trackUpdate(e)}},{key:"trackOverwrite",value:function(e,t){e=0<arguments.length&&void 0!==e?e:{},t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).trackOverwrite(e)}},{key:"timeEvent",value:function(e,t){e=0<arguments.length&&void 0!==e?e:{},t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).timeEvent(e.eventName,e.time)}},{key:"userSet",value:function(e,t){e=0<arguments.length&&void 0!==e?e:{},t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).userSet(e.properties,e.time,e.onComplete)}},{key:"userSetOnce",value:function(e,t){e=0<arguments.length&&void 0!==e?e:{},t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).userSetOnce(e.properties,e.time,e.onComplete)}},{key:"userUnset",value:function(e,t){e=0<arguments.length&&void 0!==e?e:{},t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).userUnset(e.property,e.time,e.onComplete)}},{key:"userAdd",value:function(e,t){e=0<arguments.length&&void 0!==e?e:{},t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).userAdd(e.properties,e.time,e.onComplete)}},{key:"userAppend",value:function(e,t){e=0<arguments.length&&void 0!==e?e:{},t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).userAppend(e.properties,e.time,e.onComplete)}},{key:"userUniqAppend",value:function(e,t){e=0<arguments.length&&void 0!==e?e:{},t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).userUniqAppend(e.properties,e.time,e.onComplete)}},{key:"userDelete",value:function(e,t){e=0<arguments.length&&void 0!==e?e:{},t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).userDel(e.time,e.onComplete)}},{key:"setSuperProperties",value:function(e,t){t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).setSuperProperties(e)}},{key:"unsetSuperProperty",value:function(e,t){t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).unsetSuperProperty(e)}},{key:"clearSuperProperties",value:function(e){this._shareInstance(e).clearSuperProperties()}},{key:"getSuperProperties",value:function(e){return this._shareInstance(e).getSuperProperties()}},{key:"setDynamicSuperProperties",value:function(e,t){t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).setDynamicSuperProperties(e)}},{key:"getPresetProperties",value:function(e){return this._shareInstance(e).getPresetProperties()}},{key:"login",value:function(e,t){t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).login(e)}},{key:"logout",value:function(e){this._shareInstance(e).logout()}},{key:"setDistinctId",value:function(e,t){t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).identify(e)}},{key:"getDistinctId",value:function(e){return this._shareInstance(e).getDistinctId()}},{key:"getSDKVersion",value:function(){return Config.LIB_VERSION}},{key:"getDeviceId",value:function(e){return this._shareInstance(e).getDeviceId()}},{key:"flush",value:function(e){this._shareInstance(e).flush()}},{key:"setTrackStatus",value:function(e,t){t=1<arguments.length&&void 0!==t?t:"";this._shareInstance(t).setTrackStatus(e)}},{key:"ThinkingDataAPI",value:function(){return ThinkingDataAPI}}]),e}();module.exports=TDAnalytics; |