@fle-sdk/event-tracking-web 1.2.8 → 1.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.esm.js +5 -6
- package/lib/index.esm.min.js +1 -1
- package/lib/index.js +5 -6
- package/lib/index.min.js +1 -1
- package/lib/types/index.d.ts +1 -1
- package/lib/types/type.d.ts +7 -6
- package/package.json +1 -1
package/lib/index.esm.js
CHANGED
|
@@ -444,7 +444,7 @@ function () {
|
|
|
444
444
|
|
|
445
445
|
this.filterSensitiveData = function (obj, sensitiveKeys) {
|
|
446
446
|
if (sensitiveKeys === void 0) {
|
|
447
|
-
sensitiveKeys = ["password", "token", "secret"
|
|
447
|
+
sensitiveKeys = ["password", "token", "secret"];
|
|
448
448
|
}
|
|
449
449
|
|
|
450
450
|
if (!_this.isObject(obj)) return obj;
|
|
@@ -1659,9 +1659,7 @@ function () {
|
|
|
1659
1659
|
this.callbacks.ajax({
|
|
1660
1660
|
url: serverUrl,
|
|
1661
1661
|
type: "POST",
|
|
1662
|
-
data: JSON.stringify(
|
|
1663
|
-
events: data
|
|
1664
|
-
}),
|
|
1662
|
+
data: JSON.stringify(data),
|
|
1665
1663
|
contentType: contentType,
|
|
1666
1664
|
credentials: false,
|
|
1667
1665
|
timeout: this.config.sendTimeout,
|
|
@@ -2360,7 +2358,8 @@ function (_super) {
|
|
|
2360
2358
|
};
|
|
2361
2359
|
|
|
2362
2360
|
_this.track = function (_a) {
|
|
2363
|
-
var
|
|
2361
|
+
var event = _a.event,
|
|
2362
|
+
desc = _a.desc,
|
|
2364
2363
|
pageKey = _a.pageKey,
|
|
2365
2364
|
partKey = _a.partKey,
|
|
2366
2365
|
business = _a.business,
|
|
@@ -2368,7 +2367,7 @@ function (_super) {
|
|
|
2368
2367
|
|
|
2369
2368
|
var params = _this.getParams({
|
|
2370
2369
|
desc: desc,
|
|
2371
|
-
event: "CustomTrack",
|
|
2370
|
+
event: event || "CustomTrack",
|
|
2372
2371
|
itemKey: _this.getItemKey(partKey, pageKey),
|
|
2373
2372
|
privateParamMap: {
|
|
2374
2373
|
business: business
|
package/lib/index.esm.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(t){return(e="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})(t)}var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,n)};var n=function(){return(n=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)};function i(e,t){for(var n=0,i=t.length,r=e.length;n<i;n++,r++)e[r]=t[n];return e}var r=function(){function t(){var t=this;this.getSystemsInfo=function(e){var t=navigator.userAgent,n="other",i=[],r={language:navigator.language},o=t.match(/MicroMessenger\/([\d\.]+)/i),a=o&&o[1]?o[1]:null,s=t.match(/(ipod).*\s([\d_]+)/i),c=t.match(/(ipad).*\s([\d_]+)/i),u=t.match(/(iphone)\sos\s([\d_]+)/i),l=t.match(/(android)\s([\d\.]+)/i),g=t.match(/(Windows NT)\s([\d\.]+)/i),p=t.match(/(Mac OS X)\s([\d_]+)/i);i=[],l?(i.push("Android "+l[2]),n="h5"):u?(i.push("iPhone, iOS "+u[2].replace(/_/g,".")),n="h5"):c?(i.push("iPad, iOS "+c[2].replace(/_/g,".")),n="ipad"):s?(i.push("iPod, iOS "+s[2].replace(/_/g,".")),n="h5"):g?(i.push("Windows "+g[2].replace(/_/g,".")),n="pc"):p&&(i.push("Mac, MacOS "+p[2].replace(/_/g,".")),n="pc"),a&&i.push("WeChat "+a),r.client=i.length?i.join(", "):"Unknown",r.platform=e||n;var d=t.toLowerCase().match(/ nettype\/([^ ]+)/g);return d&&d[0]&&(i=[(d=d[0].split("/"))[1]],r.network=i.length?i.join(", "):"Unknown"),r.ua=t,r},this.addEventListener=function(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent&&e.attachEvent("on"+t,(function(t){return n.call(e,t)}),!1)},this.removeEventListener=function(e,t,n){e.removeEventListener?e.removeEventListener(t,n):e.detachEvent&&e.detachEvent("on"+t,(function(t){return n.call(e,t)}),!0)},this.rewriteHistory=function(){var e=window.history,t=function(e){var t=window.history,n=t[e],i=new Event(e);return function(){var e=n.apply(t,arguments);return i.arguments=arguments,window.dispatchEvent(i),e}};window.history.pushState&&(e.pushState=t("pushState"),e.replaceState=t("replaceState"))},this.isArray=Array.isArray||function(e){return"[object Array]"===toString.call(e)},this.formatJsonString=function(e){try{return JSON.stringify(e,null," ")}catch(t){return JSON.stringify(e)}},this.nativeForEach=Array.prototype.forEach,this.slice=Array.prototype.slice,this.hasOwnProperty=Object.prototype.hasOwnProperty,this.breaker={},this.each=function(e,n,i){if(null==e)return!1;if(t.nativeForEach&&e.forEach===t.nativeForEach)e.forEach(n,i);else if(t.isArray(e)&&e.length===+e.length){for(var r=0,o=e.length;r<o;r++)if(r in e&&n.call(i,e[r],r,e)===t.breaker)return!1}else for(var a in e)if(t.hasOwnProperty.call(e,a)&&n.call(i,e[a],a,e)===t.breaker)return!1;return!0},this.getDomIndex=function(e){if(!e.parentNode)return-1;for(var t=0,n=e.tagName,i=e.parentNode.children,r=0;r<i.length;r++)if(i[r].tagName===n){if(e===i[r])return t;t++}return-1},this.selector=function(e){var n=e.parentNode&&9==e.parentNode.nodeType?-1:t.getDomIndex(e);return e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?"#"+e.getAttribute("id"):e.tagName.toLowerCase()+(~n?":nth-of-type("+(n+1)+")":"")},this.getDomSelector=function(e,n){if(!e||!e.parentNode||!e.parentNode.children)return!1;n=n&&n.join?n:[];var i=e.nodeName.toLowerCase();return e&&"body"!==i&&1==e.nodeType?(n.unshift(t.selector(e)),e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?n.join(" > "):t.getDomSelector(e.parentNode,n)):(n.unshift("body"),n.join(" > "))},this.getCookie=function(e){for(var t=e+"=",n=document.cookie.split(";"),i=0;i<n.length;i++){for(var r=n[i];" "==r.charAt(0);)r=r.substring(1,r.length);if(0==r.indexOf(t))return this._decodeURIComponent(r.substring(t.length,r.length))}return null},this.setCookie=function(e,t,n){var i,r="";n=null==n?73e3:n;var o=this.getMainHost();if(i=o?"; domain="+o:"",0!==n){var a=new Date;"s"===String(n).slice(-1)?a.setTime(a.getTime()+1e3*Number(String(n).slice(0,-1))):a.setTime(a.getTime()+24*n*60*60*1e3),r="; expires="+a.toUTCString()}function s(e){return e||!1}var c="",u="",l="";e&&(c=s(e)),t&&(u=s(t)),i&&(l=s(i)),c&&u&&(document.cookie=c+"="+encodeURIComponent(u)+r+"; path=/"+l)},this.getLocalStorage=function(e){try{return localStorage.getItem(e)}catch(e){return null}},this.setLocalStorage=function(e,t){try{localStorage.setItem(e,t)}catch(e){}},this.removeCookie=function(e){t.setCookie(e,"",-1)},this.getTimeStamp=function(){return(new Date).getTime()},this.uuid=function(){return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},this.getDistinctId=function(){var e=t.getCookie("distinctId");return e||(e=t.uuid(),t.setCookie("distinctId",e),e)},this.filterSensitiveData=function(e,n){if(void 0===n&&(n=["password","token","secret","key"]),!t.isObject(e))return e;var i={};return t.each(e,(function(e,r){n.some((function(e){return"string"==typeof r&&r.toLowerCase().includes(e.toLowerCase())}))?i[r]="***":t.isObject(e)?i[r]=t.filterSensitiveData(e,n):i[r]=e})),i},this.xssFilter=function(e){return e?"string"!=typeof e?e.toString():e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/"):""},this.getQueryValue=function(){for(var e=decodeURI(window.location.href).match(new RegExp("[?&][^?&]+=[^?&]+","g"))||[],t={},n=0;n<e.length;n++){var i=e[n].replace(/\?|\&/,"").split("=");t[i[0]]=i[1]}return Object.keys(t).length>0?t:null},this.ajax=function(n){function i(t){if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)}catch(e){return{}}return"object"===e(t)?t:{}}n.timeout=n.timeout||3e4,n.credentials=void 0===n.credentials||n.credentials;var r=t.xhr(n.cors);if(!r)return!1;n.type||(n.type=n.data?"POST":"GET");var o,a=n.success,s=n.error;n.success=function(e){a&&a(e),o&&(clearTimeout(o),o=null)},n.error=function(e,t){s&&s(e,t),o&&(clearTimeout(o),o=null)},o=window.setTimeout((function(){!function(){try{t.isObject(r)&&r.abort&&r.abort()}catch(e){t.printLog(e)}o&&(clearTimeout(o),o=null,n.error&&n.error(),r.onreadystatechange=null,r.onload=null,r.onerror=null)}()}),n.timeout),r.onreadystatechange=function(){try{4==r.readyState&&(r.status>=200&&r.status<300||304==r.status?n.success&&n.success(i(r.responseText)):n.error&&n.error(i(r.responseText),r.status),r.onreadystatechange=null,r.onload=null)}catch(e){r.onreadystatechange=null,r.onload=null}},r.open(n.type||"GET",n.url,!0);try{if(n.credentials&&(r.withCredentials=!0),t.isObject(n.header)&&t.each(n.header,(function(e,t){r.setRequestHeader&&r.setRequestHeader(t,e)})),n.data)n.cors||r.setRequestHeader&&r.setRequestHeader("X-Requested-With","XMLHttpRequest"),t.isObject(n.header)&&Object.keys(n.header).some((function(e){return"content-type"===e.toLowerCase()||"content-type"===e.toLowerCase()}))||("application/json"===n.contentType?r.setRequestHeader&&r.setRequestHeader("Content-type","application/json; charset=UTF-8"):r.setRequestHeader&&r.setRequestHeader("Content-type","application/x-www-form-urlencoded"))}catch(e){t.printLog(e)}r.send(n.data||null)},this.xhr=function(e){return e?void 0!==window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?new XMLHttpRequest:null:void 0!==window.XMLHttpRequest?new XMLHttpRequest:null},this.getUA=function(){var e,t={},n=navigator.userAgent.toLowerCase();return(e=n.match(/opera.([\d.]+)/))?t.opera=Number(e[1].split(".")[0]):(e=n.match(/msie ([\d.]+)/))?t.ie=Number(e[1].split(".")[0]):(e=n.match(/edge.([\d.]+)/))?t.edge=Number(e[1].split(".")[0]):(e=n.match(/firefox\/([\d.]+)/))?t.firefox=Number(e[1].split(".")[0]):(e=n.match(/chrome\/([\d.]+)/))?t.chrome=Number(e[1].split(".")[0]):(e=n.match(/version\/([\d.]+).*safari/))?t.safari=Number(e[1].match(/^\d*.\d*/)):(e=n.match(/trident\/([\d.]+)/))&&(t.ie=11),t},this.isSupportBeaconSend=function(){var n=!1;if("object"!==("undefined"==typeof navigator?"undefined":e(navigator))||"function"!=typeof navigator.sendBeacon)return n;var i=t.getUA(),r=navigator.userAgent.toLowerCase();if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){var o=(r.match(/os [\d._]*/gi)+"").replace(/[^0-9|_.]/gi,"").replace(/_/gi,".").split(".");void 0===i.safari&&(i.safari=Number(o[0])),o[0]&&+o[0]<13?(i.chrome>41||i.firefox>30||i.opera>25||i.safari>12)&&(n=!0):(i.chrome>41||i.firefox>30||i.opera>25||i.safari>11.3)&&(n=!0)}else(i.chrome>38||i.edge>13||i.firefox>30||i.opera>25||i.safari>11)&&(n=!0);return n},this.throttle=function(e,t){var n=null,i=0;return function(){for(var r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var a=Date.now(),s=t-(a-i);s<=0||s>t?(n&&(clearTimeout(n),n=null),i=a,e.apply(void 0,r)):n||(n=window.setTimeout((function(){i=Date.now(),n=null,e.apply(void 0,r)}),s))}},this.debounce=function(e,t){var n=null;return function(){for(var i=[],r=0;r<arguments.length;r++)i[r]=arguments[r];n&&clearTimeout(n),n=window.setTimeout((function(){e.apply(void 0,i)}),t)}},this.sendBeacon=function(e){if(!0===t.isSupportBeaconSend()){var n={type:e.contentType},i=new Blob([JSON.stringify(e.data)],n);return navigator.sendBeacon(e.url,i)?Promise.resolve({success:!0,message:"发送成功"}):Promise.reject({success:!1,message:"sendBeacon返回false"})}return Promise.reject({success:!1,message:"不支持sendBeacon,发送失败!"})},this.getDeviceId=function(){var e=t.getCookie("device_id")||t.getLocalStorage("device_id");if(e)return e;var n=t.collectFingerprint(),i=t.hashFingerprint(n);return t.setCookie("device_id",i,730),t.setLocalStorage("device_id",i),i},this.collectFingerprint=function(){var e={};return e.userAgent=navigator.userAgent,e.screenWidth=screen.width,e.screenHeight=screen.height,e.colorDepth=screen.colorDepth,e.pixelDepth=screen.pixelDepth,e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,e.timezoneOffset=(new Date).getTimezoneOffset(),e.language=navigator.language,e.languages=Array.from(navigator.languages),e.platform=navigator.platform,e.webgl=t.getWebGLFingerprint(),e.canvas=t.getCanvasFingerprint(),e.audio=t.getAudioFingerprint(),e.localStorage=t.hasLocalStorage(),e.sessionStorage=t.hasSessionStorage(),e.indexedDB=t.hasIndexedDB(),e.hardwareConcurrency=navigator.hardwareConcurrency,e.deviceMemory=navigator.deviceMemory,e.maxTouchPoints=navigator.maxTouchPoints,e},this.getWebGLFingerprint=function(){try{var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"not-supported";var n=t.getExtension("WEBGL_debug_renderer_info");return(n?t.getParameter(n.UNMASKED_VENDOR_WEBGL):"unknown")+"|"+(n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"unknown")}catch(e){return"error"}},this.getCanvasFingerprint=function(){try{var e=document.createElement("canvas");e.width=200,e.height=50;var t=e.getContext("2d");return t?(t.textBaseline="top",t.font="14px Arial",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("Canvas fingerprint",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("Canvas fingerprint",4,17),e.toDataURL().slice(-50)):"not-supported"}catch(e){return"error"}},this.getAudioFingerprint=function(){try{var e=window.AudioContext||window.webkitAudioContext;if(!e)return"not-supported";var t=new e,n=String(t.sampleRate||0);return t.close(),n}catch(e){return"error"}},this.hasLocalStorage=function(){try{var e="__test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}},this.hasSessionStorage=function(){try{var e="__test__";return sessionStorage.setItem(e,e),sessionStorage.removeItem(e),!0}catch(e){return!1}},this.hasIndexedDB=function(){return"indexedDB"in window&&null!==indexedDB},this.hashFingerprint=function(e){for(var t=JSON.stringify(e,Object.keys(e).sort()),n=5381,i=52711,r=0;r<t.length;r++){var o=t.charCodeAt(r);n=(n<<5)+n+o,i=(i<<5)+i+o}return"fp_"+(n>>>0).toString(16).padStart(8,"0")+(i>>>0).toString(16).padStart(8,"0")}}return t.prototype.printLog=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];if(this.isObject(t[0])&&(t[0]=this.formatJsonString(t[0])),"object"===("undefined"==typeof console?"undefined":e(console))&&console.log)try{return console.log.apply(console,t)}catch(e){console.log(t[0])}},t.prototype.isObject=function(e){return null!=e&&"[object Object]"==toString.call(e)},t.prototype.isUndefined=function(e){return void 0===e},t.prototype.isString=function(e){return"[object String]"==toString.call(e)},t.prototype.isDate=function(e){return"[object Date]"==toString.call(e)},t.prototype.isBoolean=function(e){return"[object Boolean]"==toString.call(e)},t.prototype.isNumber=function(e){return"[object Number]"==toString.call(e)&&/[\d\.]+/.test(String(e))},t.prototype.isElement=function(e){return!(!e||1!==e.nodeType)},t.prototype.isFunction=function(e){if(!e)return!1;var t=toString.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t},t.prototype.isJSONString=function(e){if(!this.isString(e))return!1;try{JSON.parse(e)}catch(e){return!1}return!0},t.prototype._decodeURIComponent=function(e){var t=e;try{t=decodeURIComponent(e)}catch(n){t=e}return t},t.prototype.getMainHost=function(){var e="mh_"+Math.random(),t=new RegExp("(^|;)\\s*"+e+"=12345"),n=new Date(0),i=document.domain,r=i.split("."),o=[];for(o.unshift(r.pop());r.length;){o.unshift(r.pop());var a=o.join("."),s=e+"=12345;domain=."+a;if(document.cookie=s,t.test(document.cookie))return document.cookie=s+";expires="+n,a}return i},t}(),o=function(){function e(e,t){this.observer=null,this.mutationObserver=null,this.elementsMap=new Map,this.config=e,this.callbacks=t}return e.prototype.updateConfig=function(e){this.config=n(n({},this.config),e)},e.prototype.init=function(){var e=this;this.config.autoTrackExposure&&("IntersectionObserver"in window?(this.observer=new IntersectionObserver((function(t){t.forEach((function(t){var n=t.target,i=e.elementsMap.get(n);if(i){var r=e.config.exposureTime||500;t.isIntersecting?(i.isVisible=!0,i.visibleStartTime=e.callbacks.getTimeStamp(),i.exposureTimer&&clearTimeout(i.exposureTimer),i.exposureTimer=window.setTimeout((function(){if(i.isVisible){var t=e.calculateexposureScreenIndex(n);e.callbacks.reportExposure(n,t)}}),r)):(i.isVisible=!1,i.exposureTimer&&(clearTimeout(i.exposureTimer),i.exposureTimer=null))}}))}),{threshold:this.config.exposureThreshold||.5}),this.observeExposureElements(),this.initMutationObserver()):this.config.showLog&&this.callbacks.printLog("当前浏览器不支持 IntersectionObserver,无法启用曝光埋点"))},e.prototype.stop=function(){this.observer&&(this.observer.disconnect(),this.observer=null,this.elementsMap.forEach((function(e){e.exposureTimer&&clearTimeout(e.exposureTimer)})),this.elementsMap.clear()),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.config.showLog&&this.callbacks.printLog("曝光监听已停止")},e.prototype.addExposureElement=function(e){this.elementsMap.has(e)||(this.elementsMap.set(e,{element:e,visibleStartTime:0,exposureCount:0,isVisible:!1,exposureTimer:null}),this.observer&&this.observer.observe(e))},e.prototype.observeExposureElements=function(){var e=this;if(this.observer){var t=document.querySelectorAll('[data-exposure="true"]');t.forEach((function(t){e.addExposureElement(t)})),this.config.showLog&&t.length>0&&this.callbacks.printLog("已监听 "+t.length+" 个曝光元素"),document.body||document.addEventListener("DOMContentLoaded",(function(){var t=document.querySelectorAll('[data-exposure="true"]');t.forEach((function(t){e.addExposureElement(t)})),e.config.showLog&&t.length>0&&e.callbacks.printLog("DOMContentLoaded 后监听 "+t.length+" 个曝光元素")}))}},e.prototype.initMutationObserver=function(){var e=this;"MutationObserver"in window?(this.mutationObserver=new MutationObserver((function(t){t.forEach((function(t){t.addedNodes.forEach((function(t){if(t.nodeType===Node.ELEMENT_NODE){var n=t;if(n.hasAttribute("data-exposure")&&"true"===n.getAttribute("data-exposure"))e.addExposureElement(n);else n.querySelectorAll('[data-exposure="true"]').forEach((function(t){e.addExposureElement(t)}))}}))}))})),document.body?(this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),this.config.showLog&&this.callbacks.printLog("MutationObserver 已启动,监听动态添加的曝光元素")):document.addEventListener("DOMContentLoaded",(function(){e.mutationObserver&&document.body&&(e.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),e.config.showLog&&e.callbacks.printLog("MutationObserver 已启动,监听动态添加的曝光元素"))}))):this.config.showLog&&this.callbacks.printLog("当前浏览器不支持 MutationObserver,无法监听动态添加的曝光元素")},e.prototype.calculateexposureScreenIndex=function(e){var t=e.getBoundingClientRect(),n=window.innerHeight||document.documentElement.clientHeight,i=window.scrollY||document.documentElement.scrollTop,r=t.top+i;return r<=0?1:Math.ceil(r/n)},e.prototype.getElementInfo=function(e){return this.elementsMap.get(e)},e.prototype.incrementExposureCount=function(e){var t=this.elementsMap.get(e);t&&t.exposureCount++},e.prototype.clearExposureTimer=function(e){var t=this.elementsMap.get(e);t&&t.exposureTimer&&(clearTimeout(t.exposureTimer),t.exposureTimer=null)},e}(),a=function(){function e(e,t){this.timer=null,this.config=e,this.callbacks=t}return e.prototype.updateConfig=function(e){var t=this.config.pageDurationInterval;this.config=n(n({},this.config),e),void 0!==e.pageDurationInterval&&e.pageDurationInterval!==t&&null!==this.timer&&(this.stop(),this.start())},e.prototype.start=function(){var e=this;this.stop();var t=this.config.pageDurationInterval||3e4;t<=0?this.config.showLog&&this.callbacks.printLog("定时上报间隔时间无效,已禁用定时上报"):(this.timer=window.setInterval((function(){"visible"===document.visibilityState&&e.callbacks.track(t,{desc:"定时上报页面停留时长"},!0).catch((function(t){e.config.showLog&&e.callbacks.printLog("定时上报页面停留时长失败: "+t)}))}),t),this.config.showLog&&this.callbacks.printLog("定时上报页面停留时长已启动,间隔: "+t+"ms"))},e.prototype.stop=function(){null!==this.timer&&(clearInterval(this.timer),this.timer=null,this.config.showLog&&this.callbacks.printLog("定时上报页面停留时长已停止"))},e.prototype.calculateDuration=function(e){if(null!=e)return Math.max(e,0);var t=this.callbacks.getCookie("retainedStartTime"),n=t?+t:this.callbacks.getTimeStamp(),i=this.callbacks.getTimeStamp();return Math.max(i-n,0)},e}(),s=function(){function e(e,t){this.timer=null,this.isFlushingQueue=!1,this.config=e,this.callbacks=t}return e.prototype.start=function(){var e=this;this.config.batchSend&&(this.clearTimer(),this.timer=window.setInterval((function(){e.flushQueue()}),this.config.batchInterval))},e.prototype.updateConfig=function(e){this.config=n(n({},this.config),e),this.clearTimer(),this.start()},e.prototype.addToQueue=function(e){if(this.config.batchSend)if(this.callbacks.shouldSample()){var t=this.getQueueFromStorage();t.push(e),this.saveQueueToStorage(t),t.length>=this.config.batchMaxSize&&this.flushQueue()}else this.config.showLog&&this.callbacks.printLog("数据已采样跳过(批量模式)")},e.prototype.clearTimer=function(){null!==this.timer&&(clearInterval(this.timer),this.timer=null)},e.prototype.clearQueue=function(){this.callbacks.setLocalStorage("web_tracking_batch_queue","[]"),this.config.showLog&&this.callbacks.printLog("批量队列已清空")},e.prototype.restoreQueue=function(){var e=this.getQueueFromStorage();e.length>0&&this.config.showLog&&this.callbacks.printLog("从 LocalStorage 恢复 "+e.length+" 条批量数据")},e.prototype.getQueueFromStorage=function(){try{var e=this.callbacks.getLocalStorage("web_tracking_batch_queue");if(e){var t=JSON.parse(e);if(Array.isArray(t))return t}}catch(e){this.callbacks.printLog("读取批量队列失败: "+e),this.callbacks.setLocalStorage("web_tracking_batch_queue","[]")}return[]},e.prototype.saveQueueToStorage=function(e){try{var t=JSON.stringify(e);if(t.length>4194304){var n=Math.floor(.8*e.length),i=e.slice(-n);this.callbacks.printLog("队列过大,已截断保留最新 "+n+" 条数据(限制: 4MB)"),this.callbacks.setLocalStorage("web_tracking_batch_queue",JSON.stringify(i))}else this.callbacks.setLocalStorage("web_tracking_batch_queue",t)}catch(e){this.callbacks.printLog("保存批量队列到 LocalStorage 失败: "+e)}},e.prototype.flushQueue=function(){var e=this;if(!this.isFlushingQueue){var t=this.getQueueFromStorage();if(0!==t.length){var n=this.callbacks.getTimeStamp(),i=t.filter((function(e){return!e._nextRetryTime||e._nextRetryTime<=n}));if(0!==i.length){var r=t.filter((function(e){return!!e._nextRetryTime&&e._nextRetryTime>n}));this.saveQueueToStorage(r),this.isFlushingQueue=!0,this.sendBatchData(i,(function(){e.isFlushingQueue=!1}))}else this.config.showLog&&this.callbacks.printLog("批量队列中有 "+t.length+" 条数据等待重试")}}},e.prototype.sendBatchData=function(e,t){var n=this,i=this.config,r=i.serverUrl,o=i.contentType,a=i.showLog,s=i.sendMethod,c=i.header;a&&(this.callbacks.printLog("批量发送 "+e.length+" 条数据"),e.forEach((function(e){return n.callbacks.printLog(JSON.stringify(e))})));var u=this.callbacks.shouldUseBeacon(s,void 0,c),l=function(){t&&t()};if(u)try{var g=new Blob([JSON.stringify(e)],{type:o||"application/json"});navigator.sendBeacon(r,g)?(a&&this.callbacks.printLog("批量发送成功: "+e.length+" 条数据"),l()):(this.callbacks.printLog("批量发送失败: sendBeacon 返回 false,数据已重新加入队列"),this.retryBatchData(e),l())}catch(t){this.callbacks.printLog("批量发送失败: "+t+",数据已重新加入队列"),this.retryBatchData(e),l()}else this.callbacks.ajax({url:r,type:"POST",data:JSON.stringify({events:e}),contentType:o,credentials:!1,timeout:this.config.sendTimeout,cors:!0,success:function(){n.config.showLog&&n.callbacks.printLog("批量发送成功: "+e.length+" 条数据"),l()},error:function(t){n.callbacks.printLog("批量发送失败: "+t+",数据已重新加入队列"),n.retryBatchData(e),l()}})},e.prototype.retryBatchData=function(e){var t=this,n=this.getQueueFromStorage(),r=function(e){return e.event+"_"+e.itemKey+"_"+e.requestTime},o=new Set(n.map(r)),a=this.callbacks.getTimeStamp(),s=e.filter((function(e){var n=r(e);if(o.has(n))return!1;var i=(e._retryCount||0)+1;return i>3?(t.config.showLog&&t.callbacks.printLog("数据已达到最大重试次数,放弃重试: "+n),!1):(e._retryCount=i,e._nextRetryTime=a+1e3*Math.pow(2,i),o.add(n),!0)})),c=i(i([],s),n),u=2*this.config.batchMaxSize,l=c.length>u?c.slice(0,u):c;this.saveQueueToStorage(l),this.config.showLog&&this.callbacks.printLog("已将 "+s.length+" 条数据加入重试队列")},e}(),c=function(){function e(e){this.deviceId="",this.callbacks=e}return e.prototype.getDeviceId=function(){if(this.deviceId)return this.deviceId;var e=this.callbacks.getCookie("device_id")||this.callbacks.getLocalStorage("device_id");if(e)return this.deviceId=e,this.deviceId;var t=this.callbacks.collectFingerprint(),n=this.callbacks.hashFingerprint(t);return this.callbacks.setCookie("device_id",n,730),this.callbacks.setLocalStorage("device_id",n),this.deviceId=n,this.deviceId},e.prototype.resetDeviceId=function(){return document.cookie="device_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",localStorage.removeItem("device_id"),this.deviceId="",this.getDeviceId()},e}(),u=function(){function e(e,t){this.isFlushingPendingData=!1,this.isUnloadListenerSetup=!1,this.config=e,this.callbacks=t}return e.prototype.updateConfig=function(e){this.config=n(n({},this.config),e)},e.prototype.addToQueue=function(e){var t=this.getQueueFromStorage();t.push(e);var n=this.config.pendingRequestsMaxSize||50;if(t.length>n){var i=t.slice(-n);this.config.showLog&&this.callbacks.printLog("待发送请求队列已满,已移除最旧的数据(最大限制: "+n+")"),this.saveQueueToStorage(i)}else this.saveQueueToStorage(t)},e.prototype.restoreQueue=function(){var e=this.getQueueFromStorage();e.length>0&&this.config.showLog&&this.callbacks.printLog("从 LocalStorage 恢复 "+e.length+" 条待发送请求")},e.prototype.flushQueue=function(){var e=this,t=this.getQueueFromStorage();if(0!==t.length){this.saveQueueToStorage([]);var n=this.config,i=n.serverUrl,r=n.sendTimeout,o=n.contentType,a=n.showLog,s=n.header;t.forEach((function(t){e.callbacks.shouldSample()?(a&&e.callbacks.printLog(JSON.stringify(t)),e.callbacks.ajax({url:i,type:"POST",data:JSON.stringify(t),contentType:o,header:s,credentials:!1,timeout:r,cors:!0,success:function(){a&&e.callbacks.printLog("待发送请求发送成功")},error:function(t){a&&e.callbacks.printLog("待发送请求发送失败(不再重试): "+t)}})):a&&e.callbacks.printLog("待发送请求已采样跳过")}))}},e.prototype.flushQueueWithBeacon=function(){var e=this;if(!this.isFlushingPendingData){this.isFlushingPendingData=!0;var t=this.getQueueFromStorage();if(0!==t.length){var n=this.config,i=n.serverUrl,r=n.contentType,o=n.showLog,a=0,s=0;t.forEach((function(t){e.sendWithBeacon(t,i,r)?a++:s++})),o&&this.callbacks.printLog("页面卸载时发送待请求数据: 成功 "+a+" 条,失败 "+s+" 条"),this.isFlushingPendingData=!1}else this.isFlushingPendingData=!1}},e.prototype.setupUnloadListener=function(){var e=this;this.isUnloadListenerSetup||(this.isUnloadListenerSetup=!0,document.addEventListener("visibilitychange",(function(){e.isPageUnloading()&&e.flushQueueWithBeacon()})),window.addEventListener("beforeunload",(function(){e.flushQueueWithBeacon()})),window.addEventListener("pagehide",(function(){e.flushQueueWithBeacon()})))},e.prototype.getQueueFromStorage=function(){try{var e=this.callbacks.getLocalStorage("web_tracking_pending_requests");if(e){var t=JSON.parse(e);if(Array.isArray(t))return t}}catch(e){this.callbacks.printLog("读取待发送请求失败: "+e),this.callbacks.setLocalStorage("web_tracking_pending_requests","[]")}return[]},e.prototype.saveQueueToStorage=function(e){try{this.callbacks.setLocalStorage("web_tracking_pending_requests",JSON.stringify(e))}catch(e){this.callbacks.printLog("保存待发送请求到 LocalStorage 失败: "+e)}},e.prototype.isPageUnloading=function(){return"hidden"===document.visibilityState},e.prototype.sendWithBeacon=function(e,t,n){try{var i=new Blob([JSON.stringify(e)],{type:n||"application/json"});return navigator.sendBeacon(t,i)}catch(e){return this.config.showLog&&this.callbacks.printLog("sendBeacon 发送失败: "+e),!1}},e}(),l=new(function(i){function r(){var t=i.call(this)||this;return t.useCustomPageKey=!1,t.userInfo=null,t.currentUrl="",t.pageKey="",t.deviceId="",t.eventDescMap={PageView:"Web 浏览页面",WebClick:"Web 元素点击",PageRetained:"Web 页面浏览时长",CustomTrack:"Web 自定义代码上报",WebExposure:"Web 元素曝光"},t.init=function(e){t.preset(e);var n=window.location.pathname;t.currentUrl=window.location.href,e.pageKey?(t.pageKey=e.pageKey,t.useCustomPageKey=!0):(t.pageKey=n.replace(/\//g,"_").substring(1),t.useCustomPageKey=!1),t.systemsInfo=t.getSystemsInfo(e.platform),t.deviceId=t.deviceManager.getDeviceId(),e.userInfo&&t.isObject(e.userInfo)&&(t.userInfo=e.userInfo),t.setCookie("retainedStartTime",t.getTimeStamp()),t.initConfig.batchSend&&t.batchSender.restoreQueue(),t.pendingRequestsManager.restoreQueue(),t.pendingRequestsManager.setupUnloadListener();var i=t.getAutoTrackConfig();t.currentAutoTrackConfig=i,i.retained&&t.pageDurationTracker.start(),i.exposure&&t.exposureTracker.init()},t.preset=function(i){if(i instanceof Object){if(void 0!==i.pageKey)if(null===i.pageKey||""===i.pageKey){t.useCustomPageKey=!1;var r=window.location.pathname;t.pageKey=r.replace(/\//g,"_").substring(1)}else t.pageKey=i.pageKey,t.useCustomPageKey=!0;t.each(i,(function(i,r){if("pageKey"!==r){if("autoTrack"===r&&"object"===e(i)&&null!==i){var o=i;return t.initConfig.autoTrack=n(n({},t.currentAutoTrackConfig),o),void(t.currentAutoTrackConfig=t.getAutoTrackConfig())}if(t.initConfig.hasOwnProperty(r)){var a=t.validateConfigParam(String(r),i);a.valid?t.initConfig[r]=i:console.warn("配置参数验证失败: "+String(r)+" = "+i+", 原因: "+a.message)}}}))}/^(((ht|f)tps?):\/\/)?[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:/~+#\(\)]*[\w\-\.,@?^=%&/~+#\(\)])?$/.test(t.initConfig.serverUrl)||console.warn("当前 server_url 为空或不正确,只在控制台打印日志,network 中不会发数据,请配置正确的 server_url!"),t.initConfig.autoTrack||t.initConfig.trackPartKeyClick?t.listener():t.unlistener(),t.batchSender.updateConfig({batchSend:t.initConfig.batchSend,batchInterval:t.initConfig.batchInterval,batchMaxSize:t.initConfig.batchMaxSize,sendTimeout:t.initConfig.sendTimeout,serverUrl:t.initConfig.serverUrl,contentType:t.initConfig.contentType,showLog:t.initConfig.showLog,sendMethod:t.initConfig.sendMethod,header:t.initConfig.header}),t.pendingRequestsManager.updateConfig({pendingRequestsMaxSize:t.initConfig.pendingRequestsMaxSize,sendTimeout:t.initConfig.sendTimeout,serverUrl:t.initConfig.serverUrl,contentType:t.initConfig.contentType,showLog:t.initConfig.showLog,header:t.initConfig.header});var o=t.getAutoTrackConfig();o.retained?(t.pageDurationTracker.updateConfig({pageDurationInterval:t.initConfig.pageDurationInterval,showLog:t.initConfig.showLog}),t.pageDurationTracker.start()):t.pageDurationTracker.stop(),o.exposure?(t.exposureTracker.updateConfig({autoTrackExposure:!0,exposureThreshold:t.initConfig.exposureThreshold,exposureTime:t.initConfig.exposureTime,exposureNum:t.initConfig.exposureNum,showLog:t.initConfig.showLog}),t.exposureTracker.init()):t.exposureTracker.stop()},t.validateConfigParam=function(t,n){switch(t){case"sampleRate":if("number"!=typeof n||n<0||n>1)return{valid:!1,message:"sampleRate 必须是 0-1 之间的数字"};break;case"sendTimeout":if("number"!=typeof n||n<=0)return{valid:!1,message:"sendTimeout 必须是大于 0 的数字"};break;case"batchInterval":if("number"!=typeof n||n<=0)return{valid:!1,message:"batchInterval 必须是大于 0 的数字"};break;case"batchMaxSize":if("number"!=typeof n||n<=0||!Number.isInteger(n))return{valid:!1,message:"batchMaxSize 必须是大于 0 的整数"};break;case"pendingRequestsMaxSize":if("number"!=typeof n||n<=0||!Number.isInteger(n))return{valid:!1,message:"pendingRequestsMaxSize 必须是大于 0 的整数"};break;case"pageDurationInterval":if("number"!=typeof n||n<=0)return{valid:!1,message:"pageDurationInterval 必须是大于 0 的数字"};break;case"sendMethod":if("string"!=typeof n||!["auto","xhr","beacon"].includes(n))return{valid:!1,message:"sendMethod 必须是 auto、xhr 或 beacon"};break;case"exposureThreshold":if("number"!=typeof n||n<0||n>1)return{valid:!1,message:"exposureThreshold 必须是 0-1 之间的数字"};break;case"exposureTime":if("number"!=typeof n||n<=0)return{valid:!1,message:"exposureTime 必须是大于 0 的数字"};break;case"exposureNum":if(void 0!==n&&("number"!=typeof n||n<=0||!Number.isInteger(n)))return{valid:!1,message:"exposureNum 必须是大于 0 的整数或不限制"};break;case"showLog":case"isTrackSinglePage":case"batchSend":if("boolean"!=typeof n)return{valid:!1,message:t+" 必须是布尔值"};break;case"autoTrack":if("boolean"!=typeof n&&"object"!==e(n))return{valid:!1,message:"autoTrack 必须是布尔值或对象"};if("object"===e(n)&&null!==n){var i=n,r=["view","click","exposure","retained"];for(var o in i){if(!r.includes(o))return{valid:!1,message:"autoTrack 对象中包含无效的属性: "+o};if("boolean"!=typeof i[o])return{valid:!1,message:"autoTrack."+o+" 必须是布尔值"}}}break;case"business":case"header":if(null!==n&&"object"!==e(n))return{valid:!1,message:t+" 必须是对象或 null"};break;case"contentType":if("application/json"!==n&&"application/x-www-form-urlencoded"!==n)return{valid:!1,message:"contentType 必须是 application/json 或 application/x-www-form-urlencoded"};break;case"platform":if("string"!=typeof n)return{valid:!1,message:"platform 必须是字符串"}}return{valid:!0}},t.getAutoTrackConfig=function(){var n,i,r,o,a=t.initConfig.autoTrack;return"boolean"==typeof a?{view:a,click:a,exposure:a,retained:a}:"object"===e(a)&&null!==a?{view:null!==(n=a.view)&&void 0!==n&&n,click:null!==(i=a.click)&&void 0!==i&&i,exposure:null!==(r=a.exposure)&&void 0!==r&&r,retained:null!==(o=a.retained)&&void 0!==o&&o}:{view:!1,click:!1,exposure:!1,retained:!1}},t.login=function(e){t.isObject(e)&&(t.userInfo=e)},t.getDeviceId=function(){return t.deviceManager.getDeviceId()},t.resetDeviceId=function(){return t.deviceManager.resetDeviceId()},t.track=function(e){var n=e.desc,i=e.pageKey,r=e.partKey,o=e.business,a=e.header,s=t.getParams({desc:n,event:"CustomTrack",itemKey:t.getItemKey(r,i),privateParamMap:{business:o}});return t.sendData(s,a)},t.listener=function(){t.unlistener();var e=t.getAutoTrackConfig();e.view&&(t.initConfig.isTrackSinglePage&&(t.rewriteHistory(),t.addSinglePageEvent(t.onPageViewCallback)),t.each(["load","beforeunload"],(function(e){t.addEventListener(window,e,t.onPageViewCallback)}))),e.click&&t.addEventListener(window,"click",t.onClickCallback)},t.unlistener=function(){if(t.initConfig.isTrackSinglePage){var e=window.history.pushState?"popstate":"hashchange";t.each(["pushState","replaceState",e],(function(e){t.removeEventListener(window,e,t.onPageViewCallback)}))}t.each(["load","beforeunload"],(function(e){t.removeEventListener(window,e,t.onPageViewCallback)})),t.removeEventListener(window,"click",t.onClickCallback),t.batchSender.clearTimer(),t.pageDurationTracker.stop()},t.clearBatchTimer=function(){t.batchSender.clearTimer()},t.clearBatchQueue=function(){t.batchSender.clearQueue()},t.setPageKey=function(e,n){if(void 0===n&&(n=!1),null===e||""===e){t.useCustomPageKey=!1;var i=window.location.pathname;t.pageKey=i.replace(/\//g,"_").substring(1),t.initConfig.showLog&&t.printLog("页面标识已恢复自动生成: "+t.pageKey)}else t.pageKey=e,t.useCustomPageKey=!n,t.initConfig.showLog&&t.printLog("页面标识已设置为: "+e+", 自动更新: "+n)},t.getPageKey=function(){return t.pageKey},t.onClickCallback=function(e){var n,i=e.target;if(null===(n=null==i?void 0:i.dataset)||void 0===n?void 0:n.partKey){var r=[e.pageX,e.pageY],o=i.id,a=i.className,s=t.extractDataAttributes(i),c=i.getAttribute("data-desc")||t.eventDescMap.WebClick,u=i.getAttribute("data-part-key"),l=i.getAttribute("data-page-key")||void 0,g=t.getParams({event:"WebClick",desc:c,itemKey:t.getItemKey(u,l),privateParamMap:{business:s,targetEle:{nodeName:i.nodeName,id:o,className:a,position:r}}});t.sendData(g)}},t.onPageViewCallback=function(e){var n,i,r=window.location.origin,o=t.getParams({event:"PageView",desc:t.eventDescMap.PageView,privateParamMap:{currentUrl:t.currentUrl,targetUrl:(null===(n=e.arguments)||void 0===n?void 0:n[2])?r+(null===(i=e.arguments)||void 0===i?void 0:i[2]):null}});t.currentUrl=window.location.href,t.useCustomPageKey||(t.pageKey=window.location.pathname.replace(/\//g,"_").substring(1)),t.getAutoTrackConfig().retained&&(t.pageDurationTracker.stop(),t.pageDurationTracker.start()),t.sendData(o)},t.getParams=function(e){var n=e.event,i=e.desc,r=e.privateParamMap,o=void 0===r?{}:r,a=e.itemKey,s=t.initConfig.business,c=window.innerWidth,u=window.innerHeight,l=window.screen.width,g=window.screen.height,p=t.filterSensitiveData(s||{}),d=t.filterSensitiveData(t.userInfo||{}),h=t.filterSensitiveData(o||{}),f=t.filterSensitiveData(t.getQueryValue()||{}),v={currentUrl:h.currentUrl||t.currentUrl,business:Object.assign({},p,h.business||{}),pageWidth:c,pageHeight:u,screenWidth:l,screenHeight:g,sdkVersion:t.sdkVersion,systemsInfo:t.systemsInfo,urlParams:f,userInfo:d,deviceId:t.deviceId};return h.targetEle&&(v.targetEle=h.targetEle),h.targetUrl&&(v.targetUrl=h.targetUrl),h.pointerType&&(v.pointerType=h.pointerType),h.elementSelector&&(v.elementSelector=h.elementSelector),h.retainedDuration&&(v.retainedDuration=h.retainedDuration),void 0!==h.exposureScreenNo&&(v.exposureScreenNo=h.exposureScreenNo),{event:n,desc:i,itemKey:a||t.getItemKey(),requestTime:t.getTimeStamp(),privateParamMap:v}},t.shouldSample=function(){var e=t.initConfig.sampleRate;return e>=1||!(e<=0)&&Math.random()<e},t.shouldUseBeacon=function(e,t,n){return"beacon"===e||"xhr"!==e&&(!t&&!n&&"function"==typeof navigator.sendBeacon)},t.sendData=function(e,n){return new Promise((function(i,r){if(!t.shouldSample())return t.initConfig.showLog&&t.printLog("数据已采样跳过"),void i({success:!1,message:"数据已采样跳过"});if(t.initConfig.showLog&&t.printLog(e),t.initConfig.batchSend)return t.batchSender.addToQueue(e),void i({success:!0,message:"数据已加入批量队列"});var o=t.initConfig,a=o.serverUrl,s=o.sendTimeout,c=o.contentType,u=o.showLog,l=o.header;t.shouldUseBeacon(t.initConfig.sendMethod,n,l)?t.sendWithBeacon(e,a,c)?i({success:!0,message:"数据发送成功"}):(t.pendingRequestsManager.addToQueue(e),i({success:!1,message:"sendBeacon 发送失败,数据已加入待发送队列"})):t.ajax({url:a,type:"POST",data:JSON.stringify(e),contentType:c,header:n||l,credentials:!1,timeout:s,cors:!0,success:function(e){u&&t.printLog("数据发送成功",e),i({success:!0,data:e})},error:function(n){u&&t.printLog("数据发送失败",n),t.pendingRequestsManager.addToQueue(e),r({success:!1,message:"数据发送失败",error:n})}})}))},t.sendWithBeacon=function(e,n,i){try{var r=new Blob([JSON.stringify(e)],{type:i||"application/json"});return navigator.sendBeacon(n,r)}catch(e){return t.initConfig.showLog&&t.printLog("sendBeacon 发送失败: "+e),!1}},t.trackPageDuration=function(e,n,i){void 0===i&&(i=!0);var r=t.pageDurationTracker.calculateDuration(e),o=(null==n?void 0:n.desc)||t.eventDescMap.PageRetained,a=(null==n?void 0:n.pageKey)||t.pageKey,s=(null==n?void 0:n.business)||{},c=null==n?void 0:n.header,u=t.getParams({event:"PageRetained",desc:o,itemKey:t.getItemKey(void 0,a),privateParamMap:{business:s,retainedDuration:r}}),l=t.sendData(u,c);return i&&t.setCookie("retainedStartTime",t.getTimeStamp()),l},t.getItemKey=function(e,n){var i=void 0!==n?n:t.pageKey,r=void 0!==e?e:"";return r?t.initConfig.appKey+"."+i+"."+r:t.initConfig.appKey+"."+i},t.extractDataAttributes=function(e){for(var t={},n=0;n<e.attributes.length;n++){var i=e.attributes[n].name;if(i.startsWith("data-")&&"data-exposure"!==i&&"data-part-key"!==i&&"data-desc"!==i&&"data-page-key"!==i)t[i.replace("data-","").replace(/-([a-z])/g,(function(e,t){return t.toUpperCase()}))]=e.getAttribute(i)}return t},t.handleExposureReport=function(e,n){var i=t.exposureTracker.getElementInfo(e);if(!i)return Promise.resolve();var r=t.initConfig.exposureNum;if(void 0!==r&&i.exposureCount>=r)return t.initConfig.showLog&&t.printLog("元素已达到最大曝光次数限制: "+r),Promise.resolve();var o=t.extractDataAttributes(e),a=e.getAttribute("data-desc")||t.eventDescMap.WebExposure,s=e.getAttribute("data-part-key")||"exposure",c=e.getAttribute("data-page-key")||void 0,u=t.getParams({event:"WebExposure",desc:a,itemKey:t.getItemKey(s,c),privateParamMap:{business:o,exposureScreenNo:n}});return t.sendData(u).then((function(){t.exposureTracker.incrementExposureCount(e),t.exposureTracker.clearExposureTimer(e),t.initConfig.showLog&&t.printLog("曝光上报成功,当前曝光次数: "+(i.exposureCount+1))})).catch((function(e){t.initConfig.showLog&&t.printLog("曝光上报失败: "+e)}))},t.sdkVersion="1.2.8",t.initConfig={appKey:"",platform:void 0,showLog:!1,serverUrl:"",autoTrack:!1,sendTimeout:3e3,isTrackSinglePage:!1,contentType:"application/json",business:{},header:void 0,sampleRate:1,batchSend:!1,batchInterval:5e3,batchMaxSize:10,pendingRequestsMaxSize:50,pageDurationInterval:3e4,sendMethod:"auto",exposureThreshold:.5,exposureTime:500,exposureNum:void 0},t.systemsInfo={},t.deviceManager=new c({getCookie:t.getCookie.bind(t),setCookie:t.setCookie.bind(t),getLocalStorage:t.getLocalStorage.bind(t),setLocalStorage:t.setLocalStorage.bind(t),collectFingerprint:t.collectFingerprint.bind(t),hashFingerprint:t.hashFingerprint.bind(t)}),t.batchSender=new s({batchSend:!1,batchInterval:5e3,batchMaxSize:10,sendTimeout:3e3,serverUrl:"",contentType:"application/json",showLog:!1,sendMethod:"auto",header:void 0},{getLocalStorage:t.getLocalStorage.bind(t),setLocalStorage:t.setLocalStorage.bind(t),getTimeStamp:t.getTimeStamp.bind(t),ajax:t.ajax.bind(t),shouldSample:t.shouldSample.bind(t),shouldUseBeacon:t.shouldUseBeacon.bind(t),printLog:t.printLog.bind(t)}),t.pendingRequestsManager=new u({pendingRequestsMaxSize:50,sendTimeout:3e3,serverUrl:"",contentType:"application/json",showLog:!1,header:void 0},{getLocalStorage:t.getLocalStorage.bind(t),setLocalStorage:t.setLocalStorage.bind(t),shouldSample:t.shouldSample.bind(t),ajax:t.ajax.bind(t),printLog:t.printLog.bind(t)}),t.pageDurationTracker=new a({pageDurationInterval:3e4,showLog:!1},{getCookie:t.getCookie.bind(t),setCookie:t.setCookie.bind(t),getTimeStamp:t.getTimeStamp.bind(t),track:t.trackPageDuration.bind(t),printLog:t.printLog.bind(t)}),t.exposureTracker=new o({autoTrackExposure:!1,exposureThreshold:.5,exposureTime:500,exposureNum:void 0,showLog:!1},{reportExposure:t.handleExposureReport.bind(t),printLog:t.printLog.bind(t),getTimeStamp:t.getTimeStamp.bind(t),extractDataAttributes:t.extractDataAttributes.bind(t)}),t}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function i(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}(r,i),r.prototype.printLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.initConfig.showLog&&i.prototype.printLog.apply(this,e)},r.prototype.addSinglePageEvent=function(e){var t=this,n=window.history.pushState?"popstate":"hashchange";this.each(["pushState","replaceState",n],(function(n){t.addEventListener(window,n,e)}))},r}(r));export default l;
|
|
1
|
+
function e(t){return(e="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})(t)}var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,n)};var n=function(){return(n=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)};function i(e,t){for(var n=0,i=t.length,r=e.length;n<i;n++,r++)e[r]=t[n];return e}var r=function(){function t(){var t=this;this.getSystemsInfo=function(e){var t=navigator.userAgent,n="other",i=[],r={language:navigator.language},o=t.match(/MicroMessenger\/([\d\.]+)/i),a=o&&o[1]?o[1]:null,s=t.match(/(ipod).*\s([\d_]+)/i),c=t.match(/(ipad).*\s([\d_]+)/i),u=t.match(/(iphone)\sos\s([\d_]+)/i),l=t.match(/(android)\s([\d\.]+)/i),g=t.match(/(Windows NT)\s([\d\.]+)/i),p=t.match(/(Mac OS X)\s([\d_]+)/i);i=[],l?(i.push("Android "+l[2]),n="h5"):u?(i.push("iPhone, iOS "+u[2].replace(/_/g,".")),n="h5"):c?(i.push("iPad, iOS "+c[2].replace(/_/g,".")),n="ipad"):s?(i.push("iPod, iOS "+s[2].replace(/_/g,".")),n="h5"):g?(i.push("Windows "+g[2].replace(/_/g,".")),n="pc"):p&&(i.push("Mac, MacOS "+p[2].replace(/_/g,".")),n="pc"),a&&i.push("WeChat "+a),r.client=i.length?i.join(", "):"Unknown",r.platform=e||n;var d=t.toLowerCase().match(/ nettype\/([^ ]+)/g);return d&&d[0]&&(i=[(d=d[0].split("/"))[1]],r.network=i.length?i.join(", "):"Unknown"),r.ua=t,r},this.addEventListener=function(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent&&e.attachEvent("on"+t,(function(t){return n.call(e,t)}),!1)},this.removeEventListener=function(e,t,n){e.removeEventListener?e.removeEventListener(t,n):e.detachEvent&&e.detachEvent("on"+t,(function(t){return n.call(e,t)}),!0)},this.rewriteHistory=function(){var e=window.history,t=function(e){var t=window.history,n=t[e],i=new Event(e);return function(){var e=n.apply(t,arguments);return i.arguments=arguments,window.dispatchEvent(i),e}};window.history.pushState&&(e.pushState=t("pushState"),e.replaceState=t("replaceState"))},this.isArray=Array.isArray||function(e){return"[object Array]"===toString.call(e)},this.formatJsonString=function(e){try{return JSON.stringify(e,null," ")}catch(t){return JSON.stringify(e)}},this.nativeForEach=Array.prototype.forEach,this.slice=Array.prototype.slice,this.hasOwnProperty=Object.prototype.hasOwnProperty,this.breaker={},this.each=function(e,n,i){if(null==e)return!1;if(t.nativeForEach&&e.forEach===t.nativeForEach)e.forEach(n,i);else if(t.isArray(e)&&e.length===+e.length){for(var r=0,o=e.length;r<o;r++)if(r in e&&n.call(i,e[r],r,e)===t.breaker)return!1}else for(var a in e)if(t.hasOwnProperty.call(e,a)&&n.call(i,e[a],a,e)===t.breaker)return!1;return!0},this.getDomIndex=function(e){if(!e.parentNode)return-1;for(var t=0,n=e.tagName,i=e.parentNode.children,r=0;r<i.length;r++)if(i[r].tagName===n){if(e===i[r])return t;t++}return-1},this.selector=function(e){var n=e.parentNode&&9==e.parentNode.nodeType?-1:t.getDomIndex(e);return e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?"#"+e.getAttribute("id"):e.tagName.toLowerCase()+(~n?":nth-of-type("+(n+1)+")":"")},this.getDomSelector=function(e,n){if(!e||!e.parentNode||!e.parentNode.children)return!1;n=n&&n.join?n:[];var i=e.nodeName.toLowerCase();return e&&"body"!==i&&1==e.nodeType?(n.unshift(t.selector(e)),e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?n.join(" > "):t.getDomSelector(e.parentNode,n)):(n.unshift("body"),n.join(" > "))},this.getCookie=function(e){for(var t=e+"=",n=document.cookie.split(";"),i=0;i<n.length;i++){for(var r=n[i];" "==r.charAt(0);)r=r.substring(1,r.length);if(0==r.indexOf(t))return this._decodeURIComponent(r.substring(t.length,r.length))}return null},this.setCookie=function(e,t,n){var i,r="";n=null==n?73e3:n;var o=this.getMainHost();if(i=o?"; domain="+o:"",0!==n){var a=new Date;"s"===String(n).slice(-1)?a.setTime(a.getTime()+1e3*Number(String(n).slice(0,-1))):a.setTime(a.getTime()+24*n*60*60*1e3),r="; expires="+a.toUTCString()}function s(e){return e||!1}var c="",u="",l="";e&&(c=s(e)),t&&(u=s(t)),i&&(l=s(i)),c&&u&&(document.cookie=c+"="+encodeURIComponent(u)+r+"; path=/"+l)},this.getLocalStorage=function(e){try{return localStorage.getItem(e)}catch(e){return null}},this.setLocalStorage=function(e,t){try{localStorage.setItem(e,t)}catch(e){}},this.removeCookie=function(e){t.setCookie(e,"",-1)},this.getTimeStamp=function(){return(new Date).getTime()},this.uuid=function(){return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},this.getDistinctId=function(){var e=t.getCookie("distinctId");return e||(e=t.uuid(),t.setCookie("distinctId",e),e)},this.filterSensitiveData=function(e,n){if(void 0===n&&(n=["password","token","secret"]),!t.isObject(e))return e;var i={};return t.each(e,(function(e,r){n.some((function(e){return"string"==typeof r&&r.toLowerCase().includes(e.toLowerCase())}))?i[r]="***":t.isObject(e)?i[r]=t.filterSensitiveData(e,n):i[r]=e})),i},this.xssFilter=function(e){return e?"string"!=typeof e?e.toString():e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/"):""},this.getQueryValue=function(){for(var e=decodeURI(window.location.href).match(new RegExp("[?&][^?&]+=[^?&]+","g"))||[],t={},n=0;n<e.length;n++){var i=e[n].replace(/\?|\&/,"").split("=");t[i[0]]=i[1]}return Object.keys(t).length>0?t:null},this.ajax=function(n){function i(t){if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)}catch(e){return{}}return"object"===e(t)?t:{}}n.timeout=n.timeout||3e4,n.credentials=void 0===n.credentials||n.credentials;var r=t.xhr(n.cors);if(!r)return!1;n.type||(n.type=n.data?"POST":"GET");var o,a=n.success,s=n.error;n.success=function(e){a&&a(e),o&&(clearTimeout(o),o=null)},n.error=function(e,t){s&&s(e,t),o&&(clearTimeout(o),o=null)},o=window.setTimeout((function(){!function(){try{t.isObject(r)&&r.abort&&r.abort()}catch(e){t.printLog(e)}o&&(clearTimeout(o),o=null,n.error&&n.error(),r.onreadystatechange=null,r.onload=null,r.onerror=null)}()}),n.timeout),r.onreadystatechange=function(){try{4==r.readyState&&(r.status>=200&&r.status<300||304==r.status?n.success&&n.success(i(r.responseText)):n.error&&n.error(i(r.responseText),r.status),r.onreadystatechange=null,r.onload=null)}catch(e){r.onreadystatechange=null,r.onload=null}},r.open(n.type||"GET",n.url,!0);try{if(n.credentials&&(r.withCredentials=!0),t.isObject(n.header)&&t.each(n.header,(function(e,t){r.setRequestHeader&&r.setRequestHeader(t,e)})),n.data)n.cors||r.setRequestHeader&&r.setRequestHeader("X-Requested-With","XMLHttpRequest"),t.isObject(n.header)&&Object.keys(n.header).some((function(e){return"content-type"===e.toLowerCase()||"content-type"===e.toLowerCase()}))||("application/json"===n.contentType?r.setRequestHeader&&r.setRequestHeader("Content-type","application/json; charset=UTF-8"):r.setRequestHeader&&r.setRequestHeader("Content-type","application/x-www-form-urlencoded"))}catch(e){t.printLog(e)}r.send(n.data||null)},this.xhr=function(e){return e?void 0!==window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?new XMLHttpRequest:null:void 0!==window.XMLHttpRequest?new XMLHttpRequest:null},this.getUA=function(){var e,t={},n=navigator.userAgent.toLowerCase();return(e=n.match(/opera.([\d.]+)/))?t.opera=Number(e[1].split(".")[0]):(e=n.match(/msie ([\d.]+)/))?t.ie=Number(e[1].split(".")[0]):(e=n.match(/edge.([\d.]+)/))?t.edge=Number(e[1].split(".")[0]):(e=n.match(/firefox\/([\d.]+)/))?t.firefox=Number(e[1].split(".")[0]):(e=n.match(/chrome\/([\d.]+)/))?t.chrome=Number(e[1].split(".")[0]):(e=n.match(/version\/([\d.]+).*safari/))?t.safari=Number(e[1].match(/^\d*.\d*/)):(e=n.match(/trident\/([\d.]+)/))&&(t.ie=11),t},this.isSupportBeaconSend=function(){var n=!1;if("object"!==("undefined"==typeof navigator?"undefined":e(navigator))||"function"!=typeof navigator.sendBeacon)return n;var i=t.getUA(),r=navigator.userAgent.toLowerCase();if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){var o=(r.match(/os [\d._]*/gi)+"").replace(/[^0-9|_.]/gi,"").replace(/_/gi,".").split(".");void 0===i.safari&&(i.safari=Number(o[0])),o[0]&&+o[0]<13?(i.chrome>41||i.firefox>30||i.opera>25||i.safari>12)&&(n=!0):(i.chrome>41||i.firefox>30||i.opera>25||i.safari>11.3)&&(n=!0)}else(i.chrome>38||i.edge>13||i.firefox>30||i.opera>25||i.safari>11)&&(n=!0);return n},this.throttle=function(e,t){var n=null,i=0;return function(){for(var r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var a=Date.now(),s=t-(a-i);s<=0||s>t?(n&&(clearTimeout(n),n=null),i=a,e.apply(void 0,r)):n||(n=window.setTimeout((function(){i=Date.now(),n=null,e.apply(void 0,r)}),s))}},this.debounce=function(e,t){var n=null;return function(){for(var i=[],r=0;r<arguments.length;r++)i[r]=arguments[r];n&&clearTimeout(n),n=window.setTimeout((function(){e.apply(void 0,i)}),t)}},this.sendBeacon=function(e){if(!0===t.isSupportBeaconSend()){var n={type:e.contentType},i=new Blob([JSON.stringify(e.data)],n);return navigator.sendBeacon(e.url,i)?Promise.resolve({success:!0,message:"发送成功"}):Promise.reject({success:!1,message:"sendBeacon返回false"})}return Promise.reject({success:!1,message:"不支持sendBeacon,发送失败!"})},this.getDeviceId=function(){var e=t.getCookie("device_id")||t.getLocalStorage("device_id");if(e)return e;var n=t.collectFingerprint(),i=t.hashFingerprint(n);return t.setCookie("device_id",i,730),t.setLocalStorage("device_id",i),i},this.collectFingerprint=function(){var e={};return e.userAgent=navigator.userAgent,e.screenWidth=screen.width,e.screenHeight=screen.height,e.colorDepth=screen.colorDepth,e.pixelDepth=screen.pixelDepth,e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,e.timezoneOffset=(new Date).getTimezoneOffset(),e.language=navigator.language,e.languages=Array.from(navigator.languages),e.platform=navigator.platform,e.webgl=t.getWebGLFingerprint(),e.canvas=t.getCanvasFingerprint(),e.audio=t.getAudioFingerprint(),e.localStorage=t.hasLocalStorage(),e.sessionStorage=t.hasSessionStorage(),e.indexedDB=t.hasIndexedDB(),e.hardwareConcurrency=navigator.hardwareConcurrency,e.deviceMemory=navigator.deviceMemory,e.maxTouchPoints=navigator.maxTouchPoints,e},this.getWebGLFingerprint=function(){try{var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"not-supported";var n=t.getExtension("WEBGL_debug_renderer_info");return(n?t.getParameter(n.UNMASKED_VENDOR_WEBGL):"unknown")+"|"+(n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"unknown")}catch(e){return"error"}},this.getCanvasFingerprint=function(){try{var e=document.createElement("canvas");e.width=200,e.height=50;var t=e.getContext("2d");return t?(t.textBaseline="top",t.font="14px Arial",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("Canvas fingerprint",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("Canvas fingerprint",4,17),e.toDataURL().slice(-50)):"not-supported"}catch(e){return"error"}},this.getAudioFingerprint=function(){try{var e=window.AudioContext||window.webkitAudioContext;if(!e)return"not-supported";var t=new e,n=String(t.sampleRate||0);return t.close(),n}catch(e){return"error"}},this.hasLocalStorage=function(){try{var e="__test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}},this.hasSessionStorage=function(){try{var e="__test__";return sessionStorage.setItem(e,e),sessionStorage.removeItem(e),!0}catch(e){return!1}},this.hasIndexedDB=function(){return"indexedDB"in window&&null!==indexedDB},this.hashFingerprint=function(e){for(var t=JSON.stringify(e,Object.keys(e).sort()),n=5381,i=52711,r=0;r<t.length;r++){var o=t.charCodeAt(r);n=(n<<5)+n+o,i=(i<<5)+i+o}return"fp_"+(n>>>0).toString(16).padStart(8,"0")+(i>>>0).toString(16).padStart(8,"0")}}return t.prototype.printLog=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];if(this.isObject(t[0])&&(t[0]=this.formatJsonString(t[0])),"object"===("undefined"==typeof console?"undefined":e(console))&&console.log)try{return console.log.apply(console,t)}catch(e){console.log(t[0])}},t.prototype.isObject=function(e){return null!=e&&"[object Object]"==toString.call(e)},t.prototype.isUndefined=function(e){return void 0===e},t.prototype.isString=function(e){return"[object String]"==toString.call(e)},t.prototype.isDate=function(e){return"[object Date]"==toString.call(e)},t.prototype.isBoolean=function(e){return"[object Boolean]"==toString.call(e)},t.prototype.isNumber=function(e){return"[object Number]"==toString.call(e)&&/[\d\.]+/.test(String(e))},t.prototype.isElement=function(e){return!(!e||1!==e.nodeType)},t.prototype.isFunction=function(e){if(!e)return!1;var t=toString.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t},t.prototype.isJSONString=function(e){if(!this.isString(e))return!1;try{JSON.parse(e)}catch(e){return!1}return!0},t.prototype._decodeURIComponent=function(e){var t=e;try{t=decodeURIComponent(e)}catch(n){t=e}return t},t.prototype.getMainHost=function(){var e="mh_"+Math.random(),t=new RegExp("(^|;)\\s*"+e+"=12345"),n=new Date(0),i=document.domain,r=i.split("."),o=[];for(o.unshift(r.pop());r.length;){o.unshift(r.pop());var a=o.join("."),s=e+"=12345;domain=."+a;if(document.cookie=s,t.test(document.cookie))return document.cookie=s+";expires="+n,a}return i},t}(),o=function(){function e(e,t){this.observer=null,this.mutationObserver=null,this.elementsMap=new Map,this.config=e,this.callbacks=t}return e.prototype.updateConfig=function(e){this.config=n(n({},this.config),e)},e.prototype.init=function(){var e=this;this.config.autoTrackExposure&&("IntersectionObserver"in window?(this.observer=new IntersectionObserver((function(t){t.forEach((function(t){var n=t.target,i=e.elementsMap.get(n);if(i){var r=e.config.exposureTime||500;t.isIntersecting?(i.isVisible=!0,i.visibleStartTime=e.callbacks.getTimeStamp(),i.exposureTimer&&clearTimeout(i.exposureTimer),i.exposureTimer=window.setTimeout((function(){if(i.isVisible){var t=e.calculateexposureScreenIndex(n);e.callbacks.reportExposure(n,t)}}),r)):(i.isVisible=!1,i.exposureTimer&&(clearTimeout(i.exposureTimer),i.exposureTimer=null))}}))}),{threshold:this.config.exposureThreshold||.5}),this.observeExposureElements(),this.initMutationObserver()):this.config.showLog&&this.callbacks.printLog("当前浏览器不支持 IntersectionObserver,无法启用曝光埋点"))},e.prototype.stop=function(){this.observer&&(this.observer.disconnect(),this.observer=null,this.elementsMap.forEach((function(e){e.exposureTimer&&clearTimeout(e.exposureTimer)})),this.elementsMap.clear()),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.config.showLog&&this.callbacks.printLog("曝光监听已停止")},e.prototype.addExposureElement=function(e){this.elementsMap.has(e)||(this.elementsMap.set(e,{element:e,visibleStartTime:0,exposureCount:0,isVisible:!1,exposureTimer:null}),this.observer&&this.observer.observe(e))},e.prototype.observeExposureElements=function(){var e=this;if(this.observer){var t=document.querySelectorAll('[data-exposure="true"]');t.forEach((function(t){e.addExposureElement(t)})),this.config.showLog&&t.length>0&&this.callbacks.printLog("已监听 "+t.length+" 个曝光元素"),document.body||document.addEventListener("DOMContentLoaded",(function(){var t=document.querySelectorAll('[data-exposure="true"]');t.forEach((function(t){e.addExposureElement(t)})),e.config.showLog&&t.length>0&&e.callbacks.printLog("DOMContentLoaded 后监听 "+t.length+" 个曝光元素")}))}},e.prototype.initMutationObserver=function(){var e=this;"MutationObserver"in window?(this.mutationObserver=new MutationObserver((function(t){t.forEach((function(t){t.addedNodes.forEach((function(t){if(t.nodeType===Node.ELEMENT_NODE){var n=t;if(n.hasAttribute("data-exposure")&&"true"===n.getAttribute("data-exposure"))e.addExposureElement(n);else n.querySelectorAll('[data-exposure="true"]').forEach((function(t){e.addExposureElement(t)}))}}))}))})),document.body?(this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),this.config.showLog&&this.callbacks.printLog("MutationObserver 已启动,监听动态添加的曝光元素")):document.addEventListener("DOMContentLoaded",(function(){e.mutationObserver&&document.body&&(e.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),e.config.showLog&&e.callbacks.printLog("MutationObserver 已启动,监听动态添加的曝光元素"))}))):this.config.showLog&&this.callbacks.printLog("当前浏览器不支持 MutationObserver,无法监听动态添加的曝光元素")},e.prototype.calculateexposureScreenIndex=function(e){var t=e.getBoundingClientRect(),n=window.innerHeight||document.documentElement.clientHeight,i=window.scrollY||document.documentElement.scrollTop,r=t.top+i;return r<=0?1:Math.ceil(r/n)},e.prototype.getElementInfo=function(e){return this.elementsMap.get(e)},e.prototype.incrementExposureCount=function(e){var t=this.elementsMap.get(e);t&&t.exposureCount++},e.prototype.clearExposureTimer=function(e){var t=this.elementsMap.get(e);t&&t.exposureTimer&&(clearTimeout(t.exposureTimer),t.exposureTimer=null)},e}(),a=function(){function e(e,t){this.timer=null,this.config=e,this.callbacks=t}return e.prototype.updateConfig=function(e){var t=this.config.pageDurationInterval;this.config=n(n({},this.config),e),void 0!==e.pageDurationInterval&&e.pageDurationInterval!==t&&null!==this.timer&&(this.stop(),this.start())},e.prototype.start=function(){var e=this;this.stop();var t=this.config.pageDurationInterval||3e4;t<=0?this.config.showLog&&this.callbacks.printLog("定时上报间隔时间无效,已禁用定时上报"):(this.timer=window.setInterval((function(){"visible"===document.visibilityState&&e.callbacks.track(t,{desc:"定时上报页面停留时长"},!0).catch((function(t){e.config.showLog&&e.callbacks.printLog("定时上报页面停留时长失败: "+t)}))}),t),this.config.showLog&&this.callbacks.printLog("定时上报页面停留时长已启动,间隔: "+t+"ms"))},e.prototype.stop=function(){null!==this.timer&&(clearInterval(this.timer),this.timer=null,this.config.showLog&&this.callbacks.printLog("定时上报页面停留时长已停止"))},e.prototype.calculateDuration=function(e){if(null!=e)return Math.max(e,0);var t=this.callbacks.getCookie("retainedStartTime"),n=t?+t:this.callbacks.getTimeStamp(),i=this.callbacks.getTimeStamp();return Math.max(i-n,0)},e}(),s=function(){function e(e,t){this.timer=null,this.isFlushingQueue=!1,this.config=e,this.callbacks=t}return e.prototype.start=function(){var e=this;this.config.batchSend&&(this.clearTimer(),this.timer=window.setInterval((function(){e.flushQueue()}),this.config.batchInterval))},e.prototype.updateConfig=function(e){this.config=n(n({},this.config),e),this.clearTimer(),this.start()},e.prototype.addToQueue=function(e){if(this.config.batchSend)if(this.callbacks.shouldSample()){var t=this.getQueueFromStorage();t.push(e),this.saveQueueToStorage(t),t.length>=this.config.batchMaxSize&&this.flushQueue()}else this.config.showLog&&this.callbacks.printLog("数据已采样跳过(批量模式)")},e.prototype.clearTimer=function(){null!==this.timer&&(clearInterval(this.timer),this.timer=null)},e.prototype.clearQueue=function(){this.callbacks.setLocalStorage("web_tracking_batch_queue","[]"),this.config.showLog&&this.callbacks.printLog("批量队列已清空")},e.prototype.restoreQueue=function(){var e=this.getQueueFromStorage();e.length>0&&this.config.showLog&&this.callbacks.printLog("从 LocalStorage 恢复 "+e.length+" 条批量数据")},e.prototype.getQueueFromStorage=function(){try{var e=this.callbacks.getLocalStorage("web_tracking_batch_queue");if(e){var t=JSON.parse(e);if(Array.isArray(t))return t}}catch(e){this.callbacks.printLog("读取批量队列失败: "+e),this.callbacks.setLocalStorage("web_tracking_batch_queue","[]")}return[]},e.prototype.saveQueueToStorage=function(e){try{var t=JSON.stringify(e);if(t.length>4194304){var n=Math.floor(.8*e.length),i=e.slice(-n);this.callbacks.printLog("队列过大,已截断保留最新 "+n+" 条数据(限制: 4MB)"),this.callbacks.setLocalStorage("web_tracking_batch_queue",JSON.stringify(i))}else this.callbacks.setLocalStorage("web_tracking_batch_queue",t)}catch(e){this.callbacks.printLog("保存批量队列到 LocalStorage 失败: "+e)}},e.prototype.flushQueue=function(){var e=this;if(!this.isFlushingQueue){var t=this.getQueueFromStorage();if(0!==t.length){var n=this.callbacks.getTimeStamp(),i=t.filter((function(e){return!e._nextRetryTime||e._nextRetryTime<=n}));if(0!==i.length){var r=t.filter((function(e){return!!e._nextRetryTime&&e._nextRetryTime>n}));this.saveQueueToStorage(r),this.isFlushingQueue=!0,this.sendBatchData(i,(function(){e.isFlushingQueue=!1}))}else this.config.showLog&&this.callbacks.printLog("批量队列中有 "+t.length+" 条数据等待重试")}}},e.prototype.sendBatchData=function(e,t){var n=this,i=this.config,r=i.serverUrl,o=i.contentType,a=i.showLog,s=i.sendMethod,c=i.header;a&&(this.callbacks.printLog("批量发送 "+e.length+" 条数据"),e.forEach((function(e){return n.callbacks.printLog(JSON.stringify(e))})));var u=this.callbacks.shouldUseBeacon(s,void 0,c),l=function(){t&&t()};if(u)try{var g=new Blob([JSON.stringify(e)],{type:o||"application/json"});navigator.sendBeacon(r,g)?(a&&this.callbacks.printLog("批量发送成功: "+e.length+" 条数据"),l()):(this.callbacks.printLog("批量发送失败: sendBeacon 返回 false,数据已重新加入队列"),this.retryBatchData(e),l())}catch(t){this.callbacks.printLog("批量发送失败: "+t+",数据已重新加入队列"),this.retryBatchData(e),l()}else this.callbacks.ajax({url:r,type:"POST",data:JSON.stringify(e),contentType:o,credentials:!1,timeout:this.config.sendTimeout,cors:!0,success:function(){n.config.showLog&&n.callbacks.printLog("批量发送成功: "+e.length+" 条数据"),l()},error:function(t){n.callbacks.printLog("批量发送失败: "+t+",数据已重新加入队列"),n.retryBatchData(e),l()}})},e.prototype.retryBatchData=function(e){var t=this,n=this.getQueueFromStorage(),r=function(e){return e.event+"_"+e.itemKey+"_"+e.requestTime},o=new Set(n.map(r)),a=this.callbacks.getTimeStamp(),s=e.filter((function(e){var n=r(e);if(o.has(n))return!1;var i=(e._retryCount||0)+1;return i>3?(t.config.showLog&&t.callbacks.printLog("数据已达到最大重试次数,放弃重试: "+n),!1):(e._retryCount=i,e._nextRetryTime=a+1e3*Math.pow(2,i),o.add(n),!0)})),c=i(i([],s),n),u=2*this.config.batchMaxSize,l=c.length>u?c.slice(0,u):c;this.saveQueueToStorage(l),this.config.showLog&&this.callbacks.printLog("已将 "+s.length+" 条数据加入重试队列")},e}(),c=function(){function e(e){this.deviceId="",this.callbacks=e}return e.prototype.getDeviceId=function(){if(this.deviceId)return this.deviceId;var e=this.callbacks.getCookie("device_id")||this.callbacks.getLocalStorage("device_id");if(e)return this.deviceId=e,this.deviceId;var t=this.callbacks.collectFingerprint(),n=this.callbacks.hashFingerprint(t);return this.callbacks.setCookie("device_id",n,730),this.callbacks.setLocalStorage("device_id",n),this.deviceId=n,this.deviceId},e.prototype.resetDeviceId=function(){return document.cookie="device_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",localStorage.removeItem("device_id"),this.deviceId="",this.getDeviceId()},e}(),u=function(){function e(e,t){this.isFlushingPendingData=!1,this.isUnloadListenerSetup=!1,this.config=e,this.callbacks=t}return e.prototype.updateConfig=function(e){this.config=n(n({},this.config),e)},e.prototype.addToQueue=function(e){var t=this.getQueueFromStorage();t.push(e);var n=this.config.pendingRequestsMaxSize||50;if(t.length>n){var i=t.slice(-n);this.config.showLog&&this.callbacks.printLog("待发送请求队列已满,已移除最旧的数据(最大限制: "+n+")"),this.saveQueueToStorage(i)}else this.saveQueueToStorage(t)},e.prototype.restoreQueue=function(){var e=this.getQueueFromStorage();e.length>0&&this.config.showLog&&this.callbacks.printLog("从 LocalStorage 恢复 "+e.length+" 条待发送请求")},e.prototype.flushQueue=function(){var e=this,t=this.getQueueFromStorage();if(0!==t.length){this.saveQueueToStorage([]);var n=this.config,i=n.serverUrl,r=n.sendTimeout,o=n.contentType,a=n.showLog,s=n.header;t.forEach((function(t){e.callbacks.shouldSample()?(a&&e.callbacks.printLog(JSON.stringify(t)),e.callbacks.ajax({url:i,type:"POST",data:JSON.stringify(t),contentType:o,header:s,credentials:!1,timeout:r,cors:!0,success:function(){a&&e.callbacks.printLog("待发送请求发送成功")},error:function(t){a&&e.callbacks.printLog("待发送请求发送失败(不再重试): "+t)}})):a&&e.callbacks.printLog("待发送请求已采样跳过")}))}},e.prototype.flushQueueWithBeacon=function(){var e=this;if(!this.isFlushingPendingData){this.isFlushingPendingData=!0;var t=this.getQueueFromStorage();if(0!==t.length){var n=this.config,i=n.serverUrl,r=n.contentType,o=n.showLog,a=0,s=0;t.forEach((function(t){e.sendWithBeacon(t,i,r)?a++:s++})),o&&this.callbacks.printLog("页面卸载时发送待请求数据: 成功 "+a+" 条,失败 "+s+" 条"),this.isFlushingPendingData=!1}else this.isFlushingPendingData=!1}},e.prototype.setupUnloadListener=function(){var e=this;this.isUnloadListenerSetup||(this.isUnloadListenerSetup=!0,document.addEventListener("visibilitychange",(function(){e.isPageUnloading()&&e.flushQueueWithBeacon()})),window.addEventListener("beforeunload",(function(){e.flushQueueWithBeacon()})),window.addEventListener("pagehide",(function(){e.flushQueueWithBeacon()})))},e.prototype.getQueueFromStorage=function(){try{var e=this.callbacks.getLocalStorage("web_tracking_pending_requests");if(e){var t=JSON.parse(e);if(Array.isArray(t))return t}}catch(e){this.callbacks.printLog("读取待发送请求失败: "+e),this.callbacks.setLocalStorage("web_tracking_pending_requests","[]")}return[]},e.prototype.saveQueueToStorage=function(e){try{this.callbacks.setLocalStorage("web_tracking_pending_requests",JSON.stringify(e))}catch(e){this.callbacks.printLog("保存待发送请求到 LocalStorage 失败: "+e)}},e.prototype.isPageUnloading=function(){return"hidden"===document.visibilityState},e.prototype.sendWithBeacon=function(e,t,n){try{var i=new Blob([JSON.stringify(e)],{type:n||"application/json"});return navigator.sendBeacon(t,i)}catch(e){return this.config.showLog&&this.callbacks.printLog("sendBeacon 发送失败: "+e),!1}},e}(),l=new(function(i){function r(){var t=i.call(this)||this;return t.useCustomPageKey=!1,t.userInfo=null,t.currentUrl="",t.pageKey="",t.deviceId="",t.eventDescMap={PageView:"Web 浏览页面",WebClick:"Web 元素点击",PageRetained:"Web 页面浏览时长",CustomTrack:"Web 自定义代码上报",WebExposure:"Web 元素曝光"},t.init=function(e){t.preset(e);var n=window.location.pathname;t.currentUrl=window.location.href,e.pageKey?(t.pageKey=e.pageKey,t.useCustomPageKey=!0):(t.pageKey=n.replace(/\//g,"_").substring(1),t.useCustomPageKey=!1),t.systemsInfo=t.getSystemsInfo(e.platform),t.deviceId=t.deviceManager.getDeviceId(),e.userInfo&&t.isObject(e.userInfo)&&(t.userInfo=e.userInfo),t.setCookie("retainedStartTime",t.getTimeStamp()),t.initConfig.batchSend&&t.batchSender.restoreQueue(),t.pendingRequestsManager.restoreQueue(),t.pendingRequestsManager.setupUnloadListener();var i=t.getAutoTrackConfig();t.currentAutoTrackConfig=i,i.retained&&t.pageDurationTracker.start(),i.exposure&&t.exposureTracker.init()},t.preset=function(i){if(i instanceof Object){if(void 0!==i.pageKey)if(null===i.pageKey||""===i.pageKey){t.useCustomPageKey=!1;var r=window.location.pathname;t.pageKey=r.replace(/\//g,"_").substring(1)}else t.pageKey=i.pageKey,t.useCustomPageKey=!0;t.each(i,(function(i,r){if("pageKey"!==r){if("autoTrack"===r&&"object"===e(i)&&null!==i){var o=i;return t.initConfig.autoTrack=n(n({},t.currentAutoTrackConfig),o),void(t.currentAutoTrackConfig=t.getAutoTrackConfig())}if(t.initConfig.hasOwnProperty(r)){var a=t.validateConfigParam(String(r),i);a.valid?t.initConfig[r]=i:console.warn("配置参数验证失败: "+String(r)+" = "+i+", 原因: "+a.message)}}}))}/^(((ht|f)tps?):\/\/)?[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:/~+#\(\)]*[\w\-\.,@?^=%&/~+#\(\)])?$/.test(t.initConfig.serverUrl)||console.warn("当前 server_url 为空或不正确,只在控制台打印日志,network 中不会发数据,请配置正确的 server_url!"),t.initConfig.autoTrack||t.initConfig.trackPartKeyClick?t.listener():t.unlistener(),t.batchSender.updateConfig({batchSend:t.initConfig.batchSend,batchInterval:t.initConfig.batchInterval,batchMaxSize:t.initConfig.batchMaxSize,sendTimeout:t.initConfig.sendTimeout,serverUrl:t.initConfig.serverUrl,contentType:t.initConfig.contentType,showLog:t.initConfig.showLog,sendMethod:t.initConfig.sendMethod,header:t.initConfig.header}),t.pendingRequestsManager.updateConfig({pendingRequestsMaxSize:t.initConfig.pendingRequestsMaxSize,sendTimeout:t.initConfig.sendTimeout,serverUrl:t.initConfig.serverUrl,contentType:t.initConfig.contentType,showLog:t.initConfig.showLog,header:t.initConfig.header});var o=t.getAutoTrackConfig();o.retained?(t.pageDurationTracker.updateConfig({pageDurationInterval:t.initConfig.pageDurationInterval,showLog:t.initConfig.showLog}),t.pageDurationTracker.start()):t.pageDurationTracker.stop(),o.exposure?(t.exposureTracker.updateConfig({autoTrackExposure:!0,exposureThreshold:t.initConfig.exposureThreshold,exposureTime:t.initConfig.exposureTime,exposureNum:t.initConfig.exposureNum,showLog:t.initConfig.showLog}),t.exposureTracker.init()):t.exposureTracker.stop()},t.validateConfigParam=function(t,n){switch(t){case"sampleRate":if("number"!=typeof n||n<0||n>1)return{valid:!1,message:"sampleRate 必须是 0-1 之间的数字"};break;case"sendTimeout":if("number"!=typeof n||n<=0)return{valid:!1,message:"sendTimeout 必须是大于 0 的数字"};break;case"batchInterval":if("number"!=typeof n||n<=0)return{valid:!1,message:"batchInterval 必须是大于 0 的数字"};break;case"batchMaxSize":if("number"!=typeof n||n<=0||!Number.isInteger(n))return{valid:!1,message:"batchMaxSize 必须是大于 0 的整数"};break;case"pendingRequestsMaxSize":if("number"!=typeof n||n<=0||!Number.isInteger(n))return{valid:!1,message:"pendingRequestsMaxSize 必须是大于 0 的整数"};break;case"pageDurationInterval":if("number"!=typeof n||n<=0)return{valid:!1,message:"pageDurationInterval 必须是大于 0 的数字"};break;case"sendMethod":if("string"!=typeof n||!["auto","xhr","beacon"].includes(n))return{valid:!1,message:"sendMethod 必须是 auto、xhr 或 beacon"};break;case"exposureThreshold":if("number"!=typeof n||n<0||n>1)return{valid:!1,message:"exposureThreshold 必须是 0-1 之间的数字"};break;case"exposureTime":if("number"!=typeof n||n<=0)return{valid:!1,message:"exposureTime 必须是大于 0 的数字"};break;case"exposureNum":if(void 0!==n&&("number"!=typeof n||n<=0||!Number.isInteger(n)))return{valid:!1,message:"exposureNum 必须是大于 0 的整数或不限制"};break;case"showLog":case"isTrackSinglePage":case"batchSend":if("boolean"!=typeof n)return{valid:!1,message:t+" 必须是布尔值"};break;case"autoTrack":if("boolean"!=typeof n&&"object"!==e(n))return{valid:!1,message:"autoTrack 必须是布尔值或对象"};if("object"===e(n)&&null!==n){var i=n,r=["view","click","exposure","retained"];for(var o in i){if(!r.includes(o))return{valid:!1,message:"autoTrack 对象中包含无效的属性: "+o};if("boolean"!=typeof i[o])return{valid:!1,message:"autoTrack."+o+" 必须是布尔值"}}}break;case"business":case"header":if(null!==n&&"object"!==e(n))return{valid:!1,message:t+" 必须是对象或 null"};break;case"contentType":if("application/json"!==n&&"application/x-www-form-urlencoded"!==n)return{valid:!1,message:"contentType 必须是 application/json 或 application/x-www-form-urlencoded"};break;case"platform":if("string"!=typeof n)return{valid:!1,message:"platform 必须是字符串"}}return{valid:!0}},t.getAutoTrackConfig=function(){var n,i,r,o,a=t.initConfig.autoTrack;return"boolean"==typeof a?{view:a,click:a,exposure:a,retained:a}:"object"===e(a)&&null!==a?{view:null!==(n=a.view)&&void 0!==n&&n,click:null!==(i=a.click)&&void 0!==i&&i,exposure:null!==(r=a.exposure)&&void 0!==r&&r,retained:null!==(o=a.retained)&&void 0!==o&&o}:{view:!1,click:!1,exposure:!1,retained:!1}},t.login=function(e){t.isObject(e)&&(t.userInfo=e)},t.getDeviceId=function(){return t.deviceManager.getDeviceId()},t.resetDeviceId=function(){return t.deviceManager.resetDeviceId()},t.track=function(e){var n=e.event,i=e.desc,r=e.pageKey,o=e.partKey,a=e.business,s=e.header,c=t.getParams({desc:i,event:n||"CustomTrack",itemKey:t.getItemKey(o,r),privateParamMap:{business:a}});return t.sendData(c,s)},t.listener=function(){t.unlistener();var e=t.getAutoTrackConfig();e.view&&(t.initConfig.isTrackSinglePage&&(t.rewriteHistory(),t.addSinglePageEvent(t.onPageViewCallback)),t.each(["load","beforeunload"],(function(e){t.addEventListener(window,e,t.onPageViewCallback)}))),e.click&&t.addEventListener(window,"click",t.onClickCallback)},t.unlistener=function(){if(t.initConfig.isTrackSinglePage){var e=window.history.pushState?"popstate":"hashchange";t.each(["pushState","replaceState",e],(function(e){t.removeEventListener(window,e,t.onPageViewCallback)}))}t.each(["load","beforeunload"],(function(e){t.removeEventListener(window,e,t.onPageViewCallback)})),t.removeEventListener(window,"click",t.onClickCallback),t.batchSender.clearTimer(),t.pageDurationTracker.stop()},t.clearBatchTimer=function(){t.batchSender.clearTimer()},t.clearBatchQueue=function(){t.batchSender.clearQueue()},t.setPageKey=function(e,n){if(void 0===n&&(n=!1),null===e||""===e){t.useCustomPageKey=!1;var i=window.location.pathname;t.pageKey=i.replace(/\//g,"_").substring(1),t.initConfig.showLog&&t.printLog("页面标识已恢复自动生成: "+t.pageKey)}else t.pageKey=e,t.useCustomPageKey=!n,t.initConfig.showLog&&t.printLog("页面标识已设置为: "+e+", 自动更新: "+n)},t.getPageKey=function(){return t.pageKey},t.onClickCallback=function(e){var n,i=e.target;if(null===(n=null==i?void 0:i.dataset)||void 0===n?void 0:n.partKey){var r=[e.pageX,e.pageY],o=i.id,a=i.className,s=t.extractDataAttributes(i),c=i.getAttribute("data-desc")||t.eventDescMap.WebClick,u=i.getAttribute("data-part-key"),l=i.getAttribute("data-page-key")||void 0,g=t.getParams({event:"WebClick",desc:c,itemKey:t.getItemKey(u,l),privateParamMap:{business:s,targetEle:{nodeName:i.nodeName,id:o,className:a,position:r}}});t.sendData(g)}},t.onPageViewCallback=function(e){var n,i,r=window.location.origin,o=t.getParams({event:"PageView",desc:t.eventDescMap.PageView,privateParamMap:{currentUrl:t.currentUrl,targetUrl:(null===(n=e.arguments)||void 0===n?void 0:n[2])?r+(null===(i=e.arguments)||void 0===i?void 0:i[2]):null}});t.currentUrl=window.location.href,t.useCustomPageKey||(t.pageKey=window.location.pathname.replace(/\//g,"_").substring(1)),t.getAutoTrackConfig().retained&&(t.pageDurationTracker.stop(),t.pageDurationTracker.start()),t.sendData(o)},t.getParams=function(e){var n=e.event,i=e.desc,r=e.privateParamMap,o=void 0===r?{}:r,a=e.itemKey,s=t.initConfig.business,c=window.innerWidth,u=window.innerHeight,l=window.screen.width,g=window.screen.height,p=t.filterSensitiveData(s||{}),d=t.filterSensitiveData(t.userInfo||{}),h=t.filterSensitiveData(o||{}),f=t.filterSensitiveData(t.getQueryValue()||{}),v={currentUrl:h.currentUrl||t.currentUrl,business:Object.assign({},p,h.business||{}),pageWidth:c,pageHeight:u,screenWidth:l,screenHeight:g,sdkVersion:t.sdkVersion,systemsInfo:t.systemsInfo,urlParams:f,userInfo:d,deviceId:t.deviceId};return h.targetEle&&(v.targetEle=h.targetEle),h.targetUrl&&(v.targetUrl=h.targetUrl),h.pointerType&&(v.pointerType=h.pointerType),h.elementSelector&&(v.elementSelector=h.elementSelector),h.retainedDuration&&(v.retainedDuration=h.retainedDuration),void 0!==h.exposureScreenNo&&(v.exposureScreenNo=h.exposureScreenNo),{event:n,desc:i,itemKey:a||t.getItemKey(),requestTime:t.getTimeStamp(),privateParamMap:v}},t.shouldSample=function(){var e=t.initConfig.sampleRate;return e>=1||!(e<=0)&&Math.random()<e},t.shouldUseBeacon=function(e,t,n){return"beacon"===e||"xhr"!==e&&(!t&&!n&&"function"==typeof navigator.sendBeacon)},t.sendData=function(e,n){return new Promise((function(i,r){if(!t.shouldSample())return t.initConfig.showLog&&t.printLog("数据已采样跳过"),void i({success:!1,message:"数据已采样跳过"});if(t.initConfig.showLog&&t.printLog(e),t.initConfig.batchSend)return t.batchSender.addToQueue(e),void i({success:!0,message:"数据已加入批量队列"});var o=t.initConfig,a=o.serverUrl,s=o.sendTimeout,c=o.contentType,u=o.showLog,l=o.header;t.shouldUseBeacon(t.initConfig.sendMethod,n,l)?t.sendWithBeacon(e,a,c)?i({success:!0,message:"数据发送成功"}):(t.pendingRequestsManager.addToQueue(e),i({success:!1,message:"sendBeacon 发送失败,数据已加入待发送队列"})):t.ajax({url:a,type:"POST",data:JSON.stringify(e),contentType:c,header:n||l,credentials:!1,timeout:s,cors:!0,success:function(e){u&&t.printLog("数据发送成功",e),i({success:!0,data:e})},error:function(n){u&&t.printLog("数据发送失败",n),t.pendingRequestsManager.addToQueue(e),r({success:!1,message:"数据发送失败",error:n})}})}))},t.sendWithBeacon=function(e,n,i){try{var r=new Blob([JSON.stringify(e)],{type:i||"application/json"});return navigator.sendBeacon(n,r)}catch(e){return t.initConfig.showLog&&t.printLog("sendBeacon 发送失败: "+e),!1}},t.trackPageDuration=function(e,n,i){void 0===i&&(i=!0);var r=t.pageDurationTracker.calculateDuration(e),o=(null==n?void 0:n.desc)||t.eventDescMap.PageRetained,a=(null==n?void 0:n.pageKey)||t.pageKey,s=(null==n?void 0:n.business)||{},c=null==n?void 0:n.header,u=t.getParams({event:"PageRetained",desc:o,itemKey:t.getItemKey(void 0,a),privateParamMap:{business:s,retainedDuration:r}}),l=t.sendData(u,c);return i&&t.setCookie("retainedStartTime",t.getTimeStamp()),l},t.getItemKey=function(e,n){var i=void 0!==n?n:t.pageKey,r=void 0!==e?e:"";return r?t.initConfig.appKey+"."+i+"."+r:t.initConfig.appKey+"."+i},t.extractDataAttributes=function(e){for(var t={},n=0;n<e.attributes.length;n++){var i=e.attributes[n].name;if(i.startsWith("data-")&&"data-exposure"!==i&&"data-part-key"!==i&&"data-desc"!==i&&"data-page-key"!==i)t[i.replace("data-","").replace(/-([a-z])/g,(function(e,t){return t.toUpperCase()}))]=e.getAttribute(i)}return t},t.handleExposureReport=function(e,n){var i=t.exposureTracker.getElementInfo(e);if(!i)return Promise.resolve();var r=t.initConfig.exposureNum;if(void 0!==r&&i.exposureCount>=r)return t.initConfig.showLog&&t.printLog("元素已达到最大曝光次数限制: "+r),Promise.resolve();var o=t.extractDataAttributes(e),a=e.getAttribute("data-desc")||t.eventDescMap.WebExposure,s=e.getAttribute("data-part-key")||"exposure",c=e.getAttribute("data-page-key")||void 0,u=t.getParams({event:"WebExposure",desc:a,itemKey:t.getItemKey(s,c),privateParamMap:{business:o,exposureScreenNo:n}});return t.sendData(u).then((function(){t.exposureTracker.incrementExposureCount(e),t.exposureTracker.clearExposureTimer(e),t.initConfig.showLog&&t.printLog("曝光上报成功,当前曝光次数: "+(i.exposureCount+1))})).catch((function(e){t.initConfig.showLog&&t.printLog("曝光上报失败: "+e)}))},t.sdkVersion="1.2.8",t.initConfig={appKey:"",platform:void 0,showLog:!1,serverUrl:"",autoTrack:!1,sendTimeout:3e3,isTrackSinglePage:!1,contentType:"application/json",business:{},header:void 0,sampleRate:1,batchSend:!1,batchInterval:5e3,batchMaxSize:10,pendingRequestsMaxSize:50,pageDurationInterval:3e4,sendMethod:"auto",exposureThreshold:.5,exposureTime:500,exposureNum:void 0},t.systemsInfo={},t.deviceManager=new c({getCookie:t.getCookie.bind(t),setCookie:t.setCookie.bind(t),getLocalStorage:t.getLocalStorage.bind(t),setLocalStorage:t.setLocalStorage.bind(t),collectFingerprint:t.collectFingerprint.bind(t),hashFingerprint:t.hashFingerprint.bind(t)}),t.batchSender=new s({batchSend:!1,batchInterval:5e3,batchMaxSize:10,sendTimeout:3e3,serverUrl:"",contentType:"application/json",showLog:!1,sendMethod:"auto",header:void 0},{getLocalStorage:t.getLocalStorage.bind(t),setLocalStorage:t.setLocalStorage.bind(t),getTimeStamp:t.getTimeStamp.bind(t),ajax:t.ajax.bind(t),shouldSample:t.shouldSample.bind(t),shouldUseBeacon:t.shouldUseBeacon.bind(t),printLog:t.printLog.bind(t)}),t.pendingRequestsManager=new u({pendingRequestsMaxSize:50,sendTimeout:3e3,serverUrl:"",contentType:"application/json",showLog:!1,header:void 0},{getLocalStorage:t.getLocalStorage.bind(t),setLocalStorage:t.setLocalStorage.bind(t),shouldSample:t.shouldSample.bind(t),ajax:t.ajax.bind(t),printLog:t.printLog.bind(t)}),t.pageDurationTracker=new a({pageDurationInterval:3e4,showLog:!1},{getCookie:t.getCookie.bind(t),setCookie:t.setCookie.bind(t),getTimeStamp:t.getTimeStamp.bind(t),track:t.trackPageDuration.bind(t),printLog:t.printLog.bind(t)}),t.exposureTracker=new o({autoTrackExposure:!1,exposureThreshold:.5,exposureTime:500,exposureNum:void 0,showLog:!1},{reportExposure:t.handleExposureReport.bind(t),printLog:t.printLog.bind(t),getTimeStamp:t.getTimeStamp.bind(t),extractDataAttributes:t.extractDataAttributes.bind(t)}),t}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function i(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}(r,i),r.prototype.printLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.initConfig.showLog&&i.prototype.printLog.apply(this,e)},r.prototype.addSinglePageEvent=function(e){var t=this,n=window.history.pushState?"popstate":"hashchange";this.each(["pushState","replaceState",n],(function(n){t.addEventListener(window,n,e)}))},r}(r));export default l;
|
package/lib/index.js
CHANGED
|
@@ -450,7 +450,7 @@
|
|
|
450
450
|
|
|
451
451
|
this.filterSensitiveData = function (obj, sensitiveKeys) {
|
|
452
452
|
if (sensitiveKeys === void 0) {
|
|
453
|
-
sensitiveKeys = ["password", "token", "secret"
|
|
453
|
+
sensitiveKeys = ["password", "token", "secret"];
|
|
454
454
|
}
|
|
455
455
|
|
|
456
456
|
if (!_this.isObject(obj)) return obj;
|
|
@@ -1665,9 +1665,7 @@
|
|
|
1665
1665
|
this.callbacks.ajax({
|
|
1666
1666
|
url: serverUrl,
|
|
1667
1667
|
type: "POST",
|
|
1668
|
-
data: JSON.stringify(
|
|
1669
|
-
events: data
|
|
1670
|
-
}),
|
|
1668
|
+
data: JSON.stringify(data),
|
|
1671
1669
|
contentType: contentType,
|
|
1672
1670
|
credentials: false,
|
|
1673
1671
|
timeout: this.config.sendTimeout,
|
|
@@ -2366,7 +2364,8 @@
|
|
|
2366
2364
|
};
|
|
2367
2365
|
|
|
2368
2366
|
_this.track = function (_a) {
|
|
2369
|
-
var
|
|
2367
|
+
var event = _a.event,
|
|
2368
|
+
desc = _a.desc,
|
|
2370
2369
|
pageKey = _a.pageKey,
|
|
2371
2370
|
partKey = _a.partKey,
|
|
2372
2371
|
business = _a.business,
|
|
@@ -2374,7 +2373,7 @@
|
|
|
2374
2373
|
|
|
2375
2374
|
var params = _this.getParams({
|
|
2376
2375
|
desc: desc,
|
|
2377
|
-
event: "CustomTrack",
|
|
2376
|
+
event: event || "CustomTrack",
|
|
2378
2377
|
itemKey: _this.getItemKey(partKey, pageKey),
|
|
2379
2378
|
privateParamMap: {
|
|
2380
2379
|
business: business
|
package/lib/index.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).WebTracking=t()}(this,(function(){"use strict";function e(t){return(e="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})(t)}var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,n)};var n=function(){return(n=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)};function i(e,t){for(var n=0,i=t.length,r=e.length;n<i;n++,r++)e[r]=t[n];return e}var r=function(){function t(){var t=this;this.getSystemsInfo=function(e){var t=navigator.userAgent,n="other",i=[],r={language:navigator.language},o=t.match(/MicroMessenger\/([\d\.]+)/i),a=o&&o[1]?o[1]:null,s=t.match(/(ipod).*\s([\d_]+)/i),c=t.match(/(ipad).*\s([\d_]+)/i),u=t.match(/(iphone)\sos\s([\d_]+)/i),l=t.match(/(android)\s([\d\.]+)/i),g=t.match(/(Windows NT)\s([\d\.]+)/i),p=t.match(/(Mac OS X)\s([\d_]+)/i);i=[],l?(i.push("Android "+l[2]),n="h5"):u?(i.push("iPhone, iOS "+u[2].replace(/_/g,".")),n="h5"):c?(i.push("iPad, iOS "+c[2].replace(/_/g,".")),n="ipad"):s?(i.push("iPod, iOS "+s[2].replace(/_/g,".")),n="h5"):g?(i.push("Windows "+g[2].replace(/_/g,".")),n="pc"):p&&(i.push("Mac, MacOS "+p[2].replace(/_/g,".")),n="pc"),a&&i.push("WeChat "+a),r.client=i.length?i.join(", "):"Unknown",r.platform=e||n;var d=t.toLowerCase().match(/ nettype\/([^ ]+)/g);return d&&d[0]&&(i=[(d=d[0].split("/"))[1]],r.network=i.length?i.join(", "):"Unknown"),r.ua=t,r},this.addEventListener=function(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent&&e.attachEvent("on"+t,(function(t){return n.call(e,t)}),!1)},this.removeEventListener=function(e,t,n){e.removeEventListener?e.removeEventListener(t,n):e.detachEvent&&e.detachEvent("on"+t,(function(t){return n.call(e,t)}),!0)},this.rewriteHistory=function(){var e=window.history,t=function(e){var t=window.history,n=t[e],i=new Event(e);return function(){var e=n.apply(t,arguments);return i.arguments=arguments,window.dispatchEvent(i),e}};window.history.pushState&&(e.pushState=t("pushState"),e.replaceState=t("replaceState"))},this.isArray=Array.isArray||function(e){return"[object Array]"===toString.call(e)},this.formatJsonString=function(e){try{return JSON.stringify(e,null," ")}catch(t){return JSON.stringify(e)}},this.nativeForEach=Array.prototype.forEach,this.slice=Array.prototype.slice,this.hasOwnProperty=Object.prototype.hasOwnProperty,this.breaker={},this.each=function(e,n,i){if(null==e)return!1;if(t.nativeForEach&&e.forEach===t.nativeForEach)e.forEach(n,i);else if(t.isArray(e)&&e.length===+e.length){for(var r=0,o=e.length;r<o;r++)if(r in e&&n.call(i,e[r],r,e)===t.breaker)return!1}else for(var a in e)if(t.hasOwnProperty.call(e,a)&&n.call(i,e[a],a,e)===t.breaker)return!1;return!0},this.getDomIndex=function(e){if(!e.parentNode)return-1;for(var t=0,n=e.tagName,i=e.parentNode.children,r=0;r<i.length;r++)if(i[r].tagName===n){if(e===i[r])return t;t++}return-1},this.selector=function(e){var n=e.parentNode&&9==e.parentNode.nodeType?-1:t.getDomIndex(e);return e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?"#"+e.getAttribute("id"):e.tagName.toLowerCase()+(~n?":nth-of-type("+(n+1)+")":"")},this.getDomSelector=function(e,n){if(!e||!e.parentNode||!e.parentNode.children)return!1;n=n&&n.join?n:[];var i=e.nodeName.toLowerCase();return e&&"body"!==i&&1==e.nodeType?(n.unshift(t.selector(e)),e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?n.join(" > "):t.getDomSelector(e.parentNode,n)):(n.unshift("body"),n.join(" > "))},this.getCookie=function(e){for(var t=e+"=",n=document.cookie.split(";"),i=0;i<n.length;i++){for(var r=n[i];" "==r.charAt(0);)r=r.substring(1,r.length);if(0==r.indexOf(t))return this._decodeURIComponent(r.substring(t.length,r.length))}return null},this.setCookie=function(e,t,n){var i,r="";n=null==n?73e3:n;var o=this.getMainHost();if(i=o?"; domain="+o:"",0!==n){var a=new Date;"s"===String(n).slice(-1)?a.setTime(a.getTime()+1e3*Number(String(n).slice(0,-1))):a.setTime(a.getTime()+24*n*60*60*1e3),r="; expires="+a.toUTCString()}function s(e){return e||!1}var c="",u="",l="";e&&(c=s(e)),t&&(u=s(t)),i&&(l=s(i)),c&&u&&(document.cookie=c+"="+encodeURIComponent(u)+r+"; path=/"+l)},this.getLocalStorage=function(e){try{return localStorage.getItem(e)}catch(e){return null}},this.setLocalStorage=function(e,t){try{localStorage.setItem(e,t)}catch(e){}},this.removeCookie=function(e){t.setCookie(e,"",-1)},this.getTimeStamp=function(){return(new Date).getTime()},this.uuid=function(){return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},this.getDistinctId=function(){var e=t.getCookie("distinctId");return e||(e=t.uuid(),t.setCookie("distinctId",e),e)},this.filterSensitiveData=function(e,n){if(void 0===n&&(n=["password","token","secret","key"]),!t.isObject(e))return e;var i={};return t.each(e,(function(e,r){n.some((function(e){return"string"==typeof r&&r.toLowerCase().includes(e.toLowerCase())}))?i[r]="***":t.isObject(e)?i[r]=t.filterSensitiveData(e,n):i[r]=e})),i},this.xssFilter=function(e){return e?"string"!=typeof e?e.toString():e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/"):""},this.getQueryValue=function(){for(var e=decodeURI(window.location.href).match(new RegExp("[?&][^?&]+=[^?&]+","g"))||[],t={},n=0;n<e.length;n++){var i=e[n].replace(/\?|\&/,"").split("=");t[i[0]]=i[1]}return Object.keys(t).length>0?t:null},this.ajax=function(n){function i(t){if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)}catch(e){return{}}return"object"===e(t)?t:{}}n.timeout=n.timeout||3e4,n.credentials=void 0===n.credentials||n.credentials;var r=t.xhr(n.cors);if(!r)return!1;n.type||(n.type=n.data?"POST":"GET");var o,a=n.success,s=n.error;n.success=function(e){a&&a(e),o&&(clearTimeout(o),o=null)},n.error=function(e,t){s&&s(e,t),o&&(clearTimeout(o),o=null)},o=window.setTimeout((function(){!function(){try{t.isObject(r)&&r.abort&&r.abort()}catch(e){t.printLog(e)}o&&(clearTimeout(o),o=null,n.error&&n.error(),r.onreadystatechange=null,r.onload=null,r.onerror=null)}()}),n.timeout),r.onreadystatechange=function(){try{4==r.readyState&&(r.status>=200&&r.status<300||304==r.status?n.success&&n.success(i(r.responseText)):n.error&&n.error(i(r.responseText),r.status),r.onreadystatechange=null,r.onload=null)}catch(e){r.onreadystatechange=null,r.onload=null}},r.open(n.type||"GET",n.url,!0);try{if(n.credentials&&(r.withCredentials=!0),t.isObject(n.header)&&t.each(n.header,(function(e,t){r.setRequestHeader&&r.setRequestHeader(t,e)})),n.data)n.cors||r.setRequestHeader&&r.setRequestHeader("X-Requested-With","XMLHttpRequest"),t.isObject(n.header)&&Object.keys(n.header).some((function(e){return"content-type"===e.toLowerCase()||"content-type"===e.toLowerCase()}))||("application/json"===n.contentType?r.setRequestHeader&&r.setRequestHeader("Content-type","application/json; charset=UTF-8"):r.setRequestHeader&&r.setRequestHeader("Content-type","application/x-www-form-urlencoded"))}catch(e){t.printLog(e)}r.send(n.data||null)},this.xhr=function(e){return e?void 0!==window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?new XMLHttpRequest:null:void 0!==window.XMLHttpRequest?new XMLHttpRequest:null},this.getUA=function(){var e,t={},n=navigator.userAgent.toLowerCase();return(e=n.match(/opera.([\d.]+)/))?t.opera=Number(e[1].split(".")[0]):(e=n.match(/msie ([\d.]+)/))?t.ie=Number(e[1].split(".")[0]):(e=n.match(/edge.([\d.]+)/))?t.edge=Number(e[1].split(".")[0]):(e=n.match(/firefox\/([\d.]+)/))?t.firefox=Number(e[1].split(".")[0]):(e=n.match(/chrome\/([\d.]+)/))?t.chrome=Number(e[1].split(".")[0]):(e=n.match(/version\/([\d.]+).*safari/))?t.safari=Number(e[1].match(/^\d*.\d*/)):(e=n.match(/trident\/([\d.]+)/))&&(t.ie=11),t},this.isSupportBeaconSend=function(){var n=!1;if("object"!==("undefined"==typeof navigator?"undefined":e(navigator))||"function"!=typeof navigator.sendBeacon)return n;var i=t.getUA(),r=navigator.userAgent.toLowerCase();if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){var o=(r.match(/os [\d._]*/gi)+"").replace(/[^0-9|_.]/gi,"").replace(/_/gi,".").split(".");void 0===i.safari&&(i.safari=Number(o[0])),o[0]&&+o[0]<13?(i.chrome>41||i.firefox>30||i.opera>25||i.safari>12)&&(n=!0):(i.chrome>41||i.firefox>30||i.opera>25||i.safari>11.3)&&(n=!0)}else(i.chrome>38||i.edge>13||i.firefox>30||i.opera>25||i.safari>11)&&(n=!0);return n},this.throttle=function(e,t){var n=null,i=0;return function(){for(var r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var a=Date.now(),s=t-(a-i);s<=0||s>t?(n&&(clearTimeout(n),n=null),i=a,e.apply(void 0,r)):n||(n=window.setTimeout((function(){i=Date.now(),n=null,e.apply(void 0,r)}),s))}},this.debounce=function(e,t){var n=null;return function(){for(var i=[],r=0;r<arguments.length;r++)i[r]=arguments[r];n&&clearTimeout(n),n=window.setTimeout((function(){e.apply(void 0,i)}),t)}},this.sendBeacon=function(e){if(!0===t.isSupportBeaconSend()){var n={type:e.contentType},i=new Blob([JSON.stringify(e.data)],n);return navigator.sendBeacon(e.url,i)?Promise.resolve({success:!0,message:"发送成功"}):Promise.reject({success:!1,message:"sendBeacon返回false"})}return Promise.reject({success:!1,message:"不支持sendBeacon,发送失败!"})},this.getDeviceId=function(){var e=t.getCookie("device_id")||t.getLocalStorage("device_id");if(e)return e;var n=t.collectFingerprint(),i=t.hashFingerprint(n);return t.setCookie("device_id",i,730),t.setLocalStorage("device_id",i),i},this.collectFingerprint=function(){var e={};return e.userAgent=navigator.userAgent,e.screenWidth=screen.width,e.screenHeight=screen.height,e.colorDepth=screen.colorDepth,e.pixelDepth=screen.pixelDepth,e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,e.timezoneOffset=(new Date).getTimezoneOffset(),e.language=navigator.language,e.languages=Array.from(navigator.languages),e.platform=navigator.platform,e.webgl=t.getWebGLFingerprint(),e.canvas=t.getCanvasFingerprint(),e.audio=t.getAudioFingerprint(),e.localStorage=t.hasLocalStorage(),e.sessionStorage=t.hasSessionStorage(),e.indexedDB=t.hasIndexedDB(),e.hardwareConcurrency=navigator.hardwareConcurrency,e.deviceMemory=navigator.deviceMemory,e.maxTouchPoints=navigator.maxTouchPoints,e},this.getWebGLFingerprint=function(){try{var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"not-supported";var n=t.getExtension("WEBGL_debug_renderer_info");return(n?t.getParameter(n.UNMASKED_VENDOR_WEBGL):"unknown")+"|"+(n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"unknown")}catch(e){return"error"}},this.getCanvasFingerprint=function(){try{var e=document.createElement("canvas");e.width=200,e.height=50;var t=e.getContext("2d");return t?(t.textBaseline="top",t.font="14px Arial",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("Canvas fingerprint",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("Canvas fingerprint",4,17),e.toDataURL().slice(-50)):"not-supported"}catch(e){return"error"}},this.getAudioFingerprint=function(){try{var e=window.AudioContext||window.webkitAudioContext;if(!e)return"not-supported";var t=new e,n=String(t.sampleRate||0);return t.close(),n}catch(e){return"error"}},this.hasLocalStorage=function(){try{var e="__test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}},this.hasSessionStorage=function(){try{var e="__test__";return sessionStorage.setItem(e,e),sessionStorage.removeItem(e),!0}catch(e){return!1}},this.hasIndexedDB=function(){return"indexedDB"in window&&null!==indexedDB},this.hashFingerprint=function(e){for(var t=JSON.stringify(e,Object.keys(e).sort()),n=5381,i=52711,r=0;r<t.length;r++){var o=t.charCodeAt(r);n=(n<<5)+n+o,i=(i<<5)+i+o}return"fp_"+(n>>>0).toString(16).padStart(8,"0")+(i>>>0).toString(16).padStart(8,"0")}}return t.prototype.printLog=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];if(this.isObject(t[0])&&(t[0]=this.formatJsonString(t[0])),"object"===("undefined"==typeof console?"undefined":e(console))&&console.log)try{return console.log.apply(console,t)}catch(e){console.log(t[0])}},t.prototype.isObject=function(e){return null!=e&&"[object Object]"==toString.call(e)},t.prototype.isUndefined=function(e){return void 0===e},t.prototype.isString=function(e){return"[object String]"==toString.call(e)},t.prototype.isDate=function(e){return"[object Date]"==toString.call(e)},t.prototype.isBoolean=function(e){return"[object Boolean]"==toString.call(e)},t.prototype.isNumber=function(e){return"[object Number]"==toString.call(e)&&/[\d\.]+/.test(String(e))},t.prototype.isElement=function(e){return!(!e||1!==e.nodeType)},t.prototype.isFunction=function(e){if(!e)return!1;var t=toString.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t},t.prototype.isJSONString=function(e){if(!this.isString(e))return!1;try{JSON.parse(e)}catch(e){return!1}return!0},t.prototype._decodeURIComponent=function(e){var t=e;try{t=decodeURIComponent(e)}catch(n){t=e}return t},t.prototype.getMainHost=function(){var e="mh_"+Math.random(),t=new RegExp("(^|;)\\s*"+e+"=12345"),n=new Date(0),i=document.domain,r=i.split("."),o=[];for(o.unshift(r.pop());r.length;){o.unshift(r.pop());var a=o.join("."),s=e+"=12345;domain=."+a;if(document.cookie=s,t.test(document.cookie))return document.cookie=s+";expires="+n,a}return i},t}(),o=function(){function e(e,t){this.observer=null,this.mutationObserver=null,this.elementsMap=new Map,this.config=e,this.callbacks=t}return e.prototype.updateConfig=function(e){this.config=n(n({},this.config),e)},e.prototype.init=function(){var e=this;this.config.autoTrackExposure&&("IntersectionObserver"in window?(this.observer=new IntersectionObserver((function(t){t.forEach((function(t){var n=t.target,i=e.elementsMap.get(n);if(i){var r=e.config.exposureTime||500;t.isIntersecting?(i.isVisible=!0,i.visibleStartTime=e.callbacks.getTimeStamp(),i.exposureTimer&&clearTimeout(i.exposureTimer),i.exposureTimer=window.setTimeout((function(){if(i.isVisible){var t=e.calculateexposureScreenIndex(n);e.callbacks.reportExposure(n,t)}}),r)):(i.isVisible=!1,i.exposureTimer&&(clearTimeout(i.exposureTimer),i.exposureTimer=null))}}))}),{threshold:this.config.exposureThreshold||.5}),this.observeExposureElements(),this.initMutationObserver()):this.config.showLog&&this.callbacks.printLog("当前浏览器不支持 IntersectionObserver,无法启用曝光埋点"))},e.prototype.stop=function(){this.observer&&(this.observer.disconnect(),this.observer=null,this.elementsMap.forEach((function(e){e.exposureTimer&&clearTimeout(e.exposureTimer)})),this.elementsMap.clear()),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.config.showLog&&this.callbacks.printLog("曝光监听已停止")},e.prototype.addExposureElement=function(e){this.elementsMap.has(e)||(this.elementsMap.set(e,{element:e,visibleStartTime:0,exposureCount:0,isVisible:!1,exposureTimer:null}),this.observer&&this.observer.observe(e))},e.prototype.observeExposureElements=function(){var e=this;if(this.observer){var t=document.querySelectorAll('[data-exposure="true"]');t.forEach((function(t){e.addExposureElement(t)})),this.config.showLog&&t.length>0&&this.callbacks.printLog("已监听 "+t.length+" 个曝光元素"),document.body||document.addEventListener("DOMContentLoaded",(function(){var t=document.querySelectorAll('[data-exposure="true"]');t.forEach((function(t){e.addExposureElement(t)})),e.config.showLog&&t.length>0&&e.callbacks.printLog("DOMContentLoaded 后监听 "+t.length+" 个曝光元素")}))}},e.prototype.initMutationObserver=function(){var e=this;"MutationObserver"in window?(this.mutationObserver=new MutationObserver((function(t){t.forEach((function(t){t.addedNodes.forEach((function(t){if(t.nodeType===Node.ELEMENT_NODE){var n=t;if(n.hasAttribute("data-exposure")&&"true"===n.getAttribute("data-exposure"))e.addExposureElement(n);else n.querySelectorAll('[data-exposure="true"]').forEach((function(t){e.addExposureElement(t)}))}}))}))})),document.body?(this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),this.config.showLog&&this.callbacks.printLog("MutationObserver 已启动,监听动态添加的曝光元素")):document.addEventListener("DOMContentLoaded",(function(){e.mutationObserver&&document.body&&(e.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),e.config.showLog&&e.callbacks.printLog("MutationObserver 已启动,监听动态添加的曝光元素"))}))):this.config.showLog&&this.callbacks.printLog("当前浏览器不支持 MutationObserver,无法监听动态添加的曝光元素")},e.prototype.calculateexposureScreenIndex=function(e){var t=e.getBoundingClientRect(),n=window.innerHeight||document.documentElement.clientHeight,i=window.scrollY||document.documentElement.scrollTop,r=t.top+i;return r<=0?1:Math.ceil(r/n)},e.prototype.getElementInfo=function(e){return this.elementsMap.get(e)},e.prototype.incrementExposureCount=function(e){var t=this.elementsMap.get(e);t&&t.exposureCount++},e.prototype.clearExposureTimer=function(e){var t=this.elementsMap.get(e);t&&t.exposureTimer&&(clearTimeout(t.exposureTimer),t.exposureTimer=null)},e}(),a=function(){function e(e,t){this.timer=null,this.config=e,this.callbacks=t}return e.prototype.updateConfig=function(e){var t=this.config.pageDurationInterval;this.config=n(n({},this.config),e),void 0!==e.pageDurationInterval&&e.pageDurationInterval!==t&&null!==this.timer&&(this.stop(),this.start())},e.prototype.start=function(){var e=this;this.stop();var t=this.config.pageDurationInterval||3e4;t<=0?this.config.showLog&&this.callbacks.printLog("定时上报间隔时间无效,已禁用定时上报"):(this.timer=window.setInterval((function(){"visible"===document.visibilityState&&e.callbacks.track(t,{desc:"定时上报页面停留时长"},!0).catch((function(t){e.config.showLog&&e.callbacks.printLog("定时上报页面停留时长失败: "+t)}))}),t),this.config.showLog&&this.callbacks.printLog("定时上报页面停留时长已启动,间隔: "+t+"ms"))},e.prototype.stop=function(){null!==this.timer&&(clearInterval(this.timer),this.timer=null,this.config.showLog&&this.callbacks.printLog("定时上报页面停留时长已停止"))},e.prototype.calculateDuration=function(e){if(null!=e)return Math.max(e,0);var t=this.callbacks.getCookie("retainedStartTime"),n=t?+t:this.callbacks.getTimeStamp(),i=this.callbacks.getTimeStamp();return Math.max(i-n,0)},e}(),s="web_tracking_batch_queue",c=4194304,u=function(){function e(e,t){this.timer=null,this.isFlushingQueue=!1,this.config=e,this.callbacks=t}return e.prototype.start=function(){var e=this;this.config.batchSend&&(this.clearTimer(),this.timer=window.setInterval((function(){e.flushQueue()}),this.config.batchInterval))},e.prototype.updateConfig=function(e){this.config=n(n({},this.config),e),this.clearTimer(),this.start()},e.prototype.addToQueue=function(e){if(this.config.batchSend)if(this.callbacks.shouldSample()){var t=this.getQueueFromStorage();t.push(e),this.saveQueueToStorage(t),t.length>=this.config.batchMaxSize&&this.flushQueue()}else this.config.showLog&&this.callbacks.printLog("数据已采样跳过(批量模式)")},e.prototype.clearTimer=function(){null!==this.timer&&(clearInterval(this.timer),this.timer=null)},e.prototype.clearQueue=function(){this.callbacks.setLocalStorage(s,"[]"),this.config.showLog&&this.callbacks.printLog("批量队列已清空")},e.prototype.restoreQueue=function(){var e=this.getQueueFromStorage();e.length>0&&this.config.showLog&&this.callbacks.printLog("从 LocalStorage 恢复 "+e.length+" 条批量数据")},e.prototype.getQueueFromStorage=function(){try{var e=this.callbacks.getLocalStorage(s);if(e){var t=JSON.parse(e);if(Array.isArray(t))return t}}catch(e){this.callbacks.printLog("读取批量队列失败: "+e),this.callbacks.setLocalStorage(s,"[]")}return[]},e.prototype.saveQueueToStorage=function(e){try{var t=JSON.stringify(e);if(t.length>c){var n=Math.floor(.8*e.length),i=e.slice(-n);this.callbacks.printLog("队列过大,已截断保留最新 "+n+" 条数据(限制: 4MB)"),this.callbacks.setLocalStorage(s,JSON.stringify(i))}else this.callbacks.setLocalStorage(s,t)}catch(e){this.callbacks.printLog("保存批量队列到 LocalStorage 失败: "+e)}},e.prototype.flushQueue=function(){var e=this;if(!this.isFlushingQueue){var t=this.getQueueFromStorage();if(0!==t.length){var n=this.callbacks.getTimeStamp(),i=t.filter((function(e){return!e._nextRetryTime||e._nextRetryTime<=n}));if(0!==i.length){var r=t.filter((function(e){return!!e._nextRetryTime&&e._nextRetryTime>n}));this.saveQueueToStorage(r),this.isFlushingQueue=!0,this.sendBatchData(i,(function(){e.isFlushingQueue=!1}))}else this.config.showLog&&this.callbacks.printLog("批量队列中有 "+t.length+" 条数据等待重试")}}},e.prototype.sendBatchData=function(e,t){var n=this,i=this.config,r=i.serverUrl,o=i.contentType,a=i.showLog,s=i.sendMethod,c=i.header;a&&(this.callbacks.printLog("批量发送 "+e.length+" 条数据"),e.forEach((function(e){return n.callbacks.printLog(JSON.stringify(e))})));var u=this.callbacks.shouldUseBeacon(s,void 0,c),l=function(){t&&t()};if(u)try{var g=new Blob([JSON.stringify(e)],{type:o||"application/json"});navigator.sendBeacon(r,g)?(a&&this.callbacks.printLog("批量发送成功: "+e.length+" 条数据"),l()):(this.callbacks.printLog("批量发送失败: sendBeacon 返回 false,数据已重新加入队列"),this.retryBatchData(e),l())}catch(t){this.callbacks.printLog("批量发送失败: "+t+",数据已重新加入队列"),this.retryBatchData(e),l()}else this.callbacks.ajax({url:r,type:"POST",data:JSON.stringify({events:e}),contentType:o,credentials:!1,timeout:this.config.sendTimeout,cors:!0,success:function(){n.config.showLog&&n.callbacks.printLog("批量发送成功: "+e.length+" 条数据"),l()},error:function(t){n.callbacks.printLog("批量发送失败: "+t+",数据已重新加入队列"),n.retryBatchData(e),l()}})},e.prototype.retryBatchData=function(e){var t=this,n=this.getQueueFromStorage(),r=function(e){return e.event+"_"+e.itemKey+"_"+e.requestTime},o=new Set(n.map(r)),a=this.callbacks.getTimeStamp(),s=e.filter((function(e){var n=r(e);if(o.has(n))return!1;var i=(e._retryCount||0)+1;return i>3?(t.config.showLog&&t.callbacks.printLog("数据已达到最大重试次数,放弃重试: "+n),!1):(e._retryCount=i,e._nextRetryTime=a+1e3*Math.pow(2,i),o.add(n),!0)})),c=i(i([],s),n),u=2*this.config.batchMaxSize,l=c.length>u?c.slice(0,u):c;this.saveQueueToStorage(l),this.config.showLog&&this.callbacks.printLog("已将 "+s.length+" 条数据加入重试队列")},e}(),l=function(){function e(e){this.deviceId="",this.callbacks=e}return e.prototype.getDeviceId=function(){if(this.deviceId)return this.deviceId;var e=this.callbacks.getCookie("device_id")||this.callbacks.getLocalStorage("device_id");if(e)return this.deviceId=e,this.deviceId;var t=this.callbacks.collectFingerprint(),n=this.callbacks.hashFingerprint(t);return this.callbacks.setCookie("device_id",n,730),this.callbacks.setLocalStorage("device_id",n),this.deviceId=n,this.deviceId},e.prototype.resetDeviceId=function(){return document.cookie="device_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",localStorage.removeItem("device_id"),this.deviceId="",this.getDeviceId()},e}(),g="web_tracking_pending_requests",p=function(){function e(e,t){this.isFlushingPendingData=!1,this.isUnloadListenerSetup=!1,this.config=e,this.callbacks=t}return e.prototype.updateConfig=function(e){this.config=n(n({},this.config),e)},e.prototype.addToQueue=function(e){var t=this.getQueueFromStorage();t.push(e);var n=this.config.pendingRequestsMaxSize||50;if(t.length>n){var i=t.slice(-n);this.config.showLog&&this.callbacks.printLog("待发送请求队列已满,已移除最旧的数据(最大限制: "+n+")"),this.saveQueueToStorage(i)}else this.saveQueueToStorage(t)},e.prototype.restoreQueue=function(){var e=this.getQueueFromStorage();e.length>0&&this.config.showLog&&this.callbacks.printLog("从 LocalStorage 恢复 "+e.length+" 条待发送请求")},e.prototype.flushQueue=function(){var e=this,t=this.getQueueFromStorage();if(0!==t.length){this.saveQueueToStorage([]);var n=this.config,i=n.serverUrl,r=n.sendTimeout,o=n.contentType,a=n.showLog,s=n.header;t.forEach((function(t){e.callbacks.shouldSample()?(a&&e.callbacks.printLog(JSON.stringify(t)),e.callbacks.ajax({url:i,type:"POST",data:JSON.stringify(t),contentType:o,header:s,credentials:!1,timeout:r,cors:!0,success:function(){a&&e.callbacks.printLog("待发送请求发送成功")},error:function(t){a&&e.callbacks.printLog("待发送请求发送失败(不再重试): "+t)}})):a&&e.callbacks.printLog("待发送请求已采样跳过")}))}},e.prototype.flushQueueWithBeacon=function(){var e=this;if(!this.isFlushingPendingData){this.isFlushingPendingData=!0;var t=this.getQueueFromStorage();if(0!==t.length){var n=this.config,i=n.serverUrl,r=n.contentType,o=n.showLog,a=0,s=0;t.forEach((function(t){e.sendWithBeacon(t,i,r)?a++:s++})),o&&this.callbacks.printLog("页面卸载时发送待请求数据: 成功 "+a+" 条,失败 "+s+" 条"),this.isFlushingPendingData=!1}else this.isFlushingPendingData=!1}},e.prototype.setupUnloadListener=function(){var e=this;this.isUnloadListenerSetup||(this.isUnloadListenerSetup=!0,document.addEventListener("visibilitychange",(function(){e.isPageUnloading()&&e.flushQueueWithBeacon()})),window.addEventListener("beforeunload",(function(){e.flushQueueWithBeacon()})),window.addEventListener("pagehide",(function(){e.flushQueueWithBeacon()})))},e.prototype.getQueueFromStorage=function(){try{var e=this.callbacks.getLocalStorage(g);if(e){var t=JSON.parse(e);if(Array.isArray(t))return t}}catch(e){this.callbacks.printLog("读取待发送请求失败: "+e),this.callbacks.setLocalStorage(g,"[]")}return[]},e.prototype.saveQueueToStorage=function(e){try{this.callbacks.setLocalStorage(g,JSON.stringify(e))}catch(e){this.callbacks.printLog("保存待发送请求到 LocalStorage 失败: "+e)}},e.prototype.isPageUnloading=function(){return"hidden"===document.visibilityState},e.prototype.sendWithBeacon=function(e,t,n){try{var i=new Blob([JSON.stringify(e)],{type:n||"application/json"});return navigator.sendBeacon(t,i)}catch(e){return this.config.showLog&&this.callbacks.printLog("sendBeacon 发送失败: "+e),!1}},e}();return new(function(i){function r(){var t=i.call(this)||this;return t.useCustomPageKey=!1,t.userInfo=null,t.currentUrl="",t.pageKey="",t.deviceId="",t.eventDescMap={PageView:"Web 浏览页面",WebClick:"Web 元素点击",PageRetained:"Web 页面浏览时长",CustomTrack:"Web 自定义代码上报",WebExposure:"Web 元素曝光"},t.init=function(e){t.preset(e);var n=window.location.pathname;t.currentUrl=window.location.href,e.pageKey?(t.pageKey=e.pageKey,t.useCustomPageKey=!0):(t.pageKey=n.replace(/\//g,"_").substring(1),t.useCustomPageKey=!1),t.systemsInfo=t.getSystemsInfo(e.platform),t.deviceId=t.deviceManager.getDeviceId(),e.userInfo&&t.isObject(e.userInfo)&&(t.userInfo=e.userInfo),t.setCookie("retainedStartTime",t.getTimeStamp()),t.initConfig.batchSend&&t.batchSender.restoreQueue(),t.pendingRequestsManager.restoreQueue(),t.pendingRequestsManager.setupUnloadListener();var i=t.getAutoTrackConfig();t.currentAutoTrackConfig=i,i.retained&&t.pageDurationTracker.start(),i.exposure&&t.exposureTracker.init()},t.preset=function(i){if(i instanceof Object){if(void 0!==i.pageKey)if(null===i.pageKey||""===i.pageKey){t.useCustomPageKey=!1;var r=window.location.pathname;t.pageKey=r.replace(/\//g,"_").substring(1)}else t.pageKey=i.pageKey,t.useCustomPageKey=!0;t.each(i,(function(i,r){if("pageKey"!==r){if("autoTrack"===r&&"object"===e(i)&&null!==i){var o=i;return t.initConfig.autoTrack=n(n({},t.currentAutoTrackConfig),o),void(t.currentAutoTrackConfig=t.getAutoTrackConfig())}if(t.initConfig.hasOwnProperty(r)){var a=t.validateConfigParam(String(r),i);a.valid?t.initConfig[r]=i:console.warn("配置参数验证失败: "+String(r)+" = "+i+", 原因: "+a.message)}}}))}/^(((ht|f)tps?):\/\/)?[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:/~+#\(\)]*[\w\-\.,@?^=%&/~+#\(\)])?$/.test(t.initConfig.serverUrl)||console.warn("当前 server_url 为空或不正确,只在控制台打印日志,network 中不会发数据,请配置正确的 server_url!"),t.initConfig.autoTrack||t.initConfig.trackPartKeyClick?t.listener():t.unlistener(),t.batchSender.updateConfig({batchSend:t.initConfig.batchSend,batchInterval:t.initConfig.batchInterval,batchMaxSize:t.initConfig.batchMaxSize,sendTimeout:t.initConfig.sendTimeout,serverUrl:t.initConfig.serverUrl,contentType:t.initConfig.contentType,showLog:t.initConfig.showLog,sendMethod:t.initConfig.sendMethod,header:t.initConfig.header}),t.pendingRequestsManager.updateConfig({pendingRequestsMaxSize:t.initConfig.pendingRequestsMaxSize,sendTimeout:t.initConfig.sendTimeout,serverUrl:t.initConfig.serverUrl,contentType:t.initConfig.contentType,showLog:t.initConfig.showLog,header:t.initConfig.header});var o=t.getAutoTrackConfig();o.retained?(t.pageDurationTracker.updateConfig({pageDurationInterval:t.initConfig.pageDurationInterval,showLog:t.initConfig.showLog}),t.pageDurationTracker.start()):t.pageDurationTracker.stop(),o.exposure?(t.exposureTracker.updateConfig({autoTrackExposure:!0,exposureThreshold:t.initConfig.exposureThreshold,exposureTime:t.initConfig.exposureTime,exposureNum:t.initConfig.exposureNum,showLog:t.initConfig.showLog}),t.exposureTracker.init()):t.exposureTracker.stop()},t.validateConfigParam=function(t,n){switch(t){case"sampleRate":if("number"!=typeof n||n<0||n>1)return{valid:!1,message:"sampleRate 必须是 0-1 之间的数字"};break;case"sendTimeout":if("number"!=typeof n||n<=0)return{valid:!1,message:"sendTimeout 必须是大于 0 的数字"};break;case"batchInterval":if("number"!=typeof n||n<=0)return{valid:!1,message:"batchInterval 必须是大于 0 的数字"};break;case"batchMaxSize":if("number"!=typeof n||n<=0||!Number.isInteger(n))return{valid:!1,message:"batchMaxSize 必须是大于 0 的整数"};break;case"pendingRequestsMaxSize":if("number"!=typeof n||n<=0||!Number.isInteger(n))return{valid:!1,message:"pendingRequestsMaxSize 必须是大于 0 的整数"};break;case"pageDurationInterval":if("number"!=typeof n||n<=0)return{valid:!1,message:"pageDurationInterval 必须是大于 0 的数字"};break;case"sendMethod":if("string"!=typeof n||!["auto","xhr","beacon"].includes(n))return{valid:!1,message:"sendMethod 必须是 auto、xhr 或 beacon"};break;case"exposureThreshold":if("number"!=typeof n||n<0||n>1)return{valid:!1,message:"exposureThreshold 必须是 0-1 之间的数字"};break;case"exposureTime":if("number"!=typeof n||n<=0)return{valid:!1,message:"exposureTime 必须是大于 0 的数字"};break;case"exposureNum":if(void 0!==n&&("number"!=typeof n||n<=0||!Number.isInteger(n)))return{valid:!1,message:"exposureNum 必须是大于 0 的整数或不限制"};break;case"showLog":case"isTrackSinglePage":case"batchSend":if("boolean"!=typeof n)return{valid:!1,message:t+" 必须是布尔值"};break;case"autoTrack":if("boolean"!=typeof n&&"object"!==e(n))return{valid:!1,message:"autoTrack 必须是布尔值或对象"};if("object"===e(n)&&null!==n){var i=n,r=["view","click","exposure","retained"];for(var o in i){if(!r.includes(o))return{valid:!1,message:"autoTrack 对象中包含无效的属性: "+o};if("boolean"!=typeof i[o])return{valid:!1,message:"autoTrack."+o+" 必须是布尔值"}}}break;case"business":case"header":if(null!==n&&"object"!==e(n))return{valid:!1,message:t+" 必须是对象或 null"};break;case"contentType":if("application/json"!==n&&"application/x-www-form-urlencoded"!==n)return{valid:!1,message:"contentType 必须是 application/json 或 application/x-www-form-urlencoded"};break;case"platform":if("string"!=typeof n)return{valid:!1,message:"platform 必须是字符串"}}return{valid:!0}},t.getAutoTrackConfig=function(){var n,i,r,o,a=t.initConfig.autoTrack;return"boolean"==typeof a?{view:a,click:a,exposure:a,retained:a}:"object"===e(a)&&null!==a?{view:null!==(n=a.view)&&void 0!==n&&n,click:null!==(i=a.click)&&void 0!==i&&i,exposure:null!==(r=a.exposure)&&void 0!==r&&r,retained:null!==(o=a.retained)&&void 0!==o&&o}:{view:!1,click:!1,exposure:!1,retained:!1}},t.login=function(e){t.isObject(e)&&(t.userInfo=e)},t.getDeviceId=function(){return t.deviceManager.getDeviceId()},t.resetDeviceId=function(){return t.deviceManager.resetDeviceId()},t.track=function(e){var n=e.desc,i=e.pageKey,r=e.partKey,o=e.business,a=e.header,s=t.getParams({desc:n,event:"CustomTrack",itemKey:t.getItemKey(r,i),privateParamMap:{business:o}});return t.sendData(s,a)},t.listener=function(){t.unlistener();var e=t.getAutoTrackConfig();e.view&&(t.initConfig.isTrackSinglePage&&(t.rewriteHistory(),t.addSinglePageEvent(t.onPageViewCallback)),t.each(["load","beforeunload"],(function(e){t.addEventListener(window,e,t.onPageViewCallback)}))),e.click&&t.addEventListener(window,"click",t.onClickCallback)},t.unlistener=function(){if(t.initConfig.isTrackSinglePage){var e=window.history.pushState?"popstate":"hashchange";t.each(["pushState","replaceState",e],(function(e){t.removeEventListener(window,e,t.onPageViewCallback)}))}t.each(["load","beforeunload"],(function(e){t.removeEventListener(window,e,t.onPageViewCallback)})),t.removeEventListener(window,"click",t.onClickCallback),t.batchSender.clearTimer(),t.pageDurationTracker.stop()},t.clearBatchTimer=function(){t.batchSender.clearTimer()},t.clearBatchQueue=function(){t.batchSender.clearQueue()},t.setPageKey=function(e,n){if(void 0===n&&(n=!1),null===e||""===e){t.useCustomPageKey=!1;var i=window.location.pathname;t.pageKey=i.replace(/\//g,"_").substring(1),t.initConfig.showLog&&t.printLog("页面标识已恢复自动生成: "+t.pageKey)}else t.pageKey=e,t.useCustomPageKey=!n,t.initConfig.showLog&&t.printLog("页面标识已设置为: "+e+", 自动更新: "+n)},t.getPageKey=function(){return t.pageKey},t.onClickCallback=function(e){var n,i=e.target;if(null===(n=null==i?void 0:i.dataset)||void 0===n?void 0:n.partKey){var r=[e.pageX,e.pageY],o=i.id,a=i.className,s=t.extractDataAttributes(i),c=i.getAttribute("data-desc")||t.eventDescMap.WebClick,u=i.getAttribute("data-part-key"),l=i.getAttribute("data-page-key")||void 0,g=t.getParams({event:"WebClick",desc:c,itemKey:t.getItemKey(u,l),privateParamMap:{business:s,targetEle:{nodeName:i.nodeName,id:o,className:a,position:r}}});t.sendData(g)}},t.onPageViewCallback=function(e){var n,i,r=window.location.origin,o=t.getParams({event:"PageView",desc:t.eventDescMap.PageView,privateParamMap:{currentUrl:t.currentUrl,targetUrl:(null===(n=e.arguments)||void 0===n?void 0:n[2])?r+(null===(i=e.arguments)||void 0===i?void 0:i[2]):null}});t.currentUrl=window.location.href,t.useCustomPageKey||(t.pageKey=window.location.pathname.replace(/\//g,"_").substring(1)),t.getAutoTrackConfig().retained&&(t.pageDurationTracker.stop(),t.pageDurationTracker.start()),t.sendData(o)},t.getParams=function(e){var n=e.event,i=e.desc,r=e.privateParamMap,o=void 0===r?{}:r,a=e.itemKey,s=t.initConfig.business,c=window.innerWidth,u=window.innerHeight,l=window.screen.width,g=window.screen.height,p=t.filterSensitiveData(s||{}),d=t.filterSensitiveData(t.userInfo||{}),h=t.filterSensitiveData(o||{}),f=t.filterSensitiveData(t.getQueryValue()||{}),v={currentUrl:h.currentUrl||t.currentUrl,business:Object.assign({},p,h.business||{}),pageWidth:c,pageHeight:u,screenWidth:l,screenHeight:g,sdkVersion:t.sdkVersion,systemsInfo:t.systemsInfo,urlParams:f,userInfo:d,deviceId:t.deviceId};return h.targetEle&&(v.targetEle=h.targetEle),h.targetUrl&&(v.targetUrl=h.targetUrl),h.pointerType&&(v.pointerType=h.pointerType),h.elementSelector&&(v.elementSelector=h.elementSelector),h.retainedDuration&&(v.retainedDuration=h.retainedDuration),void 0!==h.exposureScreenNo&&(v.exposureScreenNo=h.exposureScreenNo),{event:n,desc:i,itemKey:a||t.getItemKey(),requestTime:t.getTimeStamp(),privateParamMap:v}},t.shouldSample=function(){var e=t.initConfig.sampleRate;return e>=1||!(e<=0)&&Math.random()<e},t.shouldUseBeacon=function(e,t,n){return"beacon"===e||"xhr"!==e&&(!t&&!n&&"function"==typeof navigator.sendBeacon)},t.sendData=function(e,n){return new Promise((function(i,r){if(!t.shouldSample())return t.initConfig.showLog&&t.printLog("数据已采样跳过"),void i({success:!1,message:"数据已采样跳过"});if(t.initConfig.showLog&&t.printLog(e),t.initConfig.batchSend)return t.batchSender.addToQueue(e),void i({success:!0,message:"数据已加入批量队列"});var o=t.initConfig,a=o.serverUrl,s=o.sendTimeout,c=o.contentType,u=o.showLog,l=o.header;t.shouldUseBeacon(t.initConfig.sendMethod,n,l)?t.sendWithBeacon(e,a,c)?i({success:!0,message:"数据发送成功"}):(t.pendingRequestsManager.addToQueue(e),i({success:!1,message:"sendBeacon 发送失败,数据已加入待发送队列"})):t.ajax({url:a,type:"POST",data:JSON.stringify(e),contentType:c,header:n||l,credentials:!1,timeout:s,cors:!0,success:function(e){u&&t.printLog("数据发送成功",e),i({success:!0,data:e})},error:function(n){u&&t.printLog("数据发送失败",n),t.pendingRequestsManager.addToQueue(e),r({success:!1,message:"数据发送失败",error:n})}})}))},t.sendWithBeacon=function(e,n,i){try{var r=new Blob([JSON.stringify(e)],{type:i||"application/json"});return navigator.sendBeacon(n,r)}catch(e){return t.initConfig.showLog&&t.printLog("sendBeacon 发送失败: "+e),!1}},t.trackPageDuration=function(e,n,i){void 0===i&&(i=!0);var r=t.pageDurationTracker.calculateDuration(e),o=(null==n?void 0:n.desc)||t.eventDescMap.PageRetained,a=(null==n?void 0:n.pageKey)||t.pageKey,s=(null==n?void 0:n.business)||{},c=null==n?void 0:n.header,u=t.getParams({event:"PageRetained",desc:o,itemKey:t.getItemKey(void 0,a),privateParamMap:{business:s,retainedDuration:r}}),l=t.sendData(u,c);return i&&t.setCookie("retainedStartTime",t.getTimeStamp()),l},t.getItemKey=function(e,n){var i=void 0!==n?n:t.pageKey,r=void 0!==e?e:"";return r?t.initConfig.appKey+"."+i+"."+r:t.initConfig.appKey+"."+i},t.extractDataAttributes=function(e){for(var t={},n=0;n<e.attributes.length;n++){var i=e.attributes[n].name;if(i.startsWith("data-")&&"data-exposure"!==i&&"data-part-key"!==i&&"data-desc"!==i&&"data-page-key"!==i)t[i.replace("data-","").replace(/-([a-z])/g,(function(e,t){return t.toUpperCase()}))]=e.getAttribute(i)}return t},t.handleExposureReport=function(e,n){var i=t.exposureTracker.getElementInfo(e);if(!i)return Promise.resolve();var r=t.initConfig.exposureNum;if(void 0!==r&&i.exposureCount>=r)return t.initConfig.showLog&&t.printLog("元素已达到最大曝光次数限制: "+r),Promise.resolve();var o=t.extractDataAttributes(e),a=e.getAttribute("data-desc")||t.eventDescMap.WebExposure,s=e.getAttribute("data-part-key")||"exposure",c=e.getAttribute("data-page-key")||void 0,u=t.getParams({event:"WebExposure",desc:a,itemKey:t.getItemKey(s,c),privateParamMap:{business:o,exposureScreenNo:n}});return t.sendData(u).then((function(){t.exposureTracker.incrementExposureCount(e),t.exposureTracker.clearExposureTimer(e),t.initConfig.showLog&&t.printLog("曝光上报成功,当前曝光次数: "+(i.exposureCount+1))})).catch((function(e){t.initConfig.showLog&&t.printLog("曝光上报失败: "+e)}))},t.sdkVersion="1.2.8",t.initConfig={appKey:"",platform:void 0,showLog:!1,serverUrl:"",autoTrack:!1,sendTimeout:3e3,isTrackSinglePage:!1,contentType:"application/json",business:{},header:void 0,sampleRate:1,batchSend:!1,batchInterval:5e3,batchMaxSize:10,pendingRequestsMaxSize:50,pageDurationInterval:3e4,sendMethod:"auto",exposureThreshold:.5,exposureTime:500,exposureNum:void 0},t.systemsInfo={},t.deviceManager=new l({getCookie:t.getCookie.bind(t),setCookie:t.setCookie.bind(t),getLocalStorage:t.getLocalStorage.bind(t),setLocalStorage:t.setLocalStorage.bind(t),collectFingerprint:t.collectFingerprint.bind(t),hashFingerprint:t.hashFingerprint.bind(t)}),t.batchSender=new u({batchSend:!1,batchInterval:5e3,batchMaxSize:10,sendTimeout:3e3,serverUrl:"",contentType:"application/json",showLog:!1,sendMethod:"auto",header:void 0},{getLocalStorage:t.getLocalStorage.bind(t),setLocalStorage:t.setLocalStorage.bind(t),getTimeStamp:t.getTimeStamp.bind(t),ajax:t.ajax.bind(t),shouldSample:t.shouldSample.bind(t),shouldUseBeacon:t.shouldUseBeacon.bind(t),printLog:t.printLog.bind(t)}),t.pendingRequestsManager=new p({pendingRequestsMaxSize:50,sendTimeout:3e3,serverUrl:"",contentType:"application/json",showLog:!1,header:void 0},{getLocalStorage:t.getLocalStorage.bind(t),setLocalStorage:t.setLocalStorage.bind(t),shouldSample:t.shouldSample.bind(t),ajax:t.ajax.bind(t),printLog:t.printLog.bind(t)}),t.pageDurationTracker=new a({pageDurationInterval:3e4,showLog:!1},{getCookie:t.getCookie.bind(t),setCookie:t.setCookie.bind(t),getTimeStamp:t.getTimeStamp.bind(t),track:t.trackPageDuration.bind(t),printLog:t.printLog.bind(t)}),t.exposureTracker=new o({autoTrackExposure:!1,exposureThreshold:.5,exposureTime:500,exposureNum:void 0,showLog:!1},{reportExposure:t.handleExposureReport.bind(t),printLog:t.printLog.bind(t),getTimeStamp:t.getTimeStamp.bind(t),extractDataAttributes:t.extractDataAttributes.bind(t)}),t}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function i(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}(r,i),r.prototype.printLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.initConfig.showLog&&i.prototype.printLog.apply(this,e)},r.prototype.addSinglePageEvent=function(e){var t=this,n=window.history.pushState?"popstate":"hashchange";this.each(["pushState","replaceState",n],(function(n){t.addEventListener(window,n,e)}))},r}(r))}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).WebTracking=t()}(this,(function(){"use strict";function e(t){return(e="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})(t)}var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,n)};var n=function(){return(n=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)};function i(e,t){for(var n=0,i=t.length,r=e.length;n<i;n++,r++)e[r]=t[n];return e}var r=function(){function t(){var t=this;this.getSystemsInfo=function(e){var t=navigator.userAgent,n="other",i=[],r={language:navigator.language},o=t.match(/MicroMessenger\/([\d\.]+)/i),a=o&&o[1]?o[1]:null,s=t.match(/(ipod).*\s([\d_]+)/i),c=t.match(/(ipad).*\s([\d_]+)/i),u=t.match(/(iphone)\sos\s([\d_]+)/i),l=t.match(/(android)\s([\d\.]+)/i),g=t.match(/(Windows NT)\s([\d\.]+)/i),p=t.match(/(Mac OS X)\s([\d_]+)/i);i=[],l?(i.push("Android "+l[2]),n="h5"):u?(i.push("iPhone, iOS "+u[2].replace(/_/g,".")),n="h5"):c?(i.push("iPad, iOS "+c[2].replace(/_/g,".")),n="ipad"):s?(i.push("iPod, iOS "+s[2].replace(/_/g,".")),n="h5"):g?(i.push("Windows "+g[2].replace(/_/g,".")),n="pc"):p&&(i.push("Mac, MacOS "+p[2].replace(/_/g,".")),n="pc"),a&&i.push("WeChat "+a),r.client=i.length?i.join(", "):"Unknown",r.platform=e||n;var d=t.toLowerCase().match(/ nettype\/([^ ]+)/g);return d&&d[0]&&(i=[(d=d[0].split("/"))[1]],r.network=i.length?i.join(", "):"Unknown"),r.ua=t,r},this.addEventListener=function(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent&&e.attachEvent("on"+t,(function(t){return n.call(e,t)}),!1)},this.removeEventListener=function(e,t,n){e.removeEventListener?e.removeEventListener(t,n):e.detachEvent&&e.detachEvent("on"+t,(function(t){return n.call(e,t)}),!0)},this.rewriteHistory=function(){var e=window.history,t=function(e){var t=window.history,n=t[e],i=new Event(e);return function(){var e=n.apply(t,arguments);return i.arguments=arguments,window.dispatchEvent(i),e}};window.history.pushState&&(e.pushState=t("pushState"),e.replaceState=t("replaceState"))},this.isArray=Array.isArray||function(e){return"[object Array]"===toString.call(e)},this.formatJsonString=function(e){try{return JSON.stringify(e,null," ")}catch(t){return JSON.stringify(e)}},this.nativeForEach=Array.prototype.forEach,this.slice=Array.prototype.slice,this.hasOwnProperty=Object.prototype.hasOwnProperty,this.breaker={},this.each=function(e,n,i){if(null==e)return!1;if(t.nativeForEach&&e.forEach===t.nativeForEach)e.forEach(n,i);else if(t.isArray(e)&&e.length===+e.length){for(var r=0,o=e.length;r<o;r++)if(r in e&&n.call(i,e[r],r,e)===t.breaker)return!1}else for(var a in e)if(t.hasOwnProperty.call(e,a)&&n.call(i,e[a],a,e)===t.breaker)return!1;return!0},this.getDomIndex=function(e){if(!e.parentNode)return-1;for(var t=0,n=e.tagName,i=e.parentNode.children,r=0;r<i.length;r++)if(i[r].tagName===n){if(e===i[r])return t;t++}return-1},this.selector=function(e){var n=e.parentNode&&9==e.parentNode.nodeType?-1:t.getDomIndex(e);return e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?"#"+e.getAttribute("id"):e.tagName.toLowerCase()+(~n?":nth-of-type("+(n+1)+")":"")},this.getDomSelector=function(e,n){if(!e||!e.parentNode||!e.parentNode.children)return!1;n=n&&n.join?n:[];var i=e.nodeName.toLowerCase();return e&&"body"!==i&&1==e.nodeType?(n.unshift(t.selector(e)),e.getAttribute&&e.getAttribute("id")&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(e.getAttribute("id"))?n.join(" > "):t.getDomSelector(e.parentNode,n)):(n.unshift("body"),n.join(" > "))},this.getCookie=function(e){for(var t=e+"=",n=document.cookie.split(";"),i=0;i<n.length;i++){for(var r=n[i];" "==r.charAt(0);)r=r.substring(1,r.length);if(0==r.indexOf(t))return this._decodeURIComponent(r.substring(t.length,r.length))}return null},this.setCookie=function(e,t,n){var i,r="";n=null==n?73e3:n;var o=this.getMainHost();if(i=o?"; domain="+o:"",0!==n){var a=new Date;"s"===String(n).slice(-1)?a.setTime(a.getTime()+1e3*Number(String(n).slice(0,-1))):a.setTime(a.getTime()+24*n*60*60*1e3),r="; expires="+a.toUTCString()}function s(e){return e||!1}var c="",u="",l="";e&&(c=s(e)),t&&(u=s(t)),i&&(l=s(i)),c&&u&&(document.cookie=c+"="+encodeURIComponent(u)+r+"; path=/"+l)},this.getLocalStorage=function(e){try{return localStorage.getItem(e)}catch(e){return null}},this.setLocalStorage=function(e,t){try{localStorage.setItem(e,t)}catch(e){}},this.removeCookie=function(e){t.setCookie(e,"",-1)},this.getTimeStamp=function(){return(new Date).getTime()},this.uuid=function(){return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},this.getDistinctId=function(){var e=t.getCookie("distinctId");return e||(e=t.uuid(),t.setCookie("distinctId",e),e)},this.filterSensitiveData=function(e,n){if(void 0===n&&(n=["password","token","secret"]),!t.isObject(e))return e;var i={};return t.each(e,(function(e,r){n.some((function(e){return"string"==typeof r&&r.toLowerCase().includes(e.toLowerCase())}))?i[r]="***":t.isObject(e)?i[r]=t.filterSensitiveData(e,n):i[r]=e})),i},this.xssFilter=function(e){return e?"string"!=typeof e?e.toString():e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/"):""},this.getQueryValue=function(){for(var e=decodeURI(window.location.href).match(new RegExp("[?&][^?&]+=[^?&]+","g"))||[],t={},n=0;n<e.length;n++){var i=e[n].replace(/\?|\&/,"").split("=");t[i[0]]=i[1]}return Object.keys(t).length>0?t:null},this.ajax=function(n){function i(t){if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)}catch(e){return{}}return"object"===e(t)?t:{}}n.timeout=n.timeout||3e4,n.credentials=void 0===n.credentials||n.credentials;var r=t.xhr(n.cors);if(!r)return!1;n.type||(n.type=n.data?"POST":"GET");var o,a=n.success,s=n.error;n.success=function(e){a&&a(e),o&&(clearTimeout(o),o=null)},n.error=function(e,t){s&&s(e,t),o&&(clearTimeout(o),o=null)},o=window.setTimeout((function(){!function(){try{t.isObject(r)&&r.abort&&r.abort()}catch(e){t.printLog(e)}o&&(clearTimeout(o),o=null,n.error&&n.error(),r.onreadystatechange=null,r.onload=null,r.onerror=null)}()}),n.timeout),r.onreadystatechange=function(){try{4==r.readyState&&(r.status>=200&&r.status<300||304==r.status?n.success&&n.success(i(r.responseText)):n.error&&n.error(i(r.responseText),r.status),r.onreadystatechange=null,r.onload=null)}catch(e){r.onreadystatechange=null,r.onload=null}},r.open(n.type||"GET",n.url,!0);try{if(n.credentials&&(r.withCredentials=!0),t.isObject(n.header)&&t.each(n.header,(function(e,t){r.setRequestHeader&&r.setRequestHeader(t,e)})),n.data)n.cors||r.setRequestHeader&&r.setRequestHeader("X-Requested-With","XMLHttpRequest"),t.isObject(n.header)&&Object.keys(n.header).some((function(e){return"content-type"===e.toLowerCase()||"content-type"===e.toLowerCase()}))||("application/json"===n.contentType?r.setRequestHeader&&r.setRequestHeader("Content-type","application/json; charset=UTF-8"):r.setRequestHeader&&r.setRequestHeader("Content-type","application/x-www-form-urlencoded"))}catch(e){t.printLog(e)}r.send(n.data||null)},this.xhr=function(e){return e?void 0!==window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest?new XMLHttpRequest:null:void 0!==window.XMLHttpRequest?new XMLHttpRequest:null},this.getUA=function(){var e,t={},n=navigator.userAgent.toLowerCase();return(e=n.match(/opera.([\d.]+)/))?t.opera=Number(e[1].split(".")[0]):(e=n.match(/msie ([\d.]+)/))?t.ie=Number(e[1].split(".")[0]):(e=n.match(/edge.([\d.]+)/))?t.edge=Number(e[1].split(".")[0]):(e=n.match(/firefox\/([\d.]+)/))?t.firefox=Number(e[1].split(".")[0]):(e=n.match(/chrome\/([\d.]+)/))?t.chrome=Number(e[1].split(".")[0]):(e=n.match(/version\/([\d.]+).*safari/))?t.safari=Number(e[1].match(/^\d*.\d*/)):(e=n.match(/trident\/([\d.]+)/))&&(t.ie=11),t},this.isSupportBeaconSend=function(){var n=!1;if("object"!==("undefined"==typeof navigator?"undefined":e(navigator))||"function"!=typeof navigator.sendBeacon)return n;var i=t.getUA(),r=navigator.userAgent.toLowerCase();if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){var o=(r.match(/os [\d._]*/gi)+"").replace(/[^0-9|_.]/gi,"").replace(/_/gi,".").split(".");void 0===i.safari&&(i.safari=Number(o[0])),o[0]&&+o[0]<13?(i.chrome>41||i.firefox>30||i.opera>25||i.safari>12)&&(n=!0):(i.chrome>41||i.firefox>30||i.opera>25||i.safari>11.3)&&(n=!0)}else(i.chrome>38||i.edge>13||i.firefox>30||i.opera>25||i.safari>11)&&(n=!0);return n},this.throttle=function(e,t){var n=null,i=0;return function(){for(var r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var a=Date.now(),s=t-(a-i);s<=0||s>t?(n&&(clearTimeout(n),n=null),i=a,e.apply(void 0,r)):n||(n=window.setTimeout((function(){i=Date.now(),n=null,e.apply(void 0,r)}),s))}},this.debounce=function(e,t){var n=null;return function(){for(var i=[],r=0;r<arguments.length;r++)i[r]=arguments[r];n&&clearTimeout(n),n=window.setTimeout((function(){e.apply(void 0,i)}),t)}},this.sendBeacon=function(e){if(!0===t.isSupportBeaconSend()){var n={type:e.contentType},i=new Blob([JSON.stringify(e.data)],n);return navigator.sendBeacon(e.url,i)?Promise.resolve({success:!0,message:"发送成功"}):Promise.reject({success:!1,message:"sendBeacon返回false"})}return Promise.reject({success:!1,message:"不支持sendBeacon,发送失败!"})},this.getDeviceId=function(){var e=t.getCookie("device_id")||t.getLocalStorage("device_id");if(e)return e;var n=t.collectFingerprint(),i=t.hashFingerprint(n);return t.setCookie("device_id",i,730),t.setLocalStorage("device_id",i),i},this.collectFingerprint=function(){var e={};return e.userAgent=navigator.userAgent,e.screenWidth=screen.width,e.screenHeight=screen.height,e.colorDepth=screen.colorDepth,e.pixelDepth=screen.pixelDepth,e.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,e.timezoneOffset=(new Date).getTimezoneOffset(),e.language=navigator.language,e.languages=Array.from(navigator.languages),e.platform=navigator.platform,e.webgl=t.getWebGLFingerprint(),e.canvas=t.getCanvasFingerprint(),e.audio=t.getAudioFingerprint(),e.localStorage=t.hasLocalStorage(),e.sessionStorage=t.hasSessionStorage(),e.indexedDB=t.hasIndexedDB(),e.hardwareConcurrency=navigator.hardwareConcurrency,e.deviceMemory=navigator.deviceMemory,e.maxTouchPoints=navigator.maxTouchPoints,e},this.getWebGLFingerprint=function(){try{var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"not-supported";var n=t.getExtension("WEBGL_debug_renderer_info");return(n?t.getParameter(n.UNMASKED_VENDOR_WEBGL):"unknown")+"|"+(n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"unknown")}catch(e){return"error"}},this.getCanvasFingerprint=function(){try{var e=document.createElement("canvas");e.width=200,e.height=50;var t=e.getContext("2d");return t?(t.textBaseline="top",t.font="14px Arial",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("Canvas fingerprint",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("Canvas fingerprint",4,17),e.toDataURL().slice(-50)):"not-supported"}catch(e){return"error"}},this.getAudioFingerprint=function(){try{var e=window.AudioContext||window.webkitAudioContext;if(!e)return"not-supported";var t=new e,n=String(t.sampleRate||0);return t.close(),n}catch(e){return"error"}},this.hasLocalStorage=function(){try{var e="__test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}},this.hasSessionStorage=function(){try{var e="__test__";return sessionStorage.setItem(e,e),sessionStorage.removeItem(e),!0}catch(e){return!1}},this.hasIndexedDB=function(){return"indexedDB"in window&&null!==indexedDB},this.hashFingerprint=function(e){for(var t=JSON.stringify(e,Object.keys(e).sort()),n=5381,i=52711,r=0;r<t.length;r++){var o=t.charCodeAt(r);n=(n<<5)+n+o,i=(i<<5)+i+o}return"fp_"+(n>>>0).toString(16).padStart(8,"0")+(i>>>0).toString(16).padStart(8,"0")}}return t.prototype.printLog=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];if(this.isObject(t[0])&&(t[0]=this.formatJsonString(t[0])),"object"===("undefined"==typeof console?"undefined":e(console))&&console.log)try{return console.log.apply(console,t)}catch(e){console.log(t[0])}},t.prototype.isObject=function(e){return null!=e&&"[object Object]"==toString.call(e)},t.prototype.isUndefined=function(e){return void 0===e},t.prototype.isString=function(e){return"[object String]"==toString.call(e)},t.prototype.isDate=function(e){return"[object Date]"==toString.call(e)},t.prototype.isBoolean=function(e){return"[object Boolean]"==toString.call(e)},t.prototype.isNumber=function(e){return"[object Number]"==toString.call(e)&&/[\d\.]+/.test(String(e))},t.prototype.isElement=function(e){return!(!e||1!==e.nodeType)},t.prototype.isFunction=function(e){if(!e)return!1;var t=toString.call(e);return"[object Function]"==t||"[object AsyncFunction]"==t},t.prototype.isJSONString=function(e){if(!this.isString(e))return!1;try{JSON.parse(e)}catch(e){return!1}return!0},t.prototype._decodeURIComponent=function(e){var t=e;try{t=decodeURIComponent(e)}catch(n){t=e}return t},t.prototype.getMainHost=function(){var e="mh_"+Math.random(),t=new RegExp("(^|;)\\s*"+e+"=12345"),n=new Date(0),i=document.domain,r=i.split("."),o=[];for(o.unshift(r.pop());r.length;){o.unshift(r.pop());var a=o.join("."),s=e+"=12345;domain=."+a;if(document.cookie=s,t.test(document.cookie))return document.cookie=s+";expires="+n,a}return i},t}(),o=function(){function e(e,t){this.observer=null,this.mutationObserver=null,this.elementsMap=new Map,this.config=e,this.callbacks=t}return e.prototype.updateConfig=function(e){this.config=n(n({},this.config),e)},e.prototype.init=function(){var e=this;this.config.autoTrackExposure&&("IntersectionObserver"in window?(this.observer=new IntersectionObserver((function(t){t.forEach((function(t){var n=t.target,i=e.elementsMap.get(n);if(i){var r=e.config.exposureTime||500;t.isIntersecting?(i.isVisible=!0,i.visibleStartTime=e.callbacks.getTimeStamp(),i.exposureTimer&&clearTimeout(i.exposureTimer),i.exposureTimer=window.setTimeout((function(){if(i.isVisible){var t=e.calculateexposureScreenIndex(n);e.callbacks.reportExposure(n,t)}}),r)):(i.isVisible=!1,i.exposureTimer&&(clearTimeout(i.exposureTimer),i.exposureTimer=null))}}))}),{threshold:this.config.exposureThreshold||.5}),this.observeExposureElements(),this.initMutationObserver()):this.config.showLog&&this.callbacks.printLog("当前浏览器不支持 IntersectionObserver,无法启用曝光埋点"))},e.prototype.stop=function(){this.observer&&(this.observer.disconnect(),this.observer=null,this.elementsMap.forEach((function(e){e.exposureTimer&&clearTimeout(e.exposureTimer)})),this.elementsMap.clear()),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.config.showLog&&this.callbacks.printLog("曝光监听已停止")},e.prototype.addExposureElement=function(e){this.elementsMap.has(e)||(this.elementsMap.set(e,{element:e,visibleStartTime:0,exposureCount:0,isVisible:!1,exposureTimer:null}),this.observer&&this.observer.observe(e))},e.prototype.observeExposureElements=function(){var e=this;if(this.observer){var t=document.querySelectorAll('[data-exposure="true"]');t.forEach((function(t){e.addExposureElement(t)})),this.config.showLog&&t.length>0&&this.callbacks.printLog("已监听 "+t.length+" 个曝光元素"),document.body||document.addEventListener("DOMContentLoaded",(function(){var t=document.querySelectorAll('[data-exposure="true"]');t.forEach((function(t){e.addExposureElement(t)})),e.config.showLog&&t.length>0&&e.callbacks.printLog("DOMContentLoaded 后监听 "+t.length+" 个曝光元素")}))}},e.prototype.initMutationObserver=function(){var e=this;"MutationObserver"in window?(this.mutationObserver=new MutationObserver((function(t){t.forEach((function(t){t.addedNodes.forEach((function(t){if(t.nodeType===Node.ELEMENT_NODE){var n=t;if(n.hasAttribute("data-exposure")&&"true"===n.getAttribute("data-exposure"))e.addExposureElement(n);else n.querySelectorAll('[data-exposure="true"]').forEach((function(t){e.addExposureElement(t)}))}}))}))})),document.body?(this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),this.config.showLog&&this.callbacks.printLog("MutationObserver 已启动,监听动态添加的曝光元素")):document.addEventListener("DOMContentLoaded",(function(){e.mutationObserver&&document.body&&(e.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),e.config.showLog&&e.callbacks.printLog("MutationObserver 已启动,监听动态添加的曝光元素"))}))):this.config.showLog&&this.callbacks.printLog("当前浏览器不支持 MutationObserver,无法监听动态添加的曝光元素")},e.prototype.calculateexposureScreenIndex=function(e){var t=e.getBoundingClientRect(),n=window.innerHeight||document.documentElement.clientHeight,i=window.scrollY||document.documentElement.scrollTop,r=t.top+i;return r<=0?1:Math.ceil(r/n)},e.prototype.getElementInfo=function(e){return this.elementsMap.get(e)},e.prototype.incrementExposureCount=function(e){var t=this.elementsMap.get(e);t&&t.exposureCount++},e.prototype.clearExposureTimer=function(e){var t=this.elementsMap.get(e);t&&t.exposureTimer&&(clearTimeout(t.exposureTimer),t.exposureTimer=null)},e}(),a=function(){function e(e,t){this.timer=null,this.config=e,this.callbacks=t}return e.prototype.updateConfig=function(e){var t=this.config.pageDurationInterval;this.config=n(n({},this.config),e),void 0!==e.pageDurationInterval&&e.pageDurationInterval!==t&&null!==this.timer&&(this.stop(),this.start())},e.prototype.start=function(){var e=this;this.stop();var t=this.config.pageDurationInterval||3e4;t<=0?this.config.showLog&&this.callbacks.printLog("定时上报间隔时间无效,已禁用定时上报"):(this.timer=window.setInterval((function(){"visible"===document.visibilityState&&e.callbacks.track(t,{desc:"定时上报页面停留时长"},!0).catch((function(t){e.config.showLog&&e.callbacks.printLog("定时上报页面停留时长失败: "+t)}))}),t),this.config.showLog&&this.callbacks.printLog("定时上报页面停留时长已启动,间隔: "+t+"ms"))},e.prototype.stop=function(){null!==this.timer&&(clearInterval(this.timer),this.timer=null,this.config.showLog&&this.callbacks.printLog("定时上报页面停留时长已停止"))},e.prototype.calculateDuration=function(e){if(null!=e)return Math.max(e,0);var t=this.callbacks.getCookie("retainedStartTime"),n=t?+t:this.callbacks.getTimeStamp(),i=this.callbacks.getTimeStamp();return Math.max(i-n,0)},e}(),s="web_tracking_batch_queue",c=4194304,u=function(){function e(e,t){this.timer=null,this.isFlushingQueue=!1,this.config=e,this.callbacks=t}return e.prototype.start=function(){var e=this;this.config.batchSend&&(this.clearTimer(),this.timer=window.setInterval((function(){e.flushQueue()}),this.config.batchInterval))},e.prototype.updateConfig=function(e){this.config=n(n({},this.config),e),this.clearTimer(),this.start()},e.prototype.addToQueue=function(e){if(this.config.batchSend)if(this.callbacks.shouldSample()){var t=this.getQueueFromStorage();t.push(e),this.saveQueueToStorage(t),t.length>=this.config.batchMaxSize&&this.flushQueue()}else this.config.showLog&&this.callbacks.printLog("数据已采样跳过(批量模式)")},e.prototype.clearTimer=function(){null!==this.timer&&(clearInterval(this.timer),this.timer=null)},e.prototype.clearQueue=function(){this.callbacks.setLocalStorage(s,"[]"),this.config.showLog&&this.callbacks.printLog("批量队列已清空")},e.prototype.restoreQueue=function(){var e=this.getQueueFromStorage();e.length>0&&this.config.showLog&&this.callbacks.printLog("从 LocalStorage 恢复 "+e.length+" 条批量数据")},e.prototype.getQueueFromStorage=function(){try{var e=this.callbacks.getLocalStorage(s);if(e){var t=JSON.parse(e);if(Array.isArray(t))return t}}catch(e){this.callbacks.printLog("读取批量队列失败: "+e),this.callbacks.setLocalStorage(s,"[]")}return[]},e.prototype.saveQueueToStorage=function(e){try{var t=JSON.stringify(e);if(t.length>c){var n=Math.floor(.8*e.length),i=e.slice(-n);this.callbacks.printLog("队列过大,已截断保留最新 "+n+" 条数据(限制: 4MB)"),this.callbacks.setLocalStorage(s,JSON.stringify(i))}else this.callbacks.setLocalStorage(s,t)}catch(e){this.callbacks.printLog("保存批量队列到 LocalStorage 失败: "+e)}},e.prototype.flushQueue=function(){var e=this;if(!this.isFlushingQueue){var t=this.getQueueFromStorage();if(0!==t.length){var n=this.callbacks.getTimeStamp(),i=t.filter((function(e){return!e._nextRetryTime||e._nextRetryTime<=n}));if(0!==i.length){var r=t.filter((function(e){return!!e._nextRetryTime&&e._nextRetryTime>n}));this.saveQueueToStorage(r),this.isFlushingQueue=!0,this.sendBatchData(i,(function(){e.isFlushingQueue=!1}))}else this.config.showLog&&this.callbacks.printLog("批量队列中有 "+t.length+" 条数据等待重试")}}},e.prototype.sendBatchData=function(e,t){var n=this,i=this.config,r=i.serverUrl,o=i.contentType,a=i.showLog,s=i.sendMethod,c=i.header;a&&(this.callbacks.printLog("批量发送 "+e.length+" 条数据"),e.forEach((function(e){return n.callbacks.printLog(JSON.stringify(e))})));var u=this.callbacks.shouldUseBeacon(s,void 0,c),l=function(){t&&t()};if(u)try{var g=new Blob([JSON.stringify(e)],{type:o||"application/json"});navigator.sendBeacon(r,g)?(a&&this.callbacks.printLog("批量发送成功: "+e.length+" 条数据"),l()):(this.callbacks.printLog("批量发送失败: sendBeacon 返回 false,数据已重新加入队列"),this.retryBatchData(e),l())}catch(t){this.callbacks.printLog("批量发送失败: "+t+",数据已重新加入队列"),this.retryBatchData(e),l()}else this.callbacks.ajax({url:r,type:"POST",data:JSON.stringify(e),contentType:o,credentials:!1,timeout:this.config.sendTimeout,cors:!0,success:function(){n.config.showLog&&n.callbacks.printLog("批量发送成功: "+e.length+" 条数据"),l()},error:function(t){n.callbacks.printLog("批量发送失败: "+t+",数据已重新加入队列"),n.retryBatchData(e),l()}})},e.prototype.retryBatchData=function(e){var t=this,n=this.getQueueFromStorage(),r=function(e){return e.event+"_"+e.itemKey+"_"+e.requestTime},o=new Set(n.map(r)),a=this.callbacks.getTimeStamp(),s=e.filter((function(e){var n=r(e);if(o.has(n))return!1;var i=(e._retryCount||0)+1;return i>3?(t.config.showLog&&t.callbacks.printLog("数据已达到最大重试次数,放弃重试: "+n),!1):(e._retryCount=i,e._nextRetryTime=a+1e3*Math.pow(2,i),o.add(n),!0)})),c=i(i([],s),n),u=2*this.config.batchMaxSize,l=c.length>u?c.slice(0,u):c;this.saveQueueToStorage(l),this.config.showLog&&this.callbacks.printLog("已将 "+s.length+" 条数据加入重试队列")},e}(),l=function(){function e(e){this.deviceId="",this.callbacks=e}return e.prototype.getDeviceId=function(){if(this.deviceId)return this.deviceId;var e=this.callbacks.getCookie("device_id")||this.callbacks.getLocalStorage("device_id");if(e)return this.deviceId=e,this.deviceId;var t=this.callbacks.collectFingerprint(),n=this.callbacks.hashFingerprint(t);return this.callbacks.setCookie("device_id",n,730),this.callbacks.setLocalStorage("device_id",n),this.deviceId=n,this.deviceId},e.prototype.resetDeviceId=function(){return document.cookie="device_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",localStorage.removeItem("device_id"),this.deviceId="",this.getDeviceId()},e}(),g="web_tracking_pending_requests",p=function(){function e(e,t){this.isFlushingPendingData=!1,this.isUnloadListenerSetup=!1,this.config=e,this.callbacks=t}return e.prototype.updateConfig=function(e){this.config=n(n({},this.config),e)},e.prototype.addToQueue=function(e){var t=this.getQueueFromStorage();t.push(e);var n=this.config.pendingRequestsMaxSize||50;if(t.length>n){var i=t.slice(-n);this.config.showLog&&this.callbacks.printLog("待发送请求队列已满,已移除最旧的数据(最大限制: "+n+")"),this.saveQueueToStorage(i)}else this.saveQueueToStorage(t)},e.prototype.restoreQueue=function(){var e=this.getQueueFromStorage();e.length>0&&this.config.showLog&&this.callbacks.printLog("从 LocalStorage 恢复 "+e.length+" 条待发送请求")},e.prototype.flushQueue=function(){var e=this,t=this.getQueueFromStorage();if(0!==t.length){this.saveQueueToStorage([]);var n=this.config,i=n.serverUrl,r=n.sendTimeout,o=n.contentType,a=n.showLog,s=n.header;t.forEach((function(t){e.callbacks.shouldSample()?(a&&e.callbacks.printLog(JSON.stringify(t)),e.callbacks.ajax({url:i,type:"POST",data:JSON.stringify(t),contentType:o,header:s,credentials:!1,timeout:r,cors:!0,success:function(){a&&e.callbacks.printLog("待发送请求发送成功")},error:function(t){a&&e.callbacks.printLog("待发送请求发送失败(不再重试): "+t)}})):a&&e.callbacks.printLog("待发送请求已采样跳过")}))}},e.prototype.flushQueueWithBeacon=function(){var e=this;if(!this.isFlushingPendingData){this.isFlushingPendingData=!0;var t=this.getQueueFromStorage();if(0!==t.length){var n=this.config,i=n.serverUrl,r=n.contentType,o=n.showLog,a=0,s=0;t.forEach((function(t){e.sendWithBeacon(t,i,r)?a++:s++})),o&&this.callbacks.printLog("页面卸载时发送待请求数据: 成功 "+a+" 条,失败 "+s+" 条"),this.isFlushingPendingData=!1}else this.isFlushingPendingData=!1}},e.prototype.setupUnloadListener=function(){var e=this;this.isUnloadListenerSetup||(this.isUnloadListenerSetup=!0,document.addEventListener("visibilitychange",(function(){e.isPageUnloading()&&e.flushQueueWithBeacon()})),window.addEventListener("beforeunload",(function(){e.flushQueueWithBeacon()})),window.addEventListener("pagehide",(function(){e.flushQueueWithBeacon()})))},e.prototype.getQueueFromStorage=function(){try{var e=this.callbacks.getLocalStorage(g);if(e){var t=JSON.parse(e);if(Array.isArray(t))return t}}catch(e){this.callbacks.printLog("读取待发送请求失败: "+e),this.callbacks.setLocalStorage(g,"[]")}return[]},e.prototype.saveQueueToStorage=function(e){try{this.callbacks.setLocalStorage(g,JSON.stringify(e))}catch(e){this.callbacks.printLog("保存待发送请求到 LocalStorage 失败: "+e)}},e.prototype.isPageUnloading=function(){return"hidden"===document.visibilityState},e.prototype.sendWithBeacon=function(e,t,n){try{var i=new Blob([JSON.stringify(e)],{type:n||"application/json"});return navigator.sendBeacon(t,i)}catch(e){return this.config.showLog&&this.callbacks.printLog("sendBeacon 发送失败: "+e),!1}},e}();return new(function(i){function r(){var t=i.call(this)||this;return t.useCustomPageKey=!1,t.userInfo=null,t.currentUrl="",t.pageKey="",t.deviceId="",t.eventDescMap={PageView:"Web 浏览页面",WebClick:"Web 元素点击",PageRetained:"Web 页面浏览时长",CustomTrack:"Web 自定义代码上报",WebExposure:"Web 元素曝光"},t.init=function(e){t.preset(e);var n=window.location.pathname;t.currentUrl=window.location.href,e.pageKey?(t.pageKey=e.pageKey,t.useCustomPageKey=!0):(t.pageKey=n.replace(/\//g,"_").substring(1),t.useCustomPageKey=!1),t.systemsInfo=t.getSystemsInfo(e.platform),t.deviceId=t.deviceManager.getDeviceId(),e.userInfo&&t.isObject(e.userInfo)&&(t.userInfo=e.userInfo),t.setCookie("retainedStartTime",t.getTimeStamp()),t.initConfig.batchSend&&t.batchSender.restoreQueue(),t.pendingRequestsManager.restoreQueue(),t.pendingRequestsManager.setupUnloadListener();var i=t.getAutoTrackConfig();t.currentAutoTrackConfig=i,i.retained&&t.pageDurationTracker.start(),i.exposure&&t.exposureTracker.init()},t.preset=function(i){if(i instanceof Object){if(void 0!==i.pageKey)if(null===i.pageKey||""===i.pageKey){t.useCustomPageKey=!1;var r=window.location.pathname;t.pageKey=r.replace(/\//g,"_").substring(1)}else t.pageKey=i.pageKey,t.useCustomPageKey=!0;t.each(i,(function(i,r){if("pageKey"!==r){if("autoTrack"===r&&"object"===e(i)&&null!==i){var o=i;return t.initConfig.autoTrack=n(n({},t.currentAutoTrackConfig),o),void(t.currentAutoTrackConfig=t.getAutoTrackConfig())}if(t.initConfig.hasOwnProperty(r)){var a=t.validateConfigParam(String(r),i);a.valid?t.initConfig[r]=i:console.warn("配置参数验证失败: "+String(r)+" = "+i+", 原因: "+a.message)}}}))}/^(((ht|f)tps?):\/\/)?[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:/~+#\(\)]*[\w\-\.,@?^=%&/~+#\(\)])?$/.test(t.initConfig.serverUrl)||console.warn("当前 server_url 为空或不正确,只在控制台打印日志,network 中不会发数据,请配置正确的 server_url!"),t.initConfig.autoTrack||t.initConfig.trackPartKeyClick?t.listener():t.unlistener(),t.batchSender.updateConfig({batchSend:t.initConfig.batchSend,batchInterval:t.initConfig.batchInterval,batchMaxSize:t.initConfig.batchMaxSize,sendTimeout:t.initConfig.sendTimeout,serverUrl:t.initConfig.serverUrl,contentType:t.initConfig.contentType,showLog:t.initConfig.showLog,sendMethod:t.initConfig.sendMethod,header:t.initConfig.header}),t.pendingRequestsManager.updateConfig({pendingRequestsMaxSize:t.initConfig.pendingRequestsMaxSize,sendTimeout:t.initConfig.sendTimeout,serverUrl:t.initConfig.serverUrl,contentType:t.initConfig.contentType,showLog:t.initConfig.showLog,header:t.initConfig.header});var o=t.getAutoTrackConfig();o.retained?(t.pageDurationTracker.updateConfig({pageDurationInterval:t.initConfig.pageDurationInterval,showLog:t.initConfig.showLog}),t.pageDurationTracker.start()):t.pageDurationTracker.stop(),o.exposure?(t.exposureTracker.updateConfig({autoTrackExposure:!0,exposureThreshold:t.initConfig.exposureThreshold,exposureTime:t.initConfig.exposureTime,exposureNum:t.initConfig.exposureNum,showLog:t.initConfig.showLog}),t.exposureTracker.init()):t.exposureTracker.stop()},t.validateConfigParam=function(t,n){switch(t){case"sampleRate":if("number"!=typeof n||n<0||n>1)return{valid:!1,message:"sampleRate 必须是 0-1 之间的数字"};break;case"sendTimeout":if("number"!=typeof n||n<=0)return{valid:!1,message:"sendTimeout 必须是大于 0 的数字"};break;case"batchInterval":if("number"!=typeof n||n<=0)return{valid:!1,message:"batchInterval 必须是大于 0 的数字"};break;case"batchMaxSize":if("number"!=typeof n||n<=0||!Number.isInteger(n))return{valid:!1,message:"batchMaxSize 必须是大于 0 的整数"};break;case"pendingRequestsMaxSize":if("number"!=typeof n||n<=0||!Number.isInteger(n))return{valid:!1,message:"pendingRequestsMaxSize 必须是大于 0 的整数"};break;case"pageDurationInterval":if("number"!=typeof n||n<=0)return{valid:!1,message:"pageDurationInterval 必须是大于 0 的数字"};break;case"sendMethod":if("string"!=typeof n||!["auto","xhr","beacon"].includes(n))return{valid:!1,message:"sendMethod 必须是 auto、xhr 或 beacon"};break;case"exposureThreshold":if("number"!=typeof n||n<0||n>1)return{valid:!1,message:"exposureThreshold 必须是 0-1 之间的数字"};break;case"exposureTime":if("number"!=typeof n||n<=0)return{valid:!1,message:"exposureTime 必须是大于 0 的数字"};break;case"exposureNum":if(void 0!==n&&("number"!=typeof n||n<=0||!Number.isInteger(n)))return{valid:!1,message:"exposureNum 必须是大于 0 的整数或不限制"};break;case"showLog":case"isTrackSinglePage":case"batchSend":if("boolean"!=typeof n)return{valid:!1,message:t+" 必须是布尔值"};break;case"autoTrack":if("boolean"!=typeof n&&"object"!==e(n))return{valid:!1,message:"autoTrack 必须是布尔值或对象"};if("object"===e(n)&&null!==n){var i=n,r=["view","click","exposure","retained"];for(var o in i){if(!r.includes(o))return{valid:!1,message:"autoTrack 对象中包含无效的属性: "+o};if("boolean"!=typeof i[o])return{valid:!1,message:"autoTrack."+o+" 必须是布尔值"}}}break;case"business":case"header":if(null!==n&&"object"!==e(n))return{valid:!1,message:t+" 必须是对象或 null"};break;case"contentType":if("application/json"!==n&&"application/x-www-form-urlencoded"!==n)return{valid:!1,message:"contentType 必须是 application/json 或 application/x-www-form-urlencoded"};break;case"platform":if("string"!=typeof n)return{valid:!1,message:"platform 必须是字符串"}}return{valid:!0}},t.getAutoTrackConfig=function(){var n,i,r,o,a=t.initConfig.autoTrack;return"boolean"==typeof a?{view:a,click:a,exposure:a,retained:a}:"object"===e(a)&&null!==a?{view:null!==(n=a.view)&&void 0!==n&&n,click:null!==(i=a.click)&&void 0!==i&&i,exposure:null!==(r=a.exposure)&&void 0!==r&&r,retained:null!==(o=a.retained)&&void 0!==o&&o}:{view:!1,click:!1,exposure:!1,retained:!1}},t.login=function(e){t.isObject(e)&&(t.userInfo=e)},t.getDeviceId=function(){return t.deviceManager.getDeviceId()},t.resetDeviceId=function(){return t.deviceManager.resetDeviceId()},t.track=function(e){var n=e.event,i=e.desc,r=e.pageKey,o=e.partKey,a=e.business,s=e.header,c=t.getParams({desc:i,event:n||"CustomTrack",itemKey:t.getItemKey(o,r),privateParamMap:{business:a}});return t.sendData(c,s)},t.listener=function(){t.unlistener();var e=t.getAutoTrackConfig();e.view&&(t.initConfig.isTrackSinglePage&&(t.rewriteHistory(),t.addSinglePageEvent(t.onPageViewCallback)),t.each(["load","beforeunload"],(function(e){t.addEventListener(window,e,t.onPageViewCallback)}))),e.click&&t.addEventListener(window,"click",t.onClickCallback)},t.unlistener=function(){if(t.initConfig.isTrackSinglePage){var e=window.history.pushState?"popstate":"hashchange";t.each(["pushState","replaceState",e],(function(e){t.removeEventListener(window,e,t.onPageViewCallback)}))}t.each(["load","beforeunload"],(function(e){t.removeEventListener(window,e,t.onPageViewCallback)})),t.removeEventListener(window,"click",t.onClickCallback),t.batchSender.clearTimer(),t.pageDurationTracker.stop()},t.clearBatchTimer=function(){t.batchSender.clearTimer()},t.clearBatchQueue=function(){t.batchSender.clearQueue()},t.setPageKey=function(e,n){if(void 0===n&&(n=!1),null===e||""===e){t.useCustomPageKey=!1;var i=window.location.pathname;t.pageKey=i.replace(/\//g,"_").substring(1),t.initConfig.showLog&&t.printLog("页面标识已恢复自动生成: "+t.pageKey)}else t.pageKey=e,t.useCustomPageKey=!n,t.initConfig.showLog&&t.printLog("页面标识已设置为: "+e+", 自动更新: "+n)},t.getPageKey=function(){return t.pageKey},t.onClickCallback=function(e){var n,i=e.target;if(null===(n=null==i?void 0:i.dataset)||void 0===n?void 0:n.partKey){var r=[e.pageX,e.pageY],o=i.id,a=i.className,s=t.extractDataAttributes(i),c=i.getAttribute("data-desc")||t.eventDescMap.WebClick,u=i.getAttribute("data-part-key"),l=i.getAttribute("data-page-key")||void 0,g=t.getParams({event:"WebClick",desc:c,itemKey:t.getItemKey(u,l),privateParamMap:{business:s,targetEle:{nodeName:i.nodeName,id:o,className:a,position:r}}});t.sendData(g)}},t.onPageViewCallback=function(e){var n,i,r=window.location.origin,o=t.getParams({event:"PageView",desc:t.eventDescMap.PageView,privateParamMap:{currentUrl:t.currentUrl,targetUrl:(null===(n=e.arguments)||void 0===n?void 0:n[2])?r+(null===(i=e.arguments)||void 0===i?void 0:i[2]):null}});t.currentUrl=window.location.href,t.useCustomPageKey||(t.pageKey=window.location.pathname.replace(/\//g,"_").substring(1)),t.getAutoTrackConfig().retained&&(t.pageDurationTracker.stop(),t.pageDurationTracker.start()),t.sendData(o)},t.getParams=function(e){var n=e.event,i=e.desc,r=e.privateParamMap,o=void 0===r?{}:r,a=e.itemKey,s=t.initConfig.business,c=window.innerWidth,u=window.innerHeight,l=window.screen.width,g=window.screen.height,p=t.filterSensitiveData(s||{}),d=t.filterSensitiveData(t.userInfo||{}),h=t.filterSensitiveData(o||{}),f=t.filterSensitiveData(t.getQueryValue()||{}),v={currentUrl:h.currentUrl||t.currentUrl,business:Object.assign({},p,h.business||{}),pageWidth:c,pageHeight:u,screenWidth:l,screenHeight:g,sdkVersion:t.sdkVersion,systemsInfo:t.systemsInfo,urlParams:f,userInfo:d,deviceId:t.deviceId};return h.targetEle&&(v.targetEle=h.targetEle),h.targetUrl&&(v.targetUrl=h.targetUrl),h.pointerType&&(v.pointerType=h.pointerType),h.elementSelector&&(v.elementSelector=h.elementSelector),h.retainedDuration&&(v.retainedDuration=h.retainedDuration),void 0!==h.exposureScreenNo&&(v.exposureScreenNo=h.exposureScreenNo),{event:n,desc:i,itemKey:a||t.getItemKey(),requestTime:t.getTimeStamp(),privateParamMap:v}},t.shouldSample=function(){var e=t.initConfig.sampleRate;return e>=1||!(e<=0)&&Math.random()<e},t.shouldUseBeacon=function(e,t,n){return"beacon"===e||"xhr"!==e&&(!t&&!n&&"function"==typeof navigator.sendBeacon)},t.sendData=function(e,n){return new Promise((function(i,r){if(!t.shouldSample())return t.initConfig.showLog&&t.printLog("数据已采样跳过"),void i({success:!1,message:"数据已采样跳过"});if(t.initConfig.showLog&&t.printLog(e),t.initConfig.batchSend)return t.batchSender.addToQueue(e),void i({success:!0,message:"数据已加入批量队列"});var o=t.initConfig,a=o.serverUrl,s=o.sendTimeout,c=o.contentType,u=o.showLog,l=o.header;t.shouldUseBeacon(t.initConfig.sendMethod,n,l)?t.sendWithBeacon(e,a,c)?i({success:!0,message:"数据发送成功"}):(t.pendingRequestsManager.addToQueue(e),i({success:!1,message:"sendBeacon 发送失败,数据已加入待发送队列"})):t.ajax({url:a,type:"POST",data:JSON.stringify(e),contentType:c,header:n||l,credentials:!1,timeout:s,cors:!0,success:function(e){u&&t.printLog("数据发送成功",e),i({success:!0,data:e})},error:function(n){u&&t.printLog("数据发送失败",n),t.pendingRequestsManager.addToQueue(e),r({success:!1,message:"数据发送失败",error:n})}})}))},t.sendWithBeacon=function(e,n,i){try{var r=new Blob([JSON.stringify(e)],{type:i||"application/json"});return navigator.sendBeacon(n,r)}catch(e){return t.initConfig.showLog&&t.printLog("sendBeacon 发送失败: "+e),!1}},t.trackPageDuration=function(e,n,i){void 0===i&&(i=!0);var r=t.pageDurationTracker.calculateDuration(e),o=(null==n?void 0:n.desc)||t.eventDescMap.PageRetained,a=(null==n?void 0:n.pageKey)||t.pageKey,s=(null==n?void 0:n.business)||{},c=null==n?void 0:n.header,u=t.getParams({event:"PageRetained",desc:o,itemKey:t.getItemKey(void 0,a),privateParamMap:{business:s,retainedDuration:r}}),l=t.sendData(u,c);return i&&t.setCookie("retainedStartTime",t.getTimeStamp()),l},t.getItemKey=function(e,n){var i=void 0!==n?n:t.pageKey,r=void 0!==e?e:"";return r?t.initConfig.appKey+"."+i+"."+r:t.initConfig.appKey+"."+i},t.extractDataAttributes=function(e){for(var t={},n=0;n<e.attributes.length;n++){var i=e.attributes[n].name;if(i.startsWith("data-")&&"data-exposure"!==i&&"data-part-key"!==i&&"data-desc"!==i&&"data-page-key"!==i)t[i.replace("data-","").replace(/-([a-z])/g,(function(e,t){return t.toUpperCase()}))]=e.getAttribute(i)}return t},t.handleExposureReport=function(e,n){var i=t.exposureTracker.getElementInfo(e);if(!i)return Promise.resolve();var r=t.initConfig.exposureNum;if(void 0!==r&&i.exposureCount>=r)return t.initConfig.showLog&&t.printLog("元素已达到最大曝光次数限制: "+r),Promise.resolve();var o=t.extractDataAttributes(e),a=e.getAttribute("data-desc")||t.eventDescMap.WebExposure,s=e.getAttribute("data-part-key")||"exposure",c=e.getAttribute("data-page-key")||void 0,u=t.getParams({event:"WebExposure",desc:a,itemKey:t.getItemKey(s,c),privateParamMap:{business:o,exposureScreenNo:n}});return t.sendData(u).then((function(){t.exposureTracker.incrementExposureCount(e),t.exposureTracker.clearExposureTimer(e),t.initConfig.showLog&&t.printLog("曝光上报成功,当前曝光次数: "+(i.exposureCount+1))})).catch((function(e){t.initConfig.showLog&&t.printLog("曝光上报失败: "+e)}))},t.sdkVersion="1.2.8",t.initConfig={appKey:"",platform:void 0,showLog:!1,serverUrl:"",autoTrack:!1,sendTimeout:3e3,isTrackSinglePage:!1,contentType:"application/json",business:{},header:void 0,sampleRate:1,batchSend:!1,batchInterval:5e3,batchMaxSize:10,pendingRequestsMaxSize:50,pageDurationInterval:3e4,sendMethod:"auto",exposureThreshold:.5,exposureTime:500,exposureNum:void 0},t.systemsInfo={},t.deviceManager=new l({getCookie:t.getCookie.bind(t),setCookie:t.setCookie.bind(t),getLocalStorage:t.getLocalStorage.bind(t),setLocalStorage:t.setLocalStorage.bind(t),collectFingerprint:t.collectFingerprint.bind(t),hashFingerprint:t.hashFingerprint.bind(t)}),t.batchSender=new u({batchSend:!1,batchInterval:5e3,batchMaxSize:10,sendTimeout:3e3,serverUrl:"",contentType:"application/json",showLog:!1,sendMethod:"auto",header:void 0},{getLocalStorage:t.getLocalStorage.bind(t),setLocalStorage:t.setLocalStorage.bind(t),getTimeStamp:t.getTimeStamp.bind(t),ajax:t.ajax.bind(t),shouldSample:t.shouldSample.bind(t),shouldUseBeacon:t.shouldUseBeacon.bind(t),printLog:t.printLog.bind(t)}),t.pendingRequestsManager=new p({pendingRequestsMaxSize:50,sendTimeout:3e3,serverUrl:"",contentType:"application/json",showLog:!1,header:void 0},{getLocalStorage:t.getLocalStorage.bind(t),setLocalStorage:t.setLocalStorage.bind(t),shouldSample:t.shouldSample.bind(t),ajax:t.ajax.bind(t),printLog:t.printLog.bind(t)}),t.pageDurationTracker=new a({pageDurationInterval:3e4,showLog:!1},{getCookie:t.getCookie.bind(t),setCookie:t.setCookie.bind(t),getTimeStamp:t.getTimeStamp.bind(t),track:t.trackPageDuration.bind(t),printLog:t.printLog.bind(t)}),t.exposureTracker=new o({autoTrackExposure:!1,exposureThreshold:.5,exposureTime:500,exposureNum:void 0,showLog:!1},{reportExposure:t.handleExposureReport.bind(t),printLog:t.printLog.bind(t),getTimeStamp:t.getTimeStamp.bind(t),extractDataAttributes:t.extractDataAttributes.bind(t)}),t}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function i(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}(r,i),r.prototype.printLog=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.initConfig.showLog&&i.prototype.printLog.apply(this,e)},r.prototype.addSinglePageEvent=function(e){var t=this,n=window.history.pushState?"popstate":"hashchange";this.each(["pushState","replaceState",n],(function(n){t.addEventListener(window,n,e)}))},r}(r))}));
|
package/lib/types/index.d.ts
CHANGED
|
@@ -34,7 +34,7 @@ declare class WebTracking extends Tools {
|
|
|
34
34
|
login: (userInfo: JsonProps) => void;
|
|
35
35
|
getDeviceId: () => string;
|
|
36
36
|
resetDeviceId: () => string;
|
|
37
|
-
track: ({ desc, pageKey, partKey, business, header }: TrackParams) => Promise<TrackingResponse>;
|
|
37
|
+
track: ({ event, desc, pageKey, partKey, business, header }: TrackParams) => Promise<TrackingResponse>;
|
|
38
38
|
protected listener: () => void;
|
|
39
39
|
addSinglePageEvent(callback: (e: EventParams) => void): void;
|
|
40
40
|
protected unlistener: () => void;
|
package/lib/types/type.d.ts
CHANGED
|
@@ -202,6 +202,11 @@ export interface SystemsInfoTypes {
|
|
|
202
202
|
platform?: PlatformType | string;
|
|
203
203
|
}
|
|
204
204
|
export interface TrackParams {
|
|
205
|
+
/**
|
|
206
|
+
* @description 事件类型
|
|
207
|
+
* @default "CustomTrack"
|
|
208
|
+
*/
|
|
209
|
+
event?: EventTypes;
|
|
205
210
|
/**
|
|
206
211
|
* @description 页面唯一标识
|
|
207
212
|
*/
|
|
@@ -209,7 +214,7 @@ export interface TrackParams {
|
|
|
209
214
|
/**
|
|
210
215
|
* @description 控件/自定义事件的唯一标识
|
|
211
216
|
*/
|
|
212
|
-
partKey
|
|
217
|
+
partKey?: string | number;
|
|
213
218
|
/**
|
|
214
219
|
* @description 自定义代码埋点描述
|
|
215
220
|
* @default "自定义代码埋点上报"
|
|
@@ -444,11 +449,7 @@ export interface TrackingResponse {
|
|
|
444
449
|
/**
|
|
445
450
|
* @description 批量发送数据格式
|
|
446
451
|
*/
|
|
447
|
-
export
|
|
448
|
-
events: TrackingPostParams[];
|
|
449
|
-
timestamp?: number;
|
|
450
|
-
deviceId?: string;
|
|
451
|
-
}
|
|
452
|
+
export declare type BatchTrackingData = TrackingPostParams[];
|
|
452
453
|
/**
|
|
453
454
|
* @description 工具类型:将对象的所有属性变为必需
|
|
454
455
|
*/
|