spy-client 2.1.2 → 2.1.3
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/coverage/Chrome 95.0.4638.69 (Mac OS 10.15.7)/html/basicSpec.ts.html +1 -1
- package/coverage/Chrome 95.0.4638.69 (Mac OS 10.15.7)/html/checkSpec.ts.html +1 -1
- package/coverage/Chrome 95.0.4638.69 (Mac OS 10.15.7)/html/headSpec.ts.html +1 -1
- package/coverage/Chrome 95.0.4638.69 (Mac OS 10.15.7)/html/index.html +1 -1
- package/coverage/Chrome 95.0.4638.69 (Mac OS 10.15.7)/html/markSpec.ts.html +1 -1
- package/coverage/Chrome 95.0.4638.69 (Mac OS 10.15.7)/html/metricSpec.ts.html +1 -1
- package/dist/head/base.d.ts +12 -7
- package/dist/lib/interface.d.ts +4 -0
- package/dist/spy-client-basic.d.ts +3 -3
- package/dist/spy-client-basic.esm.js +12 -8
- package/dist/spy-client-basic.iife.js +12 -8
- package/dist/spy-client-basic.iife.min.js +1 -1
- package/dist/spy-client-basic.js +12 -8
- package/dist/spy-client-basic.min.js +1 -1
- package/dist/spy-client-basic.mjs +12 -8
- package/dist/spy-client.d.ts +1 -0
- package/dist/spy-client.esm.js +29 -8
- package/dist/spy-client.iife.js +29 -8
- package/dist/spy-client.iife.min.js +1 -1
- package/dist/spy-client.js +29 -8
- package/dist/spy-client.min.js +1 -1
- package/dist/spy-client.mjs +29 -8
- package/dist/spy-head.js +46 -34
- package/dist/spy-head.min.js +1 -1
- package/dist/spy-local-cache.js +28 -41
- package/dist/spy-local-cache.min.js +1 -1
- package/example/local-cache.html +77 -15
- package/package.json +3 -3
- package/src/head/base.ts +37 -4
- package/src/head/error.ts +9 -19
- package/src/head/whitescreen.ts +14 -14
- package/src/lib/huffman.ts +37 -56
- package/src/lib/interface.ts +5 -0
- package/src/spy-client-basic.ts +20 -15
- package/src/spy-client.ts +19 -1
- package/src/spy-local-cache.ts +12 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
var SpyClient=function(){"use strict";var i=function(t,e){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])})(t,e)};var u=function(){return(u=Object.assign||function(t){for(var e,i=1,o=arguments.length;i<o;i++)for(var n in e=arguments[i])Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}).apply(this,arguments)};function o(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return(Object.assign||function(t){for(var e=void 0,i=1,o=arguments.length;i<o;i++)for(var n in e=arguments[i])Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}).apply(this,t)}function r(t){var e=function(t){if(URL){var e=new URL(t);if(void 0!==e.host)return{protocol:e.protocol,host:e.host,pathname:e.pathname,ext:""}}}(t);if(!e){var i=document.createElement("a");i.href=t,e={protocol:i.protocol,host:i.host||location.host,pathname:i.pathname,ext:""}}var o=e.pathname.split(".");return e.ext=o[o.length-1],e}function f(t){return+t.toFixed(1)}function d(t){if(!t)return{xpath:""};for(var e=[];t&&1===t.nodeType&&t!==t.parentNode;){var i=t.tagName.toLowerCase();if(t.getAttribute("id")?i+="[#"+t.getAttribute("id")+"]":t.classList&&t.classList.length&&(i+="[."+t.classList[t.classList.length-1]+"]"),e.push(i),t===document.body)break;t=t.parentNode}return{xpath:e.join("<")}}var t=navigator.userAgent.toLowerCase().match(/cpu iphone os (.*?)_/),a=t&&t[2]&&+t[2]<14;function l(t){console.error("[SpyClient_log]"+t)}function c(i){return Object.keys(i).map(function(t){var e=i[t];return void 0===e?e="":"string"!=typeof e&&(e=JSON.stringify(e)),encodeURIComponent(t)+"="+encodeURIComponent(e)}).join("&")}function p(t){return"[object Array]"===Object.prototype.toString.call(t)}var e=(n.prototype.fetch=function(t,e){window.fetch&&fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},n.prototype.sendPost=function(t){var e=(p(t)?t:[t])[0],i={pid:e.pid,type:e.type,group:e.group},o=this.option.logServer+c(i);!a&&navigator.sendBeacon&&navigator.sendBeacon(o,JSON.stringify(t))||this.fetch(o,t)},n.prototype.handle=function(t){if(this.check(t)){if("number"==typeof t.sample){if(Math.random()>t.sample)return}else if("number"==typeof this.option.sample&&Math.random()>this.option.sample)return;return delete(t=o({pid:this.option.pid,lid:this.option.lid,ts:Date.now(),group:"common"},t)).sample,t}},n.prototype.send=function(t,e){void 0===e&&(e=!1);for(var i=[],o=0,n=p(t)?t:[t];o<n.length;o++){var r=n[o];if((r=this.handle(r))&&(i.push(r),!e)){var s=this.option.logServer+c(r);!a&&navigator.sendBeacon&&navigator.sendBeacon(s)||((new Image).src=s)}}e&&this.sendPost(i)},n.prototype.check=function(t){if(!this.option.check)return!0;var e=["perf","except","dist","count"];if(-1===e.indexOf(t.type))return l("type only is one of "+e.join(", ")),!1;if(t.group&&30<t.group.length)return l("group length execeeds 30"),!1;var i=/^[a-zA-Z0-9-_]{0,30}$/;if("except"===t.type){if("string"!=typeof t.info.msg||!t.info.msg.length)return l("info.msg field must be not empty and is String"),!1}else for(var o=0,n=Object.keys(t.info);o<n.length;o++){var r=n[o];if(!i.test(r))return l("info."+r+" is unexpected. Length must be not more than 30. Supported chars: a-zA-Z0-9-_"),!1;var s=t.info[r];if("dist"===t.type){if(30<s.length)return l("info."+r+" value length execeeds 30 when type == 'dist'"),!1}else if("number"!=typeof s)return l("info."+r+" value must be number"),!1}if(t.dim)for(var a=0,c=Object.keys(t.dim);a<c.length;a++){var p=c[a];if(!i.test(p))return l("dim key ["+p+"] is unexpected. Length must be not more than 30. Supported chars: a-zA-Z0-9-_"),!1;var h=t.dim[p];if(!/^[a-zA-Z0-9\-_\*\.\s\/#\+@\&\u4e00-\u9fa5]{0,30}$/.test(h))return l("dim."+p+" value ["+h+"] is unexpected. Length must be not more than 30. Supported chars: a-zA-Z0-9-_*. /#+@& and Chinese"),!1}return!0},n.prototype.sendPerf=function(t){this.send(o({type:"perf"},t))},n.prototype.sendExcept=function(t){this.send(o({type:"except"},t))},n.prototype.sendDist=function(t){this.send(o({type:"dist"},t))},n.prototype.sendCount=function(t){this.send(o({type:"count"},t))},n.prototype.sendExceptForError=function(t,e){var i=o({},e);i.info=o({},e.info||{},{msg:t.message,stack:t.stack}),this.sendExcept(i)},n.prototype.startMark=function(t){this.markCache[t]={start:Date.now()}},n.prototype.endMark=function(t){return this.markCache[t]?(this.markCache[t].total=Date.now()-this.markCache[t].start,this.markCache[t].total):0},n.prototype.clearMark=function(t){this.markCache[t]&&delete this.markCache[t]},n.prototype.getAllMark=function(){for(var t={},e=0,i=Object.keys(this.markCache);e<i.length;e++){var o=i[e];t[o]=this.markCache[o].total}return t},n.prototype.clearAllMark=function(){this.markCache={}},n);function n(t){if(this.sample={},this.markCache={},!t.pid)throw new Error("pid is required");this.option={pid:t.pid,lid:t.lid,check:!1!==t.check,sample:t.sample,logServer:t.logServer||"https://sp1.baidu.com/5b1ZeDe5KgQFm2e88IuM_a/mwb2.gif?"}}var s=window.__spyHead,h="first-input",g=(m.prototype.listenFID=function(t){this.cb=t,this.callCB()},m.prototype.callCB=function(){void 0!==this.finalValue&&this.cb&&this.cb({fid:this.finalValue})},m.prototype.destroy=function(){this.observer&&this.observer.disconnect(),this.observer=null},m.prototype.handle=function(t){var e=t.pop();e&&(this.finalValue=e.duration,this.callCB(),this.destroy())},m);function m(){var e=this;if(this.observer=null,window.PerformanceObserver){s&&s.entryMap&&s.entryMap[h]&&this.handle(s.entryMap[h]);try{this.observer=new PerformanceObserver(function(t){e.handle(t.getEntries())}),this.observer.observe({entryTypes:[h]})}catch(t){}}}var v=window.__spyHead,y="layout-shift",b=(k.prototype.listenLayoutShift=function(t){this.cb=t},k.prototype.leave=function(){this.onceLeave||(this.onceLeave=!0,this.observer&&this.observer.takeRecords&&this.observer.takeRecords(),this.finalValue=this.value,this.callCB(),this.destroy())},k.prototype.callCB=function(){void 0!==this.finalValue&&this.cb&&this.cb({layoutShift:this.finalValue})},k.prototype.destroy=function(){this.observer&&this.observer.disconnect(),this.observer=null},k.prototype.handle=function(t){var e=this;t.map(function(t){t.hadRecentInput||(e.value=(e.value||0)+(t.value||0))})},k);function k(){var e=this;if(this.observer=null,this.onceLeave=!1,window.PerformanceObserver){v&&v.entryMap&&v.entryMap[y]&&this.handle(v.entryMap[y]);try{this.observer=new PerformanceObserver(function(t){e.handle(t.getEntries())}),this.observer.observe({entryTypes:[y]})}catch(t){}}}var S={};function L(t){return S[t]}var w=window.__spyHead,T="largest-contentful-paint",C=(O.prototype.listenLCP=function(t){this.cb=t,this.callCB()},O.prototype.callCB=function(){this.finalValue&&this.cb&&this.cb({lcp:this.finalValue})},O.prototype.load=function(){this.observer&&this.observer.takeRecords&&this.observer.takeRecords(),this.finalValue=this.value,function(t,e){S[t]=e}("lcp",this.value),this.callCB(),this.destroy()},O.prototype.destroy=function(){this.observer&&this.observer.disconnect(),this.observer=null},O.prototype.handle=function(t){var e=this;t.map(function(t){e.value=t.renderTime||t.loadTime})},O);function O(){var e=this;if(this.observer=null,window.PerformanceObserver){w&&w.entryMap&&w.entryMap[T]&&this.handle(w.entryMap[T]);try{this.observer=new PerformanceObserver(function(t){e.handle(t.getEntries())}),this.observer.observe({entryTypes:[T]})}catch(t){}}}function B(t){return t.name.indexOf(".gif?")<0}var R=(I.prototype.check=function(){return window.PerformanceObserver&&performance&&performance.timing&&performance.timing.navigationStart},I.prototype.listenTTI=function(t,e){this.check()&&(this.observeLongtask(2e4),this.cb=t,(e=e||{}).interval&&(this.interval=e.interval),e.filterRequest&&(this.filterRequest=e.filterRequest))},I.prototype.load=function(){this.check()&&(this.ttiTimer=setInterval(this.ttiCheck,this.interval))},I.prototype.ttiCheck=function(){if(this.cb){var t=performance.now();if(!(t-this.lastLongTask<this.interval)){var e=this.getNetworkSilenceAt();if(!1!==e&&!(t-e<this.interval)){clearTimeout(this.ttiTimer);var i=this.lastLongTask;i=i||performance.timing.domContentLoadedEventEnd-performance.timing.navigationStart,this.stopObserveLongTask(),this.cb({tti:i})}}}},I.prototype.observerCallback=function(t){var e=t.getEntries(),i=e[e.length-1];this.lastLongTask=i.startTime+i.duration},I.prototype.stopObserveLongTask=function(){this.observer&&(this.observer.disconnect(),this.observer=null),this.stopLongTaskTimeoutId&&clearTimeout(this.stopLongTaskTimeoutId)},I.prototype.getNetworkSilenceAt=function(){for(var t=0,e=0,i=performance.getEntriesByType("resource").filter(this.filterRequest);e<i.length;e++){var o=i[e];if(!o.responseEnd)return!1;o.responseEnd>t&&(t=o.responseEnd)}return t},I.prototype.observeLongtask=function(t){this.stopObserveLongTask();try{this.observer=new PerformanceObserver(this.observerCallback),this.observer.observe({entryTypes:["longtask"]}),this.stopLongTaskTimeoutId=setTimeout(this.stopObserveLongTask,t)}catch(t){}},I);function I(){this.lastLongTask=0,this.observer=null,this.interval=5e3,this.filterRequest=B,this.observerCallback=this.observerCallback.bind(this),this.ttiCheck=this.ttiCheck.bind(this)}var z,E,P,j,M=(x.prototype.listenTiming=function(t){window.performance&&window.performance.timing&&(this.cb=t)},x.prototype.load=function(){var t=this;setTimeout(function(){t.cb&&t.cb(t.getMetric())},500)},x.prototype.getMetric=function(){var r={},t=window.performance.timing,e=t.navigationStart;if(r.dns=t.domainLookupEnd-t.domainLookupStart,r.tcp=t.connectEnd-t.connectStart,r.request=t.responseStart-t.requestStart,r.response=t.responseEnd-t.responseStart,r.parseHtml=t.domInteractive-t.domLoading,r.domReady=t.domContentLoadedEventEnd-e,r.loadEventHandle=t.loadEventEnd-t.loadEventStart,r.load=t.loadEventEnd-e,performance.getEntriesByType){var i=performance.getEntriesByType("paint");i&&i.length&&i.forEach(function(t){var e=t.name,i=t.duration,o=t.startTime,n=Math.ceil(i+o);"first-paint"===e&&(r.fp=n),"first-contentful-paint"===e&&(r.fcp=n)})}return t.domFirstPaint&&(r.t7FirstPaint=t.domFirstPaint-e),t.domFirstScreenPaint&&(r.t7FirstScreen=t.domFirstScreenPaint-e),r},x);function x(){}(E=z=z||{}).JS="js",E.CSS="css",E.IMG="img",E.FONT="font",(j=P=P||{})[j.ttf=0]="ttf",j[j.eot=1]="eot",j[j.woff=2]="woff",j[j.woff2=3]="woff2";var H=["/mwb2.gif"];function N(t,e){for(var i=0,o=e;i<o.length;i++){var n=o[i];if(-1<t.indexOf(n))return!0}return!1}function _(t){return+t.toFixed(1)}var F=(A.prototype.check=function(){return performance&&performance.getEntriesByType},A.prototype.listenResource=function(t,e){void 0===e&&(e={}),this.check()&&(this.resOption=o(this.resOption,e),this.trigger=this.resOption.trigger,this.cb=t)},A.prototype.listenBigImg=function(t,e){void 0===e&&(e={}),this.check()&&(this.bigImgOption=o(this.bigImgOption,e),this.trigger=this.bigImgOption.trigger,this.bigImgCB=t)},A.prototype.listenHttpResource=function(t,e){void 0===e&&(e={}),this.check()&&(this.httpResOption=o(this.httpResOption,e),this.trigger=this.httpResOption.trigger,this.httpResCB=t)},A.prototype.listenSlowResource=function(t,e){void 0===e&&(e={}),this.check()&&(this.slowOption=o(this.slowOption,e),this.trigger=this.slowOption.trigger,this.slowResCB=t)},A.prototype.report=function(){var l=this,t=this.getMetric();if(t){var e=t.metric,i=t.hostMetric;this.cb&&this.cb(e,i)}this.bigImgCB&&"function"==typeof window.requestIdleCallback&&Object.keys(this.bigImgList).length&&window.requestIdleCallback(function(){for(var t=0,e=Object.keys(l.bigImgList);t<e.length;t++)for(var i=e[t],o=0,n=l.bigImgList[i];o<n.length;o++){var r=n[o],s=r.timing,a=r.type;try{var c=document.body.querySelector('img[src="'+s.name+'"]');l.bigImgCB({msg:s.name,dur:s.duration,xpath:d(c).xpath,host:i,type:a})}catch(t){console.error(t)}}}),this.httpResCB&&"function"==typeof window.requestIdleCallback&&Object.keys(this.httpResList).length&&window.requestIdleCallback(function(){for(var t=0,e=Object.keys(l.httpResList);t<e.length;t++)for(var i=e[t],o=0,n=l.httpResList[i];o<n.length;o++){var r=n[o],s=r.timing,a=r.type;try{var c=document.body.querySelector('[src="'+s.name+'"]');l.httpResCB({msg:s.name,dur:s.duration,xpath:d(c).xpath,host:i,type:a})}catch(t){console.error(t)}}}),this.slowResCB&&"function"==typeof window.requestIdleCallback&&Object.keys(this.slowList).length&&window.requestIdleCallback(function(){for(var t=0,e=Object.keys(l.slowList);t<e.length;t++)for(var i=e[t],o=0,n=l.slowList[i];o<n.length;o++){var r=n[o],s=r.timing,a=r.type;try{var c=document.body.querySelector('[src="'+s.name+'"]'),p={wait:f((h=s).domainLookupStart-(h.navigationStart||h.fetchStart||h.startTime)),dns:f(h.domainLookupEnd-h.domainLookupStart),connect:f(h.connectEnd-h.connectStart),req:f(h.responseStart-h.requestStart),res:f(h.responseEnd-h.responseStart)};l.slowResCB(u(u({},p),{dur:s.duration,msg:s.name,xpath:d(c).xpath,host:i,type:a}))}catch(t){console.error(t)}}var h})},A.prototype.load=function(){var t=this;"load"===this.trigger&&this.check()&&setTimeout(function(){t.report()},500)},A.prototype.leave=function(){"leave"===this.trigger&&this.report()},A.prototype.push=function(t,e,i,o){N(o.pathname,this.resOption.ignorePaths||[])||(e.push(i),this.pushWithHost(t,this.hostList,i,o)),N(o.pathname,this.slowOption.ignorePaths||[])||i.duration>this.slowOption.threshold&&this.pushWithHost(t,this.slowList,i,o)},A.prototype.pushWithHost=function(t,e,i,o){var n=o.host;e[n]||(e[n]=[]),e[n].push({timing:i,type:t})},A.prototype.collectHttpResInHttps=function(t,e,i){"https:"!==location.protocol||0!==e.name.indexOf("http://")||N(i.pathname,this.httpResOption.ignorePaths||[])||this.pushWithHost(t,this.httpResList,e,i)},A.prototype.addScript=function(t,e){"js"===e.ext&&0!==t.decodedBodySize&&this.push("js",this.jsList,t,e)},A.prototype.addResFromCss=function(t,e){e.ext&&P.hasOwnProperty(e.ext)?this.push("font",this.fontList,t,e):this.addImg(t,e)},A.prototype.addLink=function(t,e){"css"===e.ext?this.push("css",this.cssList,t,e):"js"===e.ext&&this.push("js",this.jsList,t,e)},A.prototype.addImg=function(t,e){this.push("img",this.imgList,t,e),t.decodedBodySize>(this.bigImgOption.maxSize||0)&&!N(e.pathname,this.bigImgOption.ignorePaths||[])&&this.pushWithHost("img",this.bigImgList,t,e)},A.prototype.handleTimings=function(t){for(var e=t.length,i=0;i<e;i++){var o=t[i],n=r(o.name);if(!N(n.pathname,H))switch(t[i].initiatorType){case"script":this.addScript(o,n);break;case"css":this.addResFromCss(o,n);break;case"img":this.addImg(o,n);break;case"link":this.addLink(o,n);break;case"audio":this.collectHttpResInHttps("audio",o,n);break;case"video":this.collectHttpResInHttps("video",o,n)}}},A.prototype.getNumAndSize=function(t,e){var i={},o=t+"Num",n=t+"Size",r=t+"TransferSize",s=t+"CacheRate",a=t+"Duration";i[o]=0,i[n]=0;var c=i[r]=0;if(e.forEach(function(t){i[o]++,i[n]+=t.decodedBodySize/1024,i[r]+=t.transferSize/1024,c+=t.duration}),i[a]=_(0<i[o]?c/i[o]:0),i[n]){var p=i[n]-i[r];i[s]=_(0<=p?100*p/i[n]:0)}return i[n]=_(i[n]),i[r]=_(i[r]),i},A.prototype.getMetric=function(){var t=performance.getEntriesByType("navigation")[0],e=performance.getEntriesByType("resource");if(t&&e&&e.length){this.handleTimings(e);var i=u(u(u(u({},this.getNumAndSize(z.JS,this.jsList)),this.getNumAndSize(z.CSS,this.cssList)),this.getNumAndSize(z.IMG,this.imgList)),this.getNumAndSize(z.FONT,this.fontList)),o=t;i.docSize=_(o.decodedBodySize/1024),i.docTransferSize=_(o.transferSize/1024),i.headerSize=_((o.transferSize-o.encodedBodySize||0)/1024),i.allSize=_(i.docSize+i.jsSize+i.cssSize+i.imgSize+i.fontSize),i.allTransferSize=_(i.docTransferSize+i.jsTransferSize+i.cssTransferSize+i.imgTransferSize+i.fontTransferSize);for(var n={},r=0,s=Object.keys(this.hostList);r<s.length;r++){var a=s[r],c=this.hostList[a].map(function(t){return t.timing});n[a]=this.getNumAndSize("host",c)}return{metric:i,hostMetric:n}}},A);function A(){this.trigger="load",this.jsList=[],this.cssList=[],this.imgList=[],this.fontList=[],this.hostList={},this.bigImgList={},this.httpResList={},this.slowList={},this.resOption={ignorePaths:[],trigger:"load"},this.bigImgOption={ignorePaths:[],maxSize:153600,trigger:"load"},this.httpResOption={ignorePaths:[],trigger:"load"},this.slowOption={ignorePaths:[],trigger:"load",threshold:1e3}}var q=null;window.performance&&window.performance.memory&&(q=window.performance.memory);var D=(J.prototype.listenMemory=function(t){this.cb=t},J.prototype.leave=function(){if(!this.onceLeave&&q){this.onceLeave=!0;var t=window.performance.memory;if(t.usedJSHeapSize===q.usedJSHeapSize&&t.totalJSHeapSize===q.totalJSHeapSize)return;var e=window.performance.memory;this.cb&&this.cb({usedJSHeapSize:e.usedJSHeapSize/1024,totalJSHeapSize:e.totalJSHeapSize/1024,jsHeapSizeLimit:e.jsHeapSizeLimit/1024,usedJSHeapRate:100*e.usedJSHeapSize/e.totalJSHeapSize})}},J);function J(){this.onceLeave=!1}var V=(Z.prototype.getNavigatorInfo=function(){var t={},e=navigator.connection;return"object"==typeof e&&(t={downlink:e.downlink,effectiveType:e.effectiveType,rtt:e.rtt,saveData:!!e.saveData}),navigator.deviceMemory&&(t.deviceMemory=navigator.deviceMemory),navigator.hardwareConcurrency&&(t.hardwareConcurrency=navigator.deviceMemory),t},Z.prototype.load=function(){},Z);function Z(){}var W,U,G,$=window.__spyHead,K="longtask",Q=(X.prototype.check=function(){return window.PerformanceObserver&&performance&&performance.timing&&performance.timing.navigationStart},X.prototype.listenFSPLongTask=function(t){this.check()&&(this.fspCB=t)},X.prototype.listenLCPLongTask=function(t){this.check()&&(this.lcpCB=t)},X.prototype.listenLoadLongTask=function(t){this.check()&&(this.loadCB=t)},X.prototype.listenPageLongTask=function(t){this.check()&&(this.pageCB=t)},X.prototype.load=function(){var i=this;if(this.check()){var o=this.getStatData(Date.now());setTimeout(function(){if(i.loadCB&&i.loadCB({loadLongtaskTime:o.time,loadTBT:o.tbt,loadTotalTime:o.totalTime,loadLongtaskRate:o.rate,loadLongtaskNum:o.num}),performance.timing&&performance.timing.domFirstScreenPaint){var t=i.getStatData(performance.timing.domFirstScreenPaint);i.fspCB&&i.fspCB({fspLongtaskTime:t.time,fspTBT:t.tbt,fspTotalTime:t.totalTime,fspLongtaskRate:t.rate,fspLongtaskNum:t.num})}if(L("lcp")){var e=i.getStatData(performance.timing.navigationStart+L("lcp"));i.lcpCB&&i.lcpCB({lcpLongtaskTime:e.time,lcpTBT:e.tbt,lcpTotalTime:e.totalTime,lcpLongtaskRate:e.rate,lcpLongtaskNum:e.num})}},200)}},X.prototype.leave=function(){if(!this.onceLeave){this.onceLeave=!0;var t=this.getStatData(Date.now());this.pageCB&&this.pageCB({pageLongtaskTime:t.time,pageTBT:t.tbt,pageTotalTime:t.totalTime,pageLongtaskRate:t.rate,pageLongtaskNum:t.num,pageIframeLongtaskTime:t.iframeTime,pageIframeLongtaskRate:t.iframeRate,pageIframeLongtaskNum:t.iframeNum})}},X.prototype.destroy=function(){this.lts=[],this.observer&&this.observer.disconnect(),this.observer=null},X.prototype.getStatData=function(t){for(var e=performance.timing.navigationStart,i=0,o=0,n=0,r=0,s=0,a={},c=0;c<this.lts.length;c++){var p=this.lts[c],h=p.duration;if(e+p.startTime+h<t&&(i+=h,o+=0<h-50?h-50:0,n++,p.attribution&&p.attribution[0])){var l=p.attribution[0].containerSrc;l&&l!==location.href&&(a[l]||(a[l]=[]),a[l].push(h),r+=h,s++)}}var u=t-e;return{num:n,time:i,tbt:o,totalTime:u,rate:100*i/u,iframeTime:r,iframeNum:s,iframeRate:100*r/u,iframeLongtasks:a}},X);function X(){var e=this;this.lts=[],this.observer=null,this.onceLeave=!1,$&&$.entryMap&&$.entryMap[K]&&(this.lts=this.lts.concat($.entryMap[K]));try{this.observer=new PerformanceObserver(function(t){e.lts=e.lts.concat(t.getEntries())}),this.observer.observe({entryTypes:[K]})}catch(t){}}function Y(){this.constructor=W}function tt(t){var e=G.call(this,t)||this;return e.modules=[],e.register(new g),e.register(new C),e.register(new b),e.register(new R),e.register(new M),e.register(new F),e.register(new D),e.register(new V),e.register(new Q),e.visibilitychangeCB=e.visibilitychangeCB.bind(e),e.load=e.load.bind(e),e.leave=e.leave.bind(e),"complete"===document.readyState?e.load():window.addEventListener("load",e.load),document.addEventListener("visibilitychange",e.visibilitychangeCB),window.addEventListener("beforeunload",e.leave,!1),window.addEventListener("unload",e.leave,!1),e}return i(W=tt,U=G=e),void(W.prototype=null===U?Object.create(U):(Y.prototype=U.prototype,new Y)),tt.prototype.listenFID=function(t){this.invoke("listenFID",t)},tt.prototype.listenLayoutShift=function(t){this.invoke("listenLayoutShift",t)},tt.prototype.listenLCP=function(t){this.invoke("listenLCP",t)},tt.prototype.listenFSPLongTask=function(t){this.invoke("listenFSPLongTask",t)},tt.prototype.listenLCPLongTask=function(t){this.invoke("listenLCPLongTask",t)},tt.prototype.listenLoadLongTask=function(t){this.invoke("listenLoadLongTask",t)},tt.prototype.listenPageLongTask=function(t){this.invoke("listenPageLongTask",t)},tt.prototype.listenMemory=function(t){this.invoke("listenMemory",t)},tt.prototype.getNavigatorInfo=function(){return this.invoke("getNavigatorInfo")},tt.prototype.listenResource=function(t,e){this.invoke("listenResource",t,e)},tt.prototype.listenBigImg=function(t,e){this.invoke("listenBigImg",t,e)},tt.prototype.listenHttpResource=function(t,e){this.invoke("listenHttpResource",t,e)},tt.prototype.listenSlowResource=function(t,e){this.invoke("listenSlowResource",t,e)},tt.prototype.listenTiming=function(t){this.invoke("listenTiming",t)},tt.prototype.listenTTI=function(t,e){this.invoke("listenTTI",t,e)},tt.prototype.invoke=function(t,e,i){for(var o=0;o<this.modules.length;o++){var n=this.modules[o];if("function"==typeof n[t])return n[t].apply(n,[e,i])}console.error("no method",t)},tt.prototype.register=function(t){this.modules.push(t)},tt.prototype.load=function(){for(var t=0;t<this.modules.length;t++){var e=this.modules[t];e.load&&e.load()}},tt.prototype.leave=function(){for(var t=0;t<this.modules.length;t++){var e=this.modules[t];e.leave&&e.leave()}},tt.prototype.destroy=function(){for(var t=0;t<this.modules.length;t++){var e=this.modules[t];e.destroy&&e.destroy()}document.removeEventListener("visibilitychange",this.visibilitychangeCB),window.removeEventListener("load",this.load),window.removeEventListener("beforeunload",this.leave),window.removeEventListener("unload",this.destroy)},tt.prototype.visibilitychangeCB=function(){"hidden"===document.visibilityState&&this.leave()},tt}();
|
|
1
|
+
var SpyClient=function(){"use strict";var i=function(t,e){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])})(t,e)};var u=function(){return(u=Object.assign||function(t){for(var e,i=1,o=arguments.length;i<o;i++)for(var n in e=arguments[i])Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}).apply(this,arguments)};function o(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return(Object.assign||function(t){for(var e=void 0,i=1,o=arguments.length;i<o;i++)for(var n in e=arguments[i])Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}).apply(this,t)}function r(t){var e=function(t){if(URL){var e=new URL(t);if(void 0!==e.host)return{protocol:e.protocol,host:e.host,pathname:e.pathname,ext:""}}}(t);if(!e){var i=document.createElement("a");i.href=t,e={protocol:i.protocol,host:i.host||location.host,pathname:i.pathname,ext:""}}var o=e.pathname.split(".");return e.ext=o[o.length-1],e}function f(t){return+t.toFixed(1)}function d(t){if(!t)return{xpath:""};for(var e=[];t&&1===t.nodeType&&t!==t.parentNode;){var i=t.tagName.toLowerCase();if(t.getAttribute("id")?i+="[#"+t.getAttribute("id")+"]":t.classList&&t.classList.length&&(i+="[."+t.classList[t.classList.length-1]+"]"),e.push(i),t===document.body)break;t=t.parentNode}return{xpath:e.join("<")}}var t=navigator.userAgent.toLowerCase().match(/cpu iphone os (.*?)_/),a=t&&t[2]&&+t[2]<14;function l(t){console.error("[SpyClient_log]"+t)}function c(i){return Object.keys(i).map(function(t){var e=i[t];return void 0===e?e="":"string"!=typeof e&&(e=JSON.stringify(e)),encodeURIComponent(t)+"="+encodeURIComponent(e)}).join("&")}function h(t){return"[object Array]"===Object.prototype.toString.call(t)}var e=(n.prototype.fetch=function(t,e){window.fetch&&fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},n.prototype.sendPost=function(t){var e=(h(t)?t:[t])[0],i={pid:e.pid,type:e.type,group:e.group},o=this.option.logServer+c(i);!a&&navigator.sendBeacon&&navigator.sendBeacon(o,JSON.stringify(t))||this.fetch(o,t)},n.prototype.handle=function(t){if(this.check(t)){if(t=o({pid:this.option.pid,lid:this.option.lid,ts:Date.now(),group:"common"},t),this.option.localCache&&this.option.localCache.addLog(t),"number"==typeof t.sample){if(Math.random()>t.sample)return}else if("number"==typeof this.option.sample&&Math.random()>this.option.sample)return;return delete t.sample,t}},n.prototype.send=function(t,e){void 0===e&&(e=!1);for(var i=[],o=0,n=h(t)?t:[t];o<n.length;o++){var r=n[o];if((r=this.handle(r))&&(i.push(r),!e)){var s=this.option.logServer+c(r);!a&&navigator.sendBeacon&&navigator.sendBeacon(s)||((new Image).src=s)}}e&&this.sendPost(i)},n.prototype.check=function(t){if(!this.option.check)return!0;var e=["perf","except","dist","count"];if(-1===e.indexOf(t.type))return l("type only is one of "+e.join(", ")),!1;if(t.group&&30<t.group.length)return l("group length execeeds 30"),!1;var i=/^[a-zA-Z0-9-_]{0,30}$/;if("except"===t.type){if("string"!=typeof t.info.msg||!t.info.msg.length)return l("info.msg field must be not empty and is String"),!1}else for(var o=0,n=Object.keys(t.info);o<n.length;o++){var r=n[o];if(!i.test(r))return l("info."+r+" is unexpected. Length must be not more than 30. Supported chars: a-zA-Z0-9-_"),!1;var s=t.info[r];if("dist"===t.type){if(30<s.length)return l("info."+r+" value length execeeds 30 when type == 'dist'"),!1}else if("number"!=typeof s)return l("info."+r+" value must be number"),!1}if(t.dim)for(var a=0,c=Object.keys(t.dim);a<c.length;a++){var h=c[a];if(!i.test(h))return l("dim key ["+h+"] is unexpected. Length must be not more than 30. Supported chars: a-zA-Z0-9-_"),!1;var p=t.dim[h];if(!/^[a-zA-Z0-9\-_\*\.\s\/#\+@\&\u4e00-\u9fa5]{0,30}$/.test(p))return l("dim."+h+" value ["+p+"] is unexpected. Length must be not more than 30. Supported chars: a-zA-Z0-9-_*. /#+@& and Chinese"),!1}return!0},n.prototype.sendPerf=function(t){this.send(o({type:"perf"},t))},n.prototype.sendExcept=function(t){this.send(o({type:"except"},t))},n.prototype.sendDist=function(t){this.send(o({type:"dist"},t))},n.prototype.sendCount=function(t){this.send(o({type:"count"},t))},n.prototype.sendExceptForError=function(t,e){var i=o({},e);i.info=o({},e.info||{},{msg:t.message,stack:t.stack}),this.sendExcept(i)},n.prototype.startMark=function(t){this.markCache[t]={start:Date.now()}},n.prototype.endMark=function(t){return this.markCache[t]?(this.markCache[t].total=Date.now()-this.markCache[t].start,this.markCache[t].total):0},n.prototype.clearMark=function(t){this.markCache[t]&&delete this.markCache[t]},n.prototype.getAllMark=function(){for(var t={},e=0,i=Object.keys(this.markCache);e<i.length;e++){var o=i[e];t[o]=this.markCache[o].total}return t},n.prototype.clearAllMark=function(){this.markCache={}},n);function n(t){if(this.sample={},this.markCache={},!t.pid)throw new Error("pid is required");this.option={pid:t.pid,lid:t.lid,check:!1!==t.check,sample:t.sample,localCache:t.localCache,logServer:t.logServer||"https://sp1.baidu.com/5b1ZeDe5KgQFm2e88IuM_a/mwb2.gif?"}}var s=window.__spyHead,p="first-input",g=(m.prototype.listenFID=function(t){this.cb=t,this.callCB()},m.prototype.callCB=function(){void 0!==this.finalValue&&this.cb&&this.cb({fid:this.finalValue})},m.prototype.destroy=function(){this.observer&&this.observer.disconnect(),this.observer=null},m.prototype.handle=function(t){var e=t.pop();e&&(this.finalValue=e.duration,this.callCB(),this.destroy())},m);function m(){var e=this;if(this.observer=null,window.PerformanceObserver){s&&s.entryMap&&s.entryMap[p]&&this.handle(s.entryMap[p]);try{this.observer=new PerformanceObserver(function(t){e.handle(t.getEntries())}),this.observer.observe({entryTypes:[p]})}catch(t){}}}var v=window.__spyHead,y="layout-shift",b=(k.prototype.listenLayoutShift=function(t){this.cb=t},k.prototype.leave=function(){this.onceLeave||(this.onceLeave=!0,this.observer&&this.observer.takeRecords&&this.observer.takeRecords(),this.finalValue=this.value,this.callCB(),this.destroy())},k.prototype.callCB=function(){void 0!==this.finalValue&&this.cb&&this.cb({layoutShift:this.finalValue})},k.prototype.destroy=function(){this.observer&&this.observer.disconnect(),this.observer=null},k.prototype.handle=function(t){var e=this;t.map(function(t){t.hadRecentInput||(e.value=(e.value||0)+(t.value||0))})},k);function k(){var e=this;if(this.observer=null,this.onceLeave=!1,window.PerformanceObserver){v&&v.entryMap&&v.entryMap[y]&&this.handle(v.entryMap[y]);try{this.observer=new PerformanceObserver(function(t){e.handle(t.getEntries())}),this.observer.observe({entryTypes:[y]})}catch(t){}}}var w={};function L(t){return w[t]}var S=window.__spyHead,T="largest-contentful-paint",C=(O.prototype.listenLCP=function(t){this.cb=t,this.callCB()},O.prototype.callCB=function(){this.finalValue&&this.cb&&this.cb({lcp:this.finalValue})},O.prototype.load=function(){this.observer&&this.observer.takeRecords&&this.observer.takeRecords(),this.finalValue=this.value,function(t,e){w[t]=e}("lcp",this.value),this.callCB(),this.destroy()},O.prototype.destroy=function(){this.observer&&this.observer.disconnect(),this.observer=null},O.prototype.handle=function(t){var e=this;t.map(function(t){e.value=t.renderTime||t.loadTime})},O);function O(){var e=this;if(this.observer=null,window.PerformanceObserver){S&&S.entryMap&&S.entryMap[T]&&this.handle(S.entryMap[T]);try{this.observer=new PerformanceObserver(function(t){e.handle(t.getEntries())}),this.observer.observe({entryTypes:[T]})}catch(t){}}}function B(t){return t.name.indexOf(".gif?")<0}var R=(I.prototype.check=function(){return window.PerformanceObserver&&performance&&performance.timing&&performance.timing.navigationStart},I.prototype.listenTTI=function(t,e){this.check()&&(this.observeLongtask(2e4),this.cb=t,(e=e||{}).interval&&(this.interval=e.interval),e.filterRequest&&(this.filterRequest=e.filterRequest))},I.prototype.load=function(){this.check()&&(this.ttiTimer=setInterval(this.ttiCheck,this.interval))},I.prototype.ttiCheck=function(){if(this.cb){var t=performance.now();if(!(t-this.lastLongTask<this.interval)){var e=this.getNetworkSilenceAt();if(!1!==e&&!(t-e<this.interval)){clearTimeout(this.ttiTimer);var i=this.lastLongTask;i=i||performance.timing.domContentLoadedEventEnd-performance.timing.navigationStart,this.stopObserveLongTask(),this.cb({tti:i})}}}},I.prototype.observerCallback=function(t){var e=t.getEntries(),i=e[e.length-1];this.lastLongTask=i.startTime+i.duration},I.prototype.stopObserveLongTask=function(){this.observer&&(this.observer.disconnect(),this.observer=null),this.stopLongTaskTimeoutId&&clearTimeout(this.stopLongTaskTimeoutId)},I.prototype.getNetworkSilenceAt=function(){for(var t=0,e=0,i=performance.getEntriesByType("resource").filter(this.filterRequest);e<i.length;e++){var o=i[e];if(!o.responseEnd)return!1;o.responseEnd>t&&(t=o.responseEnd)}return t},I.prototype.observeLongtask=function(t){this.stopObserveLongTask();try{this.observer=new PerformanceObserver(this.observerCallback),this.observer.observe({entryTypes:["longtask"]}),this.stopLongTaskTimeoutId=setTimeout(this.stopObserveLongTask,t)}catch(t){}},I);function I(){this.lastLongTask=0,this.observer=null,this.interval=5e3,this.filterRequest=B,this.observerCallback=this.observerCallback.bind(this),this.ttiCheck=this.ttiCheck.bind(this)}var z,E,P,j,H=(M.prototype.listenTiming=function(t){window.performance&&window.performance.timing&&(this.cb=t)},M.prototype.load=function(){var t=this;setTimeout(function(){t.cb&&t.cb(t.getMetric())},500)},M.prototype.getMetric=function(){var r={},t=window.performance.timing,e=t.navigationStart;if(r.dns=t.domainLookupEnd-t.domainLookupStart,r.tcp=t.connectEnd-t.connectStart,r.request=t.responseStart-t.requestStart,r.response=t.responseEnd-t.responseStart,r.parseHtml=t.domInteractive-t.domLoading,r.domReady=t.domContentLoadedEventEnd-e,r.loadEventHandle=t.loadEventEnd-t.loadEventStart,r.load=t.loadEventEnd-e,performance.getEntriesByType){var i=performance.getEntriesByType("paint");i&&i.length&&i.forEach(function(t){var e=t.name,i=t.duration,o=t.startTime,n=Math.ceil(i+o);"first-paint"===e&&(r.fp=n),"first-contentful-paint"===e&&(r.fcp=n)})}return t.domFirstPaint&&(r.t7FirstPaint=t.domFirstPaint-e),t.domFirstScreenPaint&&(r.t7FirstScreen=t.domFirstScreenPaint-e),r},M);function M(){}(E=z=z||{}).JS="js",E.CSS="css",E.IMG="img",E.FONT="font",(j=P=P||{})[j.ttf=0]="ttf",j[j.eot=1]="eot",j[j.woff=2]="woff",j[j.woff2=3]="woff2";var x=["/mwb2.gif"];function N(t,e){for(var i=0,o=e;i<o.length;i++){var n=o[i];if(-1<t.indexOf(n))return!0}return!1}function _(t){return+t.toFixed(1)}var F=(A.prototype.check=function(){return performance&&performance.getEntriesByType},A.prototype.listenResource=function(t,e){void 0===e&&(e={}),this.check()&&(this.resOption=o(this.resOption,e),this.trigger=this.resOption.trigger,this.cb=t)},A.prototype.listenBigImg=function(t,e){void 0===e&&(e={}),this.check()&&(this.bigImgOption=o(this.bigImgOption,e),this.trigger=this.bigImgOption.trigger,this.bigImgCB=t)},A.prototype.listenHttpResource=function(t,e){void 0===e&&(e={}),this.check()&&(this.httpResOption=o(this.httpResOption,e),this.trigger=this.httpResOption.trigger,this.httpResCB=t)},A.prototype.listenSlowResource=function(t,e){void 0===e&&(e={}),this.check()&&(this.slowOption=o(this.slowOption,e),this.trigger=this.slowOption.trigger,this.slowResCB=t)},A.prototype.report=function(){var l=this,t=this.getMetric();if(t){var e=t.metric,i=t.hostMetric;this.cb&&this.cb(e,i)}this.bigImgCB&&"function"==typeof window.requestIdleCallback&&Object.keys(this.bigImgList).length&&window.requestIdleCallback(function(){for(var t=0,e=Object.keys(l.bigImgList);t<e.length;t++)for(var i=e[t],o=0,n=l.bigImgList[i];o<n.length;o++){var r=n[o],s=r.timing,a=r.type;try{var c=document.body.querySelector('img[src="'+s.name+'"]');l.bigImgCB({msg:s.name,dur:s.duration,xpath:d(c).xpath,host:i,type:a})}catch(t){console.error(t)}}}),this.httpResCB&&"function"==typeof window.requestIdleCallback&&Object.keys(this.httpResList).length&&window.requestIdleCallback(function(){for(var t=0,e=Object.keys(l.httpResList);t<e.length;t++)for(var i=e[t],o=0,n=l.httpResList[i];o<n.length;o++){var r=n[o],s=r.timing,a=r.type;try{var c=document.body.querySelector('[src="'+s.name+'"]');l.httpResCB({msg:s.name,dur:s.duration,xpath:d(c).xpath,host:i,type:a})}catch(t){console.error(t)}}}),this.slowResCB&&"function"==typeof window.requestIdleCallback&&Object.keys(this.slowList).length&&window.requestIdleCallback(function(){for(var t=0,e=Object.keys(l.slowList);t<e.length;t++)for(var i=e[t],o=0,n=l.slowList[i];o<n.length;o++){var r=n[o],s=r.timing,a=r.type;try{var c=document.body.querySelector('[src="'+s.name+'"]'),h={wait:f((p=s).domainLookupStart-(p.navigationStart||p.fetchStart||p.startTime)),dns:f(p.domainLookupEnd-p.domainLookupStart),connect:f(p.connectEnd-p.connectStart),req:f(p.responseStart-p.requestStart),res:f(p.responseEnd-p.responseStart)};l.slowResCB(u(u({},h),{dur:s.duration,msg:s.name,xpath:d(c).xpath,host:i,type:a}))}catch(t){console.error(t)}}var p})},A.prototype.load=function(){var t=this;"load"===this.trigger&&this.check()&&setTimeout(function(){t.report()},500)},A.prototype.leave=function(){"leave"===this.trigger&&this.report()},A.prototype.push=function(t,e,i,o){N(o.pathname,this.resOption.ignorePaths||[])||(e.push(i),this.pushWithHost(t,this.hostList,i,o)),N(o.pathname,this.slowOption.ignorePaths||[])||i.duration>this.slowOption.threshold&&this.pushWithHost(t,this.slowList,i,o)},A.prototype.pushWithHost=function(t,e,i,o){var n=o.host;e[n]||(e[n]=[]),e[n].push({timing:i,type:t})},A.prototype.collectHttpResInHttps=function(t,e,i){"https:"!==location.protocol||0!==e.name.indexOf("http://")||N(i.pathname,this.httpResOption.ignorePaths||[])||this.pushWithHost(t,this.httpResList,e,i)},A.prototype.addScript=function(t,e){"js"===e.ext&&0!==t.decodedBodySize&&this.push("js",this.jsList,t,e)},A.prototype.addResFromCss=function(t,e){e.ext&&P.hasOwnProperty(e.ext)?this.push("font",this.fontList,t,e):this.addImg(t,e)},A.prototype.addLink=function(t,e){"css"===e.ext?this.push("css",this.cssList,t,e):"js"===e.ext&&this.push("js",this.jsList,t,e)},A.prototype.addImg=function(t,e){this.push("img",this.imgList,t,e),t.decodedBodySize>(this.bigImgOption.maxSize||0)&&!N(e.pathname,this.bigImgOption.ignorePaths||[])&&this.pushWithHost("img",this.bigImgList,t,e)},A.prototype.handleTimings=function(t){for(var e=t.length,i=0;i<e;i++){var o=t[i],n=r(o.name);if(!N(n.pathname,x))switch(t[i].initiatorType){case"script":this.addScript(o,n);break;case"css":this.addResFromCss(o,n);break;case"img":this.addImg(o,n);break;case"link":this.addLink(o,n);break;case"audio":this.collectHttpResInHttps("audio",o,n);break;case"video":this.collectHttpResInHttps("video",o,n)}}},A.prototype.getNumAndSize=function(t,e){var i={},o=t+"Num",n=t+"Size",r=t+"TransferSize",s=t+"CacheRate",a=t+"Duration";i[o]=0,i[n]=0;var c=i[r]=0;if(e.forEach(function(t){i[o]++,i[n]+=t.decodedBodySize/1024,i[r]+=t.transferSize/1024,c+=t.duration}),i[a]=_(0<i[o]?c/i[o]:0),i[n]){var h=i[n]-i[r];i[s]=_(0<=h?100*h/i[n]:0)}return i[n]=_(i[n]),i[r]=_(i[r]),i},A.prototype.getMetric=function(){var t=performance.getEntriesByType("navigation")[0],e=performance.getEntriesByType("resource");if(t&&e&&e.length){this.handleTimings(e);var i=u(u(u(u({},this.getNumAndSize(z.JS,this.jsList)),this.getNumAndSize(z.CSS,this.cssList)),this.getNumAndSize(z.IMG,this.imgList)),this.getNumAndSize(z.FONT,this.fontList)),o=t;i.docSize=_(o.decodedBodySize/1024),i.docTransferSize=_(o.transferSize/1024),i.headerSize=_((o.transferSize-o.encodedBodySize||0)/1024),i.allSize=_(i.docSize+i.jsSize+i.cssSize+i.imgSize+i.fontSize),i.allTransferSize=_(i.docTransferSize+i.jsTransferSize+i.cssTransferSize+i.imgTransferSize+i.fontTransferSize);for(var n={},r=0,s=Object.keys(this.hostList);r<s.length;r++){var a=s[r],c=this.hostList[a].map(function(t){return t.timing});n[a]=this.getNumAndSize("host",c)}return{metric:i,hostMetric:n}}},A);function A(){this.trigger="load",this.jsList=[],this.cssList=[],this.imgList=[],this.fontList=[],this.hostList={},this.bigImgList={},this.httpResList={},this.slowList={},this.resOption={ignorePaths:[],trigger:"load"},this.bigImgOption={ignorePaths:[],maxSize:153600,trigger:"load"},this.httpResOption={ignorePaths:[],trigger:"load"},this.slowOption={ignorePaths:[],trigger:"load",threshold:1e3}}var q=null;window.performance&&window.performance.memory&&(q=window.performance.memory);var D=(J.prototype.listenMemory=function(t){this.cb=t},J.prototype.leave=function(){if(!this.onceLeave&&q){this.onceLeave=!0;var t=window.performance.memory;if(t.usedJSHeapSize===q.usedJSHeapSize&&t.totalJSHeapSize===q.totalJSHeapSize)return;var e=window.performance.memory;this.cb&&this.cb({usedJSHeapSize:e.usedJSHeapSize/1024,totalJSHeapSize:e.totalJSHeapSize/1024,jsHeapSizeLimit:e.jsHeapSizeLimit/1024,usedJSHeapRate:100*e.usedJSHeapSize/e.totalJSHeapSize})}},J);function J(){this.onceLeave=!1}var V=(Z.prototype.getNavigatorInfo=function(){var t={},e=navigator.connection;return"object"==typeof e&&(t={downlink:e.downlink,effectiveType:e.effectiveType,rtt:e.rtt,saveData:!!e.saveData}),navigator.deviceMemory&&(t.deviceMemory=navigator.deviceMemory),navigator.hardwareConcurrency&&(t.hardwareConcurrency=navigator.deviceMemory),t},Z.prototype.load=function(){},Z);function Z(){}var W,U,G,$=window.__spyHead,K="longtask",Q=(X.prototype.check=function(){return window.PerformanceObserver&&performance&&performance.timing&&performance.timing.navigationStart},X.prototype.listenFSPLongTask=function(t){this.check()&&(this.fspCB=t)},X.prototype.listenLCPLongTask=function(t){this.check()&&(this.lcpCB=t)},X.prototype.listenLoadLongTask=function(t){this.check()&&(this.loadCB=t)},X.prototype.listenPageLongTask=function(t){this.check()&&(this.pageCB=t)},X.prototype.load=function(){var i=this;if(this.check()){var o=this.getStatData(Date.now());setTimeout(function(){if(i.loadCB&&i.loadCB({loadLongtaskTime:o.time,loadTBT:o.tbt,loadTotalTime:o.totalTime,loadLongtaskRate:o.rate,loadLongtaskNum:o.num}),performance.timing&&performance.timing.domFirstScreenPaint){var t=i.getStatData(performance.timing.domFirstScreenPaint);i.fspCB&&i.fspCB({fspLongtaskTime:t.time,fspTBT:t.tbt,fspTotalTime:t.totalTime,fspLongtaskRate:t.rate,fspLongtaskNum:t.num})}if(L("lcp")){var e=i.getStatData(performance.timing.navigationStart+L("lcp"));i.lcpCB&&i.lcpCB({lcpLongtaskTime:e.time,lcpTBT:e.tbt,lcpTotalTime:e.totalTime,lcpLongtaskRate:e.rate,lcpLongtaskNum:e.num})}},200)}},X.prototype.leave=function(){if(!this.onceLeave){this.onceLeave=!0;var t=this.getStatData(Date.now());this.pageCB&&this.pageCB({pageLongtaskTime:t.time,pageTBT:t.tbt,pageTotalTime:t.totalTime,pageLongtaskRate:t.rate,pageLongtaskNum:t.num,pageIframeLongtaskTime:t.iframeTime,pageIframeLongtaskRate:t.iframeRate,pageIframeLongtaskNum:t.iframeNum})}},X.prototype.destroy=function(){this.lts=[],this.observer&&this.observer.disconnect(),this.observer=null},X.prototype.getStatData=function(t){for(var e=performance.timing.navigationStart,i=0,o=0,n=0,r=0,s=0,a={},c=0;c<this.lts.length;c++){var h=this.lts[c],p=h.duration;if(e+h.startTime+p<t&&(i+=p,o+=0<p-50?p-50:0,n++,h.attribution&&h.attribution[0])){var l=h.attribution[0].containerSrc;l&&l!==location.href&&(a[l]||(a[l]=[]),a[l].push(p),r+=p,s++)}}var u=t-e;return{num:n,time:i,tbt:o,totalTime:u,rate:100*i/u,iframeTime:r,iframeNum:s,iframeRate:100*r/u,iframeLongtasks:a}},X);function X(){var e=this;this.lts=[],this.observer=null,this.onceLeave=!1,$&&$.entryMap&&$.entryMap[K]&&(this.lts=this.lts.concat($.entryMap[K]));try{this.observer=new PerformanceObserver(function(t){e.lts=e.lts.concat(t.getEntries())}),this.observer.observe({entryTypes:[K]})}catch(t){}}function Y(){this.constructor=W}function tt(t){var e=G.call(this,t)||this;return e.modules=[],e.register(new g),e.register(new C),e.register(new b),e.register(new R),e.register(new H),e.register(new F),e.register(new D),e.register(new V),e.register(new Q),e.visibilitychangeCB=e.visibilitychangeCB.bind(e),e.load=e.load.bind(e),e.leave=e.leave.bind(e),"complete"===document.readyState?e.load():window.addEventListener("load",e.load),document.addEventListener("visibilitychange",e.visibilitychangeCB),window.addEventListener("beforeunload",e.leave,!1),window.addEventListener("unload",e.leave,!1),e.handleHead(),e}return i(W=tt,U=G=e),void(W.prototype=null===U?Object.create(U):(Y.prototype=U.prototype,new Y)),tt.prototype.handleHead=function(){var e=this;if(this.option.localCache){var t=window.__spyHead;if(t&&t.winerrors){for(var i=0;i<t.winerrors.length;i++){var o=t.winerrors[i];this.option.localCache.addLog(o)}t.interceptor=function(t){e.option.localCache.addLog(t)}}}},tt.prototype.listenFID=function(t){this.invoke("listenFID",t)},tt.prototype.listenLayoutShift=function(t){this.invoke("listenLayoutShift",t)},tt.prototype.listenLCP=function(t){this.invoke("listenLCP",t)},tt.prototype.listenFSPLongTask=function(t){this.invoke("listenFSPLongTask",t)},tt.prototype.listenLCPLongTask=function(t){this.invoke("listenLCPLongTask",t)},tt.prototype.listenLoadLongTask=function(t){this.invoke("listenLoadLongTask",t)},tt.prototype.listenPageLongTask=function(t){this.invoke("listenPageLongTask",t)},tt.prototype.listenMemory=function(t){this.invoke("listenMemory",t)},tt.prototype.getNavigatorInfo=function(){return this.invoke("getNavigatorInfo")},tt.prototype.listenResource=function(t,e){this.invoke("listenResource",t,e)},tt.prototype.listenBigImg=function(t,e){this.invoke("listenBigImg",t,e)},tt.prototype.listenHttpResource=function(t,e){this.invoke("listenHttpResource",t,e)},tt.prototype.listenSlowResource=function(t,e){this.invoke("listenSlowResource",t,e)},tt.prototype.listenTiming=function(t){this.invoke("listenTiming",t)},tt.prototype.listenTTI=function(t,e){this.invoke("listenTTI",t,e)},tt.prototype.invoke=function(t,e,i){for(var o=0;o<this.modules.length;o++){var n=this.modules[o];if("function"==typeof n[t])return n[t].apply(n,[e,i])}console.error("no method",t)},tt.prototype.register=function(t){this.modules.push(t)},tt.prototype.load=function(){for(var t=0;t<this.modules.length;t++){var e=this.modules[t];e.load&&e.load()}},tt.prototype.leave=function(){for(var t=0;t<this.modules.length;t++){var e=this.modules[t];e.leave&&e.leave()}},tt.prototype.destroy=function(){for(var t=0;t<this.modules.length;t++){var e=this.modules[t];e.destroy&&e.destroy()}document.removeEventListener("visibilitychange",this.visibilitychangeCB),window.removeEventListener("load",this.load),window.removeEventListener("beforeunload",this.leave),window.removeEventListener("unload",this.destroy)},tt.prototype.visibilitychangeCB=function(){"hidden"===document.visibilityState&&this.leave()},tt}();
|
package/dist/spy-client.js
CHANGED
|
@@ -171,6 +171,7 @@
|
|
|
171
171
|
lid: option.lid,
|
|
172
172
|
check: option.check !== false,
|
|
173
173
|
sample: option.sample,
|
|
174
|
+
localCache: option.localCache,
|
|
174
175
|
logServer: option.logServer || defaultLogServer,
|
|
175
176
|
};
|
|
176
177
|
}
|
|
@@ -182,9 +183,9 @@
|
|
|
182
183
|
method: 'POST',
|
|
183
184
|
credentials: 'include',
|
|
184
185
|
headers: {
|
|
185
|
-
'Content-Type': 'application/json'
|
|
186
|
+
'Content-Type': 'application/json',
|
|
186
187
|
},
|
|
187
|
-
body: JSON.stringify(data)
|
|
188
|
+
body: JSON.stringify(data),
|
|
188
189
|
});
|
|
189
190
|
};
|
|
190
191
|
SpyClient.prototype.sendPost = function (data) {
|
|
@@ -207,6 +208,15 @@
|
|
|
207
208
|
if (!this.check(logItem)) {
|
|
208
209
|
return;
|
|
209
210
|
}
|
|
211
|
+
logItem = assign({
|
|
212
|
+
pid: this.option.pid,
|
|
213
|
+
lid: this.option.lid,
|
|
214
|
+
ts: Date.now(),
|
|
215
|
+
group: 'common',
|
|
216
|
+
}, logItem);
|
|
217
|
+
if (this.option.localCache) {
|
|
218
|
+
this.option.localCache.addLog(logItem);
|
|
219
|
+
}
|
|
210
220
|
// 当前api设置了抽样,
|
|
211
221
|
if (typeof logItem.sample === 'number') {
|
|
212
222
|
if (Math.random() > logItem.sample) {
|
|
@@ -216,12 +226,6 @@
|
|
|
216
226
|
else if (typeof this.option.sample === 'number' && Math.random() > this.option.sample) { // 否则,用全局抽样
|
|
217
227
|
return;
|
|
218
228
|
}
|
|
219
|
-
logItem = assign({
|
|
220
|
-
pid: this.option.pid,
|
|
221
|
-
lid: this.option.lid,
|
|
222
|
-
ts: Date.now(),
|
|
223
|
-
group: 'common',
|
|
224
|
-
}, logItem);
|
|
225
229
|
delete logItem.sample;
|
|
226
230
|
return logItem;
|
|
227
231
|
};
|
|
@@ -1368,8 +1372,25 @@
|
|
|
1368
1372
|
document.addEventListener('visibilitychange', _this.visibilitychangeCB);
|
|
1369
1373
|
window.addEventListener('beforeunload', _this.leave, false);
|
|
1370
1374
|
window.addEventListener('unload', _this.leave, false);
|
|
1375
|
+
_this.handleHead();
|
|
1371
1376
|
return _this;
|
|
1372
1377
|
}
|
|
1378
|
+
SpyClient.prototype.handleHead = function () {
|
|
1379
|
+
var _this = this;
|
|
1380
|
+
if (this.option.localCache) {
|
|
1381
|
+
var spyHead = window.__spyHead;
|
|
1382
|
+
if (spyHead && spyHead.winerrors) {
|
|
1383
|
+
for (var index = 0; index < spyHead.winerrors.length; index++) {
|
|
1384
|
+
var obj = spyHead.winerrors[index];
|
|
1385
|
+
this.option.localCache.addLog(obj);
|
|
1386
|
+
}
|
|
1387
|
+
// Head发送的异常,也保存一份到本地,主要是JS错误和资源加载异常
|
|
1388
|
+
spyHead.interceptor = function (obj) {
|
|
1389
|
+
_this.option.localCache.addLog(obj);
|
|
1390
|
+
};
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
};
|
|
1373
1394
|
SpyClient.prototype.listenFID = function (cb) {
|
|
1374
1395
|
this.invoke('listenFID', cb);
|
|
1375
1396
|
};
|
package/dist/spy-client.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).SpyClient=e()}(this,function(){"use strict";var i=function(t,e){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])})(t,e)};var u=function(){return(u=Object.assign||function(t){for(var e,i=1,o=arguments.length;i<o;i++)for(var n in e=arguments[i])Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}).apply(this,arguments)};function o(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return(Object.assign||function(t){for(var e=void 0,i=1,o=arguments.length;i<o;i++)for(var n in e=arguments[i])Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}).apply(this,t)}function r(t){var e=function(t){if(URL){var e=new URL(t);if(void 0!==e.host)return{protocol:e.protocol,host:e.host,pathname:e.pathname,ext:""}}}(t);if(!e){var i=document.createElement("a");i.href=t,e={protocol:i.protocol,host:i.host||location.host,pathname:i.pathname,ext:""}}var o=e.pathname.split(".");return e.ext=o[o.length-1],e}function f(t){return+t.toFixed(1)}function d(t){if(!t)return{xpath:""};for(var e=[];t&&1===t.nodeType&&t!==t.parentNode;){var i=t.tagName.toLowerCase();if(t.getAttribute("id")?i+="[#"+t.getAttribute("id")+"]":t.classList&&t.classList.length&&(i+="[."+t.classList[t.classList.length-1]+"]"),e.push(i),t===document.body)break;t=t.parentNode}return{xpath:e.join("<")}}var t=navigator.userAgent.toLowerCase().match(/cpu iphone os (.*?)_/),a=t&&t[2]&&+t[2]<14;function l(t){console.error("[SpyClient_log]"+t)}function c(i){return Object.keys(i).map(function(t){var e=i[t];return void 0===e?e="":"string"!=typeof e&&(e=JSON.stringify(e)),encodeURIComponent(t)+"="+encodeURIComponent(e)}).join("&")}function p(t){return"[object Array]"===Object.prototype.toString.call(t)}var e=(n.prototype.fetch=function(t,e){window.fetch&&fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},n.prototype.sendPost=function(t){var e=(p(t)?t:[t])[0],i={pid:e.pid,type:e.type,group:e.group},o=this.option.logServer+c(i);!a&&navigator.sendBeacon&&navigator.sendBeacon(o,JSON.stringify(t))||this.fetch(o,t)},n.prototype.handle=function(t){if(this.check(t)){if("number"==typeof t.sample){if(Math.random()>t.sample)return}else if("number"==typeof this.option.sample&&Math.random()>this.option.sample)return;return delete(t=o({pid:this.option.pid,lid:this.option.lid,ts:Date.now(),group:"common"},t)).sample,t}},n.prototype.send=function(t,e){void 0===e&&(e=!1);for(var i=[],o=0,n=p(t)?t:[t];o<n.length;o++){var r=n[o];if((r=this.handle(r))&&(i.push(r),!e)){var s=this.option.logServer+c(r);!a&&navigator.sendBeacon&&navigator.sendBeacon(s)||((new Image).src=s)}}e&&this.sendPost(i)},n.prototype.check=function(t){if(!this.option.check)return!0;var e=["perf","except","dist","count"];if(-1===e.indexOf(t.type))return l("type only is one of "+e.join(", ")),!1;if(t.group&&30<t.group.length)return l("group length execeeds 30"),!1;var i=/^[a-zA-Z0-9-_]{0,30}$/;if("except"===t.type){if("string"!=typeof t.info.msg||!t.info.msg.length)return l("info.msg field must be not empty and is String"),!1}else for(var o=0,n=Object.keys(t.info);o<n.length;o++){var r=n[o];if(!i.test(r))return l("info."+r+" is unexpected. Length must be not more than 30. Supported chars: a-zA-Z0-9-_"),!1;var s=t.info[r];if("dist"===t.type){if(30<s.length)return l("info."+r+" value length execeeds 30 when type == 'dist'"),!1}else if("number"!=typeof s)return l("info."+r+" value must be number"),!1}if(t.dim)for(var a=0,c=Object.keys(t.dim);a<c.length;a++){var p=c[a];if(!i.test(p))return l("dim key ["+p+"] is unexpected. Length must be not more than 30. Supported chars: a-zA-Z0-9-_"),!1;var h=t.dim[p];if(!/^[a-zA-Z0-9\-_\*\.\s\/#\+@\&\u4e00-\u9fa5]{0,30}$/.test(h))return l("dim."+p+" value ["+h+"] is unexpected. Length must be not more than 30. Supported chars: a-zA-Z0-9-_*. /#+@& and Chinese"),!1}return!0},n.prototype.sendPerf=function(t){this.send(o({type:"perf"},t))},n.prototype.sendExcept=function(t){this.send(o({type:"except"},t))},n.prototype.sendDist=function(t){this.send(o({type:"dist"},t))},n.prototype.sendCount=function(t){this.send(o({type:"count"},t))},n.prototype.sendExceptForError=function(t,e){var i=o({},e);i.info=o({},e.info||{},{msg:t.message,stack:t.stack}),this.sendExcept(i)},n.prototype.startMark=function(t){this.markCache[t]={start:Date.now()}},n.prototype.endMark=function(t){return this.markCache[t]?(this.markCache[t].total=Date.now()-this.markCache[t].start,this.markCache[t].total):0},n.prototype.clearMark=function(t){this.markCache[t]&&delete this.markCache[t]},n.prototype.getAllMark=function(){for(var t={},e=0,i=Object.keys(this.markCache);e<i.length;e++){var o=i[e];t[o]=this.markCache[o].total}return t},n.prototype.clearAllMark=function(){this.markCache={}},n);function n(t){if(this.sample={},this.markCache={},!t.pid)throw new Error("pid is required");this.option={pid:t.pid,lid:t.lid,check:!1!==t.check,sample:t.sample,logServer:t.logServer||"https://sp1.baidu.com/5b1ZeDe5KgQFm2e88IuM_a/mwb2.gif?"}}var s=window.__spyHead,h="first-input",g=(m.prototype.listenFID=function(t){this.cb=t,this.callCB()},m.prototype.callCB=function(){void 0!==this.finalValue&&this.cb&&this.cb({fid:this.finalValue})},m.prototype.destroy=function(){this.observer&&this.observer.disconnect(),this.observer=null},m.prototype.handle=function(t){var e=t.pop();e&&(this.finalValue=e.duration,this.callCB(),this.destroy())},m);function m(){var e=this;if(this.observer=null,window.PerformanceObserver){s&&s.entryMap&&s.entryMap[h]&&this.handle(s.entryMap[h]);try{this.observer=new PerformanceObserver(function(t){e.handle(t.getEntries())}),this.observer.observe({entryTypes:[h]})}catch(t){}}}var v=window.__spyHead,y="layout-shift",b=(k.prototype.listenLayoutShift=function(t){this.cb=t},k.prototype.leave=function(){this.onceLeave||(this.onceLeave=!0,this.observer&&this.observer.takeRecords&&this.observer.takeRecords(),this.finalValue=this.value,this.callCB(),this.destroy())},k.prototype.callCB=function(){void 0!==this.finalValue&&this.cb&&this.cb({layoutShift:this.finalValue})},k.prototype.destroy=function(){this.observer&&this.observer.disconnect(),this.observer=null},k.prototype.handle=function(t){var e=this;t.map(function(t){t.hadRecentInput||(e.value=(e.value||0)+(t.value||0))})},k);function k(){var e=this;if(this.observer=null,this.onceLeave=!1,window.PerformanceObserver){v&&v.entryMap&&v.entryMap[y]&&this.handle(v.entryMap[y]);try{this.observer=new PerformanceObserver(function(t){e.handle(t.getEntries())}),this.observer.observe({entryTypes:[y]})}catch(t){}}}var S={};function L(t){return S[t]}var w=window.__spyHead,T="largest-contentful-paint",C=(O.prototype.listenLCP=function(t){this.cb=t,this.callCB()},O.prototype.callCB=function(){this.finalValue&&this.cb&&this.cb({lcp:this.finalValue})},O.prototype.load=function(){this.observer&&this.observer.takeRecords&&this.observer.takeRecords(),this.finalValue=this.value,function(t,e){S[t]=e}("lcp",this.value),this.callCB(),this.destroy()},O.prototype.destroy=function(){this.observer&&this.observer.disconnect(),this.observer=null},O.prototype.handle=function(t){var e=this;t.map(function(t){e.value=t.renderTime||t.loadTime})},O);function O(){var e=this;if(this.observer=null,window.PerformanceObserver){w&&w.entryMap&&w.entryMap[T]&&this.handle(w.entryMap[T]);try{this.observer=new PerformanceObserver(function(t){e.handle(t.getEntries())}),this.observer.observe({entryTypes:[T]})}catch(t){}}}function B(t){return t.name.indexOf(".gif?")<0}var R=(I.prototype.check=function(){return window.PerformanceObserver&&performance&&performance.timing&&performance.timing.navigationStart},I.prototype.listenTTI=function(t,e){this.check()&&(this.observeLongtask(2e4),this.cb=t,(e=e||{}).interval&&(this.interval=e.interval),e.filterRequest&&(this.filterRequest=e.filterRequest))},I.prototype.load=function(){this.check()&&(this.ttiTimer=setInterval(this.ttiCheck,this.interval))},I.prototype.ttiCheck=function(){if(this.cb){var t=performance.now();if(!(t-this.lastLongTask<this.interval)){var e=this.getNetworkSilenceAt();if(!1!==e&&!(t-e<this.interval)){clearTimeout(this.ttiTimer);var i=this.lastLongTask;i=i||performance.timing.domContentLoadedEventEnd-performance.timing.navigationStart,this.stopObserveLongTask(),this.cb({tti:i})}}}},I.prototype.observerCallback=function(t){var e=t.getEntries(),i=e[e.length-1];this.lastLongTask=i.startTime+i.duration},I.prototype.stopObserveLongTask=function(){this.observer&&(this.observer.disconnect(),this.observer=null),this.stopLongTaskTimeoutId&&clearTimeout(this.stopLongTaskTimeoutId)},I.prototype.getNetworkSilenceAt=function(){for(var t=0,e=0,i=performance.getEntriesByType("resource").filter(this.filterRequest);e<i.length;e++){var o=i[e];if(!o.responseEnd)return!1;o.responseEnd>t&&(t=o.responseEnd)}return t},I.prototype.observeLongtask=function(t){this.stopObserveLongTask();try{this.observer=new PerformanceObserver(this.observerCallback),this.observer.observe({entryTypes:["longtask"]}),this.stopLongTaskTimeoutId=setTimeout(this.stopObserveLongTask,t)}catch(t){}},I);function I(){this.lastLongTask=0,this.observer=null,this.interval=5e3,this.filterRequest=B,this.observerCallback=this.observerCallback.bind(this),this.ttiCheck=this.ttiCheck.bind(this)}var z,E,P,j,x=(M.prototype.listenTiming=function(t){window.performance&&window.performance.timing&&(this.cb=t)},M.prototype.load=function(){var t=this;setTimeout(function(){t.cb&&t.cb(t.getMetric())},500)},M.prototype.getMetric=function(){var r={},t=window.performance.timing,e=t.navigationStart;if(r.dns=t.domainLookupEnd-t.domainLookupStart,r.tcp=t.connectEnd-t.connectStart,r.request=t.responseStart-t.requestStart,r.response=t.responseEnd-t.responseStart,r.parseHtml=t.domInteractive-t.domLoading,r.domReady=t.domContentLoadedEventEnd-e,r.loadEventHandle=t.loadEventEnd-t.loadEventStart,r.load=t.loadEventEnd-e,performance.getEntriesByType){var i=performance.getEntriesByType("paint");i&&i.length&&i.forEach(function(t){var e=t.name,i=t.duration,o=t.startTime,n=Math.ceil(i+o);"first-paint"===e&&(r.fp=n),"first-contentful-paint"===e&&(r.fcp=n)})}return t.domFirstPaint&&(r.t7FirstPaint=t.domFirstPaint-e),t.domFirstScreenPaint&&(r.t7FirstScreen=t.domFirstScreenPaint-e),r},M);function M(){}(E=z=z||{}).JS="js",E.CSS="css",E.IMG="img",E.FONT="font",(j=P=P||{})[j.ttf=0]="ttf",j[j.eot=1]="eot",j[j.woff=2]="woff",j[j.woff2=3]="woff2";var H=["/mwb2.gif"];function N(t,e){for(var i=0,o=e;i<o.length;i++){var n=o[i];if(-1<t.indexOf(n))return!0}return!1}function _(t){return+t.toFixed(1)}var F=(A.prototype.check=function(){return performance&&performance.getEntriesByType},A.prototype.listenResource=function(t,e){void 0===e&&(e={}),this.check()&&(this.resOption=o(this.resOption,e),this.trigger=this.resOption.trigger,this.cb=t)},A.prototype.listenBigImg=function(t,e){void 0===e&&(e={}),this.check()&&(this.bigImgOption=o(this.bigImgOption,e),this.trigger=this.bigImgOption.trigger,this.bigImgCB=t)},A.prototype.listenHttpResource=function(t,e){void 0===e&&(e={}),this.check()&&(this.httpResOption=o(this.httpResOption,e),this.trigger=this.httpResOption.trigger,this.httpResCB=t)},A.prototype.listenSlowResource=function(t,e){void 0===e&&(e={}),this.check()&&(this.slowOption=o(this.slowOption,e),this.trigger=this.slowOption.trigger,this.slowResCB=t)},A.prototype.report=function(){var l=this,t=this.getMetric();if(t){var e=t.metric,i=t.hostMetric;this.cb&&this.cb(e,i)}this.bigImgCB&&"function"==typeof window.requestIdleCallback&&Object.keys(this.bigImgList).length&&window.requestIdleCallback(function(){for(var t=0,e=Object.keys(l.bigImgList);t<e.length;t++)for(var i=e[t],o=0,n=l.bigImgList[i];o<n.length;o++){var r=n[o],s=r.timing,a=r.type;try{var c=document.body.querySelector('img[src="'+s.name+'"]');l.bigImgCB({msg:s.name,dur:s.duration,xpath:d(c).xpath,host:i,type:a})}catch(t){console.error(t)}}}),this.httpResCB&&"function"==typeof window.requestIdleCallback&&Object.keys(this.httpResList).length&&window.requestIdleCallback(function(){for(var t=0,e=Object.keys(l.httpResList);t<e.length;t++)for(var i=e[t],o=0,n=l.httpResList[i];o<n.length;o++){var r=n[o],s=r.timing,a=r.type;try{var c=document.body.querySelector('[src="'+s.name+'"]');l.httpResCB({msg:s.name,dur:s.duration,xpath:d(c).xpath,host:i,type:a})}catch(t){console.error(t)}}}),this.slowResCB&&"function"==typeof window.requestIdleCallback&&Object.keys(this.slowList).length&&window.requestIdleCallback(function(){for(var t=0,e=Object.keys(l.slowList);t<e.length;t++)for(var i=e[t],o=0,n=l.slowList[i];o<n.length;o++){var r=n[o],s=r.timing,a=r.type;try{var c=document.body.querySelector('[src="'+s.name+'"]'),p={wait:f((h=s).domainLookupStart-(h.navigationStart||h.fetchStart||h.startTime)),dns:f(h.domainLookupEnd-h.domainLookupStart),connect:f(h.connectEnd-h.connectStart),req:f(h.responseStart-h.requestStart),res:f(h.responseEnd-h.responseStart)};l.slowResCB(u(u({},p),{dur:s.duration,msg:s.name,xpath:d(c).xpath,host:i,type:a}))}catch(t){console.error(t)}}var h})},A.prototype.load=function(){var t=this;"load"===this.trigger&&this.check()&&setTimeout(function(){t.report()},500)},A.prototype.leave=function(){"leave"===this.trigger&&this.report()},A.prototype.push=function(t,e,i,o){N(o.pathname,this.resOption.ignorePaths||[])||(e.push(i),this.pushWithHost(t,this.hostList,i,o)),N(o.pathname,this.slowOption.ignorePaths||[])||i.duration>this.slowOption.threshold&&this.pushWithHost(t,this.slowList,i,o)},A.prototype.pushWithHost=function(t,e,i,o){var n=o.host;e[n]||(e[n]=[]),e[n].push({timing:i,type:t})},A.prototype.collectHttpResInHttps=function(t,e,i){"https:"!==location.protocol||0!==e.name.indexOf("http://")||N(i.pathname,this.httpResOption.ignorePaths||[])||this.pushWithHost(t,this.httpResList,e,i)},A.prototype.addScript=function(t,e){"js"===e.ext&&0!==t.decodedBodySize&&this.push("js",this.jsList,t,e)},A.prototype.addResFromCss=function(t,e){e.ext&&P.hasOwnProperty(e.ext)?this.push("font",this.fontList,t,e):this.addImg(t,e)},A.prototype.addLink=function(t,e){"css"===e.ext?this.push("css",this.cssList,t,e):"js"===e.ext&&this.push("js",this.jsList,t,e)},A.prototype.addImg=function(t,e){this.push("img",this.imgList,t,e),t.decodedBodySize>(this.bigImgOption.maxSize||0)&&!N(e.pathname,this.bigImgOption.ignorePaths||[])&&this.pushWithHost("img",this.bigImgList,t,e)},A.prototype.handleTimings=function(t){for(var e=t.length,i=0;i<e;i++){var o=t[i],n=r(o.name);if(!N(n.pathname,H))switch(t[i].initiatorType){case"script":this.addScript(o,n);break;case"css":this.addResFromCss(o,n);break;case"img":this.addImg(o,n);break;case"link":this.addLink(o,n);break;case"audio":this.collectHttpResInHttps("audio",o,n);break;case"video":this.collectHttpResInHttps("video",o,n)}}},A.prototype.getNumAndSize=function(t,e){var i={},o=t+"Num",n=t+"Size",r=t+"TransferSize",s=t+"CacheRate",a=t+"Duration";i[o]=0,i[n]=0;var c=i[r]=0;if(e.forEach(function(t){i[o]++,i[n]+=t.decodedBodySize/1024,i[r]+=t.transferSize/1024,c+=t.duration}),i[a]=_(0<i[o]?c/i[o]:0),i[n]){var p=i[n]-i[r];i[s]=_(0<=p?100*p/i[n]:0)}return i[n]=_(i[n]),i[r]=_(i[r]),i},A.prototype.getMetric=function(){var t=performance.getEntriesByType("navigation")[0],e=performance.getEntriesByType("resource");if(t&&e&&e.length){this.handleTimings(e);var i=u(u(u(u({},this.getNumAndSize(z.JS,this.jsList)),this.getNumAndSize(z.CSS,this.cssList)),this.getNumAndSize(z.IMG,this.imgList)),this.getNumAndSize(z.FONT,this.fontList)),o=t;i.docSize=_(o.decodedBodySize/1024),i.docTransferSize=_(o.transferSize/1024),i.headerSize=_((o.transferSize-o.encodedBodySize||0)/1024),i.allSize=_(i.docSize+i.jsSize+i.cssSize+i.imgSize+i.fontSize),i.allTransferSize=_(i.docTransferSize+i.jsTransferSize+i.cssTransferSize+i.imgTransferSize+i.fontTransferSize);for(var n={},r=0,s=Object.keys(this.hostList);r<s.length;r++){var a=s[r],c=this.hostList[a].map(function(t){return t.timing});n[a]=this.getNumAndSize("host",c)}return{metric:i,hostMetric:n}}},A);function A(){this.trigger="load",this.jsList=[],this.cssList=[],this.imgList=[],this.fontList=[],this.hostList={},this.bigImgList={},this.httpResList={},this.slowList={},this.resOption={ignorePaths:[],trigger:"load"},this.bigImgOption={ignorePaths:[],maxSize:153600,trigger:"load"},this.httpResOption={ignorePaths:[],trigger:"load"},this.slowOption={ignorePaths:[],trigger:"load",threshold:1e3}}var q=null;window.performance&&window.performance.memory&&(q=window.performance.memory);var D=(J.prototype.listenMemory=function(t){this.cb=t},J.prototype.leave=function(){if(!this.onceLeave&&q){this.onceLeave=!0;var t=window.performance.memory;if(t.usedJSHeapSize===q.usedJSHeapSize&&t.totalJSHeapSize===q.totalJSHeapSize)return;var e=window.performance.memory;this.cb&&this.cb({usedJSHeapSize:e.usedJSHeapSize/1024,totalJSHeapSize:e.totalJSHeapSize/1024,jsHeapSizeLimit:e.jsHeapSizeLimit/1024,usedJSHeapRate:100*e.usedJSHeapSize/e.totalJSHeapSize})}},J);function J(){this.onceLeave=!1}var V=(Z.prototype.getNavigatorInfo=function(){var t={},e=navigator.connection;return"object"==typeof e&&(t={downlink:e.downlink,effectiveType:e.effectiveType,rtt:e.rtt,saveData:!!e.saveData}),navigator.deviceMemory&&(t.deviceMemory=navigator.deviceMemory),navigator.hardwareConcurrency&&(t.hardwareConcurrency=navigator.deviceMemory),t},Z.prototype.load=function(){},Z);function Z(){}var W,U,G,$=window.__spyHead,K="longtask",Q=(X.prototype.check=function(){return window.PerformanceObserver&&performance&&performance.timing&&performance.timing.navigationStart},X.prototype.listenFSPLongTask=function(t){this.check()&&(this.fspCB=t)},X.prototype.listenLCPLongTask=function(t){this.check()&&(this.lcpCB=t)},X.prototype.listenLoadLongTask=function(t){this.check()&&(this.loadCB=t)},X.prototype.listenPageLongTask=function(t){this.check()&&(this.pageCB=t)},X.prototype.load=function(){var i=this;if(this.check()){var o=this.getStatData(Date.now());setTimeout(function(){if(i.loadCB&&i.loadCB({loadLongtaskTime:o.time,loadTBT:o.tbt,loadTotalTime:o.totalTime,loadLongtaskRate:o.rate,loadLongtaskNum:o.num}),performance.timing&&performance.timing.domFirstScreenPaint){var t=i.getStatData(performance.timing.domFirstScreenPaint);i.fspCB&&i.fspCB({fspLongtaskTime:t.time,fspTBT:t.tbt,fspTotalTime:t.totalTime,fspLongtaskRate:t.rate,fspLongtaskNum:t.num})}if(L("lcp")){var e=i.getStatData(performance.timing.navigationStart+L("lcp"));i.lcpCB&&i.lcpCB({lcpLongtaskTime:e.time,lcpTBT:e.tbt,lcpTotalTime:e.totalTime,lcpLongtaskRate:e.rate,lcpLongtaskNum:e.num})}},200)}},X.prototype.leave=function(){if(!this.onceLeave){this.onceLeave=!0;var t=this.getStatData(Date.now());this.pageCB&&this.pageCB({pageLongtaskTime:t.time,pageTBT:t.tbt,pageTotalTime:t.totalTime,pageLongtaskRate:t.rate,pageLongtaskNum:t.num,pageIframeLongtaskTime:t.iframeTime,pageIframeLongtaskRate:t.iframeRate,pageIframeLongtaskNum:t.iframeNum})}},X.prototype.destroy=function(){this.lts=[],this.observer&&this.observer.disconnect(),this.observer=null},X.prototype.getStatData=function(t){for(var e=performance.timing.navigationStart,i=0,o=0,n=0,r=0,s=0,a={},c=0;c<this.lts.length;c++){var p=this.lts[c],h=p.duration;if(e+p.startTime+h<t&&(i+=h,o+=0<h-50?h-50:0,n++,p.attribution&&p.attribution[0])){var l=p.attribution[0].containerSrc;l&&l!==location.href&&(a[l]||(a[l]=[]),a[l].push(h),r+=h,s++)}}var u=t-e;return{num:n,time:i,tbt:o,totalTime:u,rate:100*i/u,iframeTime:r,iframeNum:s,iframeRate:100*r/u,iframeLongtasks:a}},X);function X(){var e=this;this.lts=[],this.observer=null,this.onceLeave=!1,$&&$.entryMap&&$.entryMap[K]&&(this.lts=this.lts.concat($.entryMap[K]));try{this.observer=new PerformanceObserver(function(t){e.lts=e.lts.concat(t.getEntries())}),this.observer.observe({entryTypes:[K]})}catch(t){}}function Y(){this.constructor=W}function tt(t){var e=G.call(this,t)||this;return e.modules=[],e.register(new g),e.register(new C),e.register(new b),e.register(new R),e.register(new x),e.register(new F),e.register(new D),e.register(new V),e.register(new Q),e.visibilitychangeCB=e.visibilitychangeCB.bind(e),e.load=e.load.bind(e),e.leave=e.leave.bind(e),"complete"===document.readyState?e.load():window.addEventListener("load",e.load),document.addEventListener("visibilitychange",e.visibilitychangeCB),window.addEventListener("beforeunload",e.leave,!1),window.addEventListener("unload",e.leave,!1),e}return i(W=tt,U=G=e),void(W.prototype=null===U?Object.create(U):(Y.prototype=U.prototype,new Y)),tt.prototype.listenFID=function(t){this.invoke("listenFID",t)},tt.prototype.listenLayoutShift=function(t){this.invoke("listenLayoutShift",t)},tt.prototype.listenLCP=function(t){this.invoke("listenLCP",t)},tt.prototype.listenFSPLongTask=function(t){this.invoke("listenFSPLongTask",t)},tt.prototype.listenLCPLongTask=function(t){this.invoke("listenLCPLongTask",t)},tt.prototype.listenLoadLongTask=function(t){this.invoke("listenLoadLongTask",t)},tt.prototype.listenPageLongTask=function(t){this.invoke("listenPageLongTask",t)},tt.prototype.listenMemory=function(t){this.invoke("listenMemory",t)},tt.prototype.getNavigatorInfo=function(){return this.invoke("getNavigatorInfo")},tt.prototype.listenResource=function(t,e){this.invoke("listenResource",t,e)},tt.prototype.listenBigImg=function(t,e){this.invoke("listenBigImg",t,e)},tt.prototype.listenHttpResource=function(t,e){this.invoke("listenHttpResource",t,e)},tt.prototype.listenSlowResource=function(t,e){this.invoke("listenSlowResource",t,e)},tt.prototype.listenTiming=function(t){this.invoke("listenTiming",t)},tt.prototype.listenTTI=function(t,e){this.invoke("listenTTI",t,e)},tt.prototype.invoke=function(t,e,i){for(var o=0;o<this.modules.length;o++){var n=this.modules[o];if("function"==typeof n[t])return n[t].apply(n,[e,i])}console.error("no method",t)},tt.prototype.register=function(t){this.modules.push(t)},tt.prototype.load=function(){for(var t=0;t<this.modules.length;t++){var e=this.modules[t];e.load&&e.load()}},tt.prototype.leave=function(){for(var t=0;t<this.modules.length;t++){var e=this.modules[t];e.leave&&e.leave()}},tt.prototype.destroy=function(){for(var t=0;t<this.modules.length;t++){var e=this.modules[t];e.destroy&&e.destroy()}document.removeEventListener("visibilitychange",this.visibilitychangeCB),window.removeEventListener("load",this.load),window.removeEventListener("beforeunload",this.leave),window.removeEventListener("unload",this.destroy)},tt.prototype.visibilitychangeCB=function(){"hidden"===document.visibilityState&&this.leave()},tt});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).SpyClient=e()}(this,function(){"use strict";var i=function(t,e){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])})(t,e)};var u=function(){return(u=Object.assign||function(t){for(var e,i=1,o=arguments.length;i<o;i++)for(var n in e=arguments[i])Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}).apply(this,arguments)};function o(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return(Object.assign||function(t){for(var e=void 0,i=1,o=arguments.length;i<o;i++)for(var n in e=arguments[i])Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}).apply(this,t)}function r(t){var e=function(t){if(URL){var e=new URL(t);if(void 0!==e.host)return{protocol:e.protocol,host:e.host,pathname:e.pathname,ext:""}}}(t);if(!e){var i=document.createElement("a");i.href=t,e={protocol:i.protocol,host:i.host||location.host,pathname:i.pathname,ext:""}}var o=e.pathname.split(".");return e.ext=o[o.length-1],e}function f(t){return+t.toFixed(1)}function d(t){if(!t)return{xpath:""};for(var e=[];t&&1===t.nodeType&&t!==t.parentNode;){var i=t.tagName.toLowerCase();if(t.getAttribute("id")?i+="[#"+t.getAttribute("id")+"]":t.classList&&t.classList.length&&(i+="[."+t.classList[t.classList.length-1]+"]"),e.push(i),t===document.body)break;t=t.parentNode}return{xpath:e.join("<")}}var t=navigator.userAgent.toLowerCase().match(/cpu iphone os (.*?)_/),a=t&&t[2]&&+t[2]<14;function l(t){console.error("[SpyClient_log]"+t)}function c(i){return Object.keys(i).map(function(t){var e=i[t];return void 0===e?e="":"string"!=typeof e&&(e=JSON.stringify(e)),encodeURIComponent(t)+"="+encodeURIComponent(e)}).join("&")}function p(t){return"[object Array]"===Object.prototype.toString.call(t)}var e=(n.prototype.fetch=function(t,e){window.fetch&&fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},n.prototype.sendPost=function(t){var e=(p(t)?t:[t])[0],i={pid:e.pid,type:e.type,group:e.group},o=this.option.logServer+c(i);!a&&navigator.sendBeacon&&navigator.sendBeacon(o,JSON.stringify(t))||this.fetch(o,t)},n.prototype.handle=function(t){if(this.check(t)){if(t=o({pid:this.option.pid,lid:this.option.lid,ts:Date.now(),group:"common"},t),this.option.localCache&&this.option.localCache.addLog(t),"number"==typeof t.sample){if(Math.random()>t.sample)return}else if("number"==typeof this.option.sample&&Math.random()>this.option.sample)return;return delete t.sample,t}},n.prototype.send=function(t,e){void 0===e&&(e=!1);for(var i=[],o=0,n=p(t)?t:[t];o<n.length;o++){var r=n[o];if((r=this.handle(r))&&(i.push(r),!e)){var s=this.option.logServer+c(r);!a&&navigator.sendBeacon&&navigator.sendBeacon(s)||((new Image).src=s)}}e&&this.sendPost(i)},n.prototype.check=function(t){if(!this.option.check)return!0;var e=["perf","except","dist","count"];if(-1===e.indexOf(t.type))return l("type only is one of "+e.join(", ")),!1;if(t.group&&30<t.group.length)return l("group length execeeds 30"),!1;var i=/^[a-zA-Z0-9-_]{0,30}$/;if("except"===t.type){if("string"!=typeof t.info.msg||!t.info.msg.length)return l("info.msg field must be not empty and is String"),!1}else for(var o=0,n=Object.keys(t.info);o<n.length;o++){var r=n[o];if(!i.test(r))return l("info."+r+" is unexpected. Length must be not more than 30. Supported chars: a-zA-Z0-9-_"),!1;var s=t.info[r];if("dist"===t.type){if(30<s.length)return l("info."+r+" value length execeeds 30 when type == 'dist'"),!1}else if("number"!=typeof s)return l("info."+r+" value must be number"),!1}if(t.dim)for(var a=0,c=Object.keys(t.dim);a<c.length;a++){var p=c[a];if(!i.test(p))return l("dim key ["+p+"] is unexpected. Length must be not more than 30. Supported chars: a-zA-Z0-9-_"),!1;var h=t.dim[p];if(!/^[a-zA-Z0-9\-_\*\.\s\/#\+@\&\u4e00-\u9fa5]{0,30}$/.test(h))return l("dim."+p+" value ["+h+"] is unexpected. Length must be not more than 30. Supported chars: a-zA-Z0-9-_*. /#+@& and Chinese"),!1}return!0},n.prototype.sendPerf=function(t){this.send(o({type:"perf"},t))},n.prototype.sendExcept=function(t){this.send(o({type:"except"},t))},n.prototype.sendDist=function(t){this.send(o({type:"dist"},t))},n.prototype.sendCount=function(t){this.send(o({type:"count"},t))},n.prototype.sendExceptForError=function(t,e){var i=o({},e);i.info=o({},e.info||{},{msg:t.message,stack:t.stack}),this.sendExcept(i)},n.prototype.startMark=function(t){this.markCache[t]={start:Date.now()}},n.prototype.endMark=function(t){return this.markCache[t]?(this.markCache[t].total=Date.now()-this.markCache[t].start,this.markCache[t].total):0},n.prototype.clearMark=function(t){this.markCache[t]&&delete this.markCache[t]},n.prototype.getAllMark=function(){for(var t={},e=0,i=Object.keys(this.markCache);e<i.length;e++){var o=i[e];t[o]=this.markCache[o].total}return t},n.prototype.clearAllMark=function(){this.markCache={}},n);function n(t){if(this.sample={},this.markCache={},!t.pid)throw new Error("pid is required");this.option={pid:t.pid,lid:t.lid,check:!1!==t.check,sample:t.sample,localCache:t.localCache,logServer:t.logServer||"https://sp1.baidu.com/5b1ZeDe5KgQFm2e88IuM_a/mwb2.gif?"}}var s=window.__spyHead,h="first-input",g=(m.prototype.listenFID=function(t){this.cb=t,this.callCB()},m.prototype.callCB=function(){void 0!==this.finalValue&&this.cb&&this.cb({fid:this.finalValue})},m.prototype.destroy=function(){this.observer&&this.observer.disconnect(),this.observer=null},m.prototype.handle=function(t){var e=t.pop();e&&(this.finalValue=e.duration,this.callCB(),this.destroy())},m);function m(){var e=this;if(this.observer=null,window.PerformanceObserver){s&&s.entryMap&&s.entryMap[h]&&this.handle(s.entryMap[h]);try{this.observer=new PerformanceObserver(function(t){e.handle(t.getEntries())}),this.observer.observe({entryTypes:[h]})}catch(t){}}}var v=window.__spyHead,y="layout-shift",b=(k.prototype.listenLayoutShift=function(t){this.cb=t},k.prototype.leave=function(){this.onceLeave||(this.onceLeave=!0,this.observer&&this.observer.takeRecords&&this.observer.takeRecords(),this.finalValue=this.value,this.callCB(),this.destroy())},k.prototype.callCB=function(){void 0!==this.finalValue&&this.cb&&this.cb({layoutShift:this.finalValue})},k.prototype.destroy=function(){this.observer&&this.observer.disconnect(),this.observer=null},k.prototype.handle=function(t){var e=this;t.map(function(t){t.hadRecentInput||(e.value=(e.value||0)+(t.value||0))})},k);function k(){var e=this;if(this.observer=null,this.onceLeave=!1,window.PerformanceObserver){v&&v.entryMap&&v.entryMap[y]&&this.handle(v.entryMap[y]);try{this.observer=new PerformanceObserver(function(t){e.handle(t.getEntries())}),this.observer.observe({entryTypes:[y]})}catch(t){}}}var w={};function L(t){return w[t]}var S=window.__spyHead,T="largest-contentful-paint",C=(O.prototype.listenLCP=function(t){this.cb=t,this.callCB()},O.prototype.callCB=function(){this.finalValue&&this.cb&&this.cb({lcp:this.finalValue})},O.prototype.load=function(){this.observer&&this.observer.takeRecords&&this.observer.takeRecords(),this.finalValue=this.value,function(t,e){w[t]=e}("lcp",this.value),this.callCB(),this.destroy()},O.prototype.destroy=function(){this.observer&&this.observer.disconnect(),this.observer=null},O.prototype.handle=function(t){var e=this;t.map(function(t){e.value=t.renderTime||t.loadTime})},O);function O(){var e=this;if(this.observer=null,window.PerformanceObserver){S&&S.entryMap&&S.entryMap[T]&&this.handle(S.entryMap[T]);try{this.observer=new PerformanceObserver(function(t){e.handle(t.getEntries())}),this.observer.observe({entryTypes:[T]})}catch(t){}}}function B(t){return t.name.indexOf(".gif?")<0}var R=(I.prototype.check=function(){return window.PerformanceObserver&&performance&&performance.timing&&performance.timing.navigationStart},I.prototype.listenTTI=function(t,e){this.check()&&(this.observeLongtask(2e4),this.cb=t,(e=e||{}).interval&&(this.interval=e.interval),e.filterRequest&&(this.filterRequest=e.filterRequest))},I.prototype.load=function(){this.check()&&(this.ttiTimer=setInterval(this.ttiCheck,this.interval))},I.prototype.ttiCheck=function(){if(this.cb){var t=performance.now();if(!(t-this.lastLongTask<this.interval)){var e=this.getNetworkSilenceAt();if(!1!==e&&!(t-e<this.interval)){clearTimeout(this.ttiTimer);var i=this.lastLongTask;i=i||performance.timing.domContentLoadedEventEnd-performance.timing.navigationStart,this.stopObserveLongTask(),this.cb({tti:i})}}}},I.prototype.observerCallback=function(t){var e=t.getEntries(),i=e[e.length-1];this.lastLongTask=i.startTime+i.duration},I.prototype.stopObserveLongTask=function(){this.observer&&(this.observer.disconnect(),this.observer=null),this.stopLongTaskTimeoutId&&clearTimeout(this.stopLongTaskTimeoutId)},I.prototype.getNetworkSilenceAt=function(){for(var t=0,e=0,i=performance.getEntriesByType("resource").filter(this.filterRequest);e<i.length;e++){var o=i[e];if(!o.responseEnd)return!1;o.responseEnd>t&&(t=o.responseEnd)}return t},I.prototype.observeLongtask=function(t){this.stopObserveLongTask();try{this.observer=new PerformanceObserver(this.observerCallback),this.observer.observe({entryTypes:["longtask"]}),this.stopLongTaskTimeoutId=setTimeout(this.stopObserveLongTask,t)}catch(t){}},I);function I(){this.lastLongTask=0,this.observer=null,this.interval=5e3,this.filterRequest=B,this.observerCallback=this.observerCallback.bind(this),this.ttiCheck=this.ttiCheck.bind(this)}var z,E,P,j,x=(H.prototype.listenTiming=function(t){window.performance&&window.performance.timing&&(this.cb=t)},H.prototype.load=function(){var t=this;setTimeout(function(){t.cb&&t.cb(t.getMetric())},500)},H.prototype.getMetric=function(){var r={},t=window.performance.timing,e=t.navigationStart;if(r.dns=t.domainLookupEnd-t.domainLookupStart,r.tcp=t.connectEnd-t.connectStart,r.request=t.responseStart-t.requestStart,r.response=t.responseEnd-t.responseStart,r.parseHtml=t.domInteractive-t.domLoading,r.domReady=t.domContentLoadedEventEnd-e,r.loadEventHandle=t.loadEventEnd-t.loadEventStart,r.load=t.loadEventEnd-e,performance.getEntriesByType){var i=performance.getEntriesByType("paint");i&&i.length&&i.forEach(function(t){var e=t.name,i=t.duration,o=t.startTime,n=Math.ceil(i+o);"first-paint"===e&&(r.fp=n),"first-contentful-paint"===e&&(r.fcp=n)})}return t.domFirstPaint&&(r.t7FirstPaint=t.domFirstPaint-e),t.domFirstScreenPaint&&(r.t7FirstScreen=t.domFirstScreenPaint-e),r},H);function H(){}(E=z=z||{}).JS="js",E.CSS="css",E.IMG="img",E.FONT="font",(j=P=P||{})[j.ttf=0]="ttf",j[j.eot=1]="eot",j[j.woff=2]="woff",j[j.woff2=3]="woff2";var M=["/mwb2.gif"];function N(t,e){for(var i=0,o=e;i<o.length;i++){var n=o[i];if(-1<t.indexOf(n))return!0}return!1}function _(t){return+t.toFixed(1)}var F=(A.prototype.check=function(){return performance&&performance.getEntriesByType},A.prototype.listenResource=function(t,e){void 0===e&&(e={}),this.check()&&(this.resOption=o(this.resOption,e),this.trigger=this.resOption.trigger,this.cb=t)},A.prototype.listenBigImg=function(t,e){void 0===e&&(e={}),this.check()&&(this.bigImgOption=o(this.bigImgOption,e),this.trigger=this.bigImgOption.trigger,this.bigImgCB=t)},A.prototype.listenHttpResource=function(t,e){void 0===e&&(e={}),this.check()&&(this.httpResOption=o(this.httpResOption,e),this.trigger=this.httpResOption.trigger,this.httpResCB=t)},A.prototype.listenSlowResource=function(t,e){void 0===e&&(e={}),this.check()&&(this.slowOption=o(this.slowOption,e),this.trigger=this.slowOption.trigger,this.slowResCB=t)},A.prototype.report=function(){var l=this,t=this.getMetric();if(t){var e=t.metric,i=t.hostMetric;this.cb&&this.cb(e,i)}this.bigImgCB&&"function"==typeof window.requestIdleCallback&&Object.keys(this.bigImgList).length&&window.requestIdleCallback(function(){for(var t=0,e=Object.keys(l.bigImgList);t<e.length;t++)for(var i=e[t],o=0,n=l.bigImgList[i];o<n.length;o++){var r=n[o],s=r.timing,a=r.type;try{var c=document.body.querySelector('img[src="'+s.name+'"]');l.bigImgCB({msg:s.name,dur:s.duration,xpath:d(c).xpath,host:i,type:a})}catch(t){console.error(t)}}}),this.httpResCB&&"function"==typeof window.requestIdleCallback&&Object.keys(this.httpResList).length&&window.requestIdleCallback(function(){for(var t=0,e=Object.keys(l.httpResList);t<e.length;t++)for(var i=e[t],o=0,n=l.httpResList[i];o<n.length;o++){var r=n[o],s=r.timing,a=r.type;try{var c=document.body.querySelector('[src="'+s.name+'"]');l.httpResCB({msg:s.name,dur:s.duration,xpath:d(c).xpath,host:i,type:a})}catch(t){console.error(t)}}}),this.slowResCB&&"function"==typeof window.requestIdleCallback&&Object.keys(this.slowList).length&&window.requestIdleCallback(function(){for(var t=0,e=Object.keys(l.slowList);t<e.length;t++)for(var i=e[t],o=0,n=l.slowList[i];o<n.length;o++){var r=n[o],s=r.timing,a=r.type;try{var c=document.body.querySelector('[src="'+s.name+'"]'),p={wait:f((h=s).domainLookupStart-(h.navigationStart||h.fetchStart||h.startTime)),dns:f(h.domainLookupEnd-h.domainLookupStart),connect:f(h.connectEnd-h.connectStart),req:f(h.responseStart-h.requestStart),res:f(h.responseEnd-h.responseStart)};l.slowResCB(u(u({},p),{dur:s.duration,msg:s.name,xpath:d(c).xpath,host:i,type:a}))}catch(t){console.error(t)}}var h})},A.prototype.load=function(){var t=this;"load"===this.trigger&&this.check()&&setTimeout(function(){t.report()},500)},A.prototype.leave=function(){"leave"===this.trigger&&this.report()},A.prototype.push=function(t,e,i,o){N(o.pathname,this.resOption.ignorePaths||[])||(e.push(i),this.pushWithHost(t,this.hostList,i,o)),N(o.pathname,this.slowOption.ignorePaths||[])||i.duration>this.slowOption.threshold&&this.pushWithHost(t,this.slowList,i,o)},A.prototype.pushWithHost=function(t,e,i,o){var n=o.host;e[n]||(e[n]=[]),e[n].push({timing:i,type:t})},A.prototype.collectHttpResInHttps=function(t,e,i){"https:"!==location.protocol||0!==e.name.indexOf("http://")||N(i.pathname,this.httpResOption.ignorePaths||[])||this.pushWithHost(t,this.httpResList,e,i)},A.prototype.addScript=function(t,e){"js"===e.ext&&0!==t.decodedBodySize&&this.push("js",this.jsList,t,e)},A.prototype.addResFromCss=function(t,e){e.ext&&P.hasOwnProperty(e.ext)?this.push("font",this.fontList,t,e):this.addImg(t,e)},A.prototype.addLink=function(t,e){"css"===e.ext?this.push("css",this.cssList,t,e):"js"===e.ext&&this.push("js",this.jsList,t,e)},A.prototype.addImg=function(t,e){this.push("img",this.imgList,t,e),t.decodedBodySize>(this.bigImgOption.maxSize||0)&&!N(e.pathname,this.bigImgOption.ignorePaths||[])&&this.pushWithHost("img",this.bigImgList,t,e)},A.prototype.handleTimings=function(t){for(var e=t.length,i=0;i<e;i++){var o=t[i],n=r(o.name);if(!N(n.pathname,M))switch(t[i].initiatorType){case"script":this.addScript(o,n);break;case"css":this.addResFromCss(o,n);break;case"img":this.addImg(o,n);break;case"link":this.addLink(o,n);break;case"audio":this.collectHttpResInHttps("audio",o,n);break;case"video":this.collectHttpResInHttps("video",o,n)}}},A.prototype.getNumAndSize=function(t,e){var i={},o=t+"Num",n=t+"Size",r=t+"TransferSize",s=t+"CacheRate",a=t+"Duration";i[o]=0,i[n]=0;var c=i[r]=0;if(e.forEach(function(t){i[o]++,i[n]+=t.decodedBodySize/1024,i[r]+=t.transferSize/1024,c+=t.duration}),i[a]=_(0<i[o]?c/i[o]:0),i[n]){var p=i[n]-i[r];i[s]=_(0<=p?100*p/i[n]:0)}return i[n]=_(i[n]),i[r]=_(i[r]),i},A.prototype.getMetric=function(){var t=performance.getEntriesByType("navigation")[0],e=performance.getEntriesByType("resource");if(t&&e&&e.length){this.handleTimings(e);var i=u(u(u(u({},this.getNumAndSize(z.JS,this.jsList)),this.getNumAndSize(z.CSS,this.cssList)),this.getNumAndSize(z.IMG,this.imgList)),this.getNumAndSize(z.FONT,this.fontList)),o=t;i.docSize=_(o.decodedBodySize/1024),i.docTransferSize=_(o.transferSize/1024),i.headerSize=_((o.transferSize-o.encodedBodySize||0)/1024),i.allSize=_(i.docSize+i.jsSize+i.cssSize+i.imgSize+i.fontSize),i.allTransferSize=_(i.docTransferSize+i.jsTransferSize+i.cssTransferSize+i.imgTransferSize+i.fontTransferSize);for(var n={},r=0,s=Object.keys(this.hostList);r<s.length;r++){var a=s[r],c=this.hostList[a].map(function(t){return t.timing});n[a]=this.getNumAndSize("host",c)}return{metric:i,hostMetric:n}}},A);function A(){this.trigger="load",this.jsList=[],this.cssList=[],this.imgList=[],this.fontList=[],this.hostList={},this.bigImgList={},this.httpResList={},this.slowList={},this.resOption={ignorePaths:[],trigger:"load"},this.bigImgOption={ignorePaths:[],maxSize:153600,trigger:"load"},this.httpResOption={ignorePaths:[],trigger:"load"},this.slowOption={ignorePaths:[],trigger:"load",threshold:1e3}}var q=null;window.performance&&window.performance.memory&&(q=window.performance.memory);var D=(J.prototype.listenMemory=function(t){this.cb=t},J.prototype.leave=function(){if(!this.onceLeave&&q){this.onceLeave=!0;var t=window.performance.memory;if(t.usedJSHeapSize===q.usedJSHeapSize&&t.totalJSHeapSize===q.totalJSHeapSize)return;var e=window.performance.memory;this.cb&&this.cb({usedJSHeapSize:e.usedJSHeapSize/1024,totalJSHeapSize:e.totalJSHeapSize/1024,jsHeapSizeLimit:e.jsHeapSizeLimit/1024,usedJSHeapRate:100*e.usedJSHeapSize/e.totalJSHeapSize})}},J);function J(){this.onceLeave=!1}var V=(Z.prototype.getNavigatorInfo=function(){var t={},e=navigator.connection;return"object"==typeof e&&(t={downlink:e.downlink,effectiveType:e.effectiveType,rtt:e.rtt,saveData:!!e.saveData}),navigator.deviceMemory&&(t.deviceMemory=navigator.deviceMemory),navigator.hardwareConcurrency&&(t.hardwareConcurrency=navigator.deviceMemory),t},Z.prototype.load=function(){},Z);function Z(){}var W,U,G,$=window.__spyHead,K="longtask",Q=(X.prototype.check=function(){return window.PerformanceObserver&&performance&&performance.timing&&performance.timing.navigationStart},X.prototype.listenFSPLongTask=function(t){this.check()&&(this.fspCB=t)},X.prototype.listenLCPLongTask=function(t){this.check()&&(this.lcpCB=t)},X.prototype.listenLoadLongTask=function(t){this.check()&&(this.loadCB=t)},X.prototype.listenPageLongTask=function(t){this.check()&&(this.pageCB=t)},X.prototype.load=function(){var i=this;if(this.check()){var o=this.getStatData(Date.now());setTimeout(function(){if(i.loadCB&&i.loadCB({loadLongtaskTime:o.time,loadTBT:o.tbt,loadTotalTime:o.totalTime,loadLongtaskRate:o.rate,loadLongtaskNum:o.num}),performance.timing&&performance.timing.domFirstScreenPaint){var t=i.getStatData(performance.timing.domFirstScreenPaint);i.fspCB&&i.fspCB({fspLongtaskTime:t.time,fspTBT:t.tbt,fspTotalTime:t.totalTime,fspLongtaskRate:t.rate,fspLongtaskNum:t.num})}if(L("lcp")){var e=i.getStatData(performance.timing.navigationStart+L("lcp"));i.lcpCB&&i.lcpCB({lcpLongtaskTime:e.time,lcpTBT:e.tbt,lcpTotalTime:e.totalTime,lcpLongtaskRate:e.rate,lcpLongtaskNum:e.num})}},200)}},X.prototype.leave=function(){if(!this.onceLeave){this.onceLeave=!0;var t=this.getStatData(Date.now());this.pageCB&&this.pageCB({pageLongtaskTime:t.time,pageTBT:t.tbt,pageTotalTime:t.totalTime,pageLongtaskRate:t.rate,pageLongtaskNum:t.num,pageIframeLongtaskTime:t.iframeTime,pageIframeLongtaskRate:t.iframeRate,pageIframeLongtaskNum:t.iframeNum})}},X.prototype.destroy=function(){this.lts=[],this.observer&&this.observer.disconnect(),this.observer=null},X.prototype.getStatData=function(t){for(var e=performance.timing.navigationStart,i=0,o=0,n=0,r=0,s=0,a={},c=0;c<this.lts.length;c++){var p=this.lts[c],h=p.duration;if(e+p.startTime+h<t&&(i+=h,o+=0<h-50?h-50:0,n++,p.attribution&&p.attribution[0])){var l=p.attribution[0].containerSrc;l&&l!==location.href&&(a[l]||(a[l]=[]),a[l].push(h),r+=h,s++)}}var u=t-e;return{num:n,time:i,tbt:o,totalTime:u,rate:100*i/u,iframeTime:r,iframeNum:s,iframeRate:100*r/u,iframeLongtasks:a}},X);function X(){var e=this;this.lts=[],this.observer=null,this.onceLeave=!1,$&&$.entryMap&&$.entryMap[K]&&(this.lts=this.lts.concat($.entryMap[K]));try{this.observer=new PerformanceObserver(function(t){e.lts=e.lts.concat(t.getEntries())}),this.observer.observe({entryTypes:[K]})}catch(t){}}function Y(){this.constructor=W}function tt(t){var e=G.call(this,t)||this;return e.modules=[],e.register(new g),e.register(new C),e.register(new b),e.register(new R),e.register(new x),e.register(new F),e.register(new D),e.register(new V),e.register(new Q),e.visibilitychangeCB=e.visibilitychangeCB.bind(e),e.load=e.load.bind(e),e.leave=e.leave.bind(e),"complete"===document.readyState?e.load():window.addEventListener("load",e.load),document.addEventListener("visibilitychange",e.visibilitychangeCB),window.addEventListener("beforeunload",e.leave,!1),window.addEventListener("unload",e.leave,!1),e.handleHead(),e}return i(W=tt,U=G=e),void(W.prototype=null===U?Object.create(U):(Y.prototype=U.prototype,new Y)),tt.prototype.handleHead=function(){var e=this;if(this.option.localCache){var t=window.__spyHead;if(t&&t.winerrors){for(var i=0;i<t.winerrors.length;i++){var o=t.winerrors[i];this.option.localCache.addLog(o)}t.interceptor=function(t){e.option.localCache.addLog(t)}}}},tt.prototype.listenFID=function(t){this.invoke("listenFID",t)},tt.prototype.listenLayoutShift=function(t){this.invoke("listenLayoutShift",t)},tt.prototype.listenLCP=function(t){this.invoke("listenLCP",t)},tt.prototype.listenFSPLongTask=function(t){this.invoke("listenFSPLongTask",t)},tt.prototype.listenLCPLongTask=function(t){this.invoke("listenLCPLongTask",t)},tt.prototype.listenLoadLongTask=function(t){this.invoke("listenLoadLongTask",t)},tt.prototype.listenPageLongTask=function(t){this.invoke("listenPageLongTask",t)},tt.prototype.listenMemory=function(t){this.invoke("listenMemory",t)},tt.prototype.getNavigatorInfo=function(){return this.invoke("getNavigatorInfo")},tt.prototype.listenResource=function(t,e){this.invoke("listenResource",t,e)},tt.prototype.listenBigImg=function(t,e){this.invoke("listenBigImg",t,e)},tt.prototype.listenHttpResource=function(t,e){this.invoke("listenHttpResource",t,e)},tt.prototype.listenSlowResource=function(t,e){this.invoke("listenSlowResource",t,e)},tt.prototype.listenTiming=function(t){this.invoke("listenTiming",t)},tt.prototype.listenTTI=function(t,e){this.invoke("listenTTI",t,e)},tt.prototype.invoke=function(t,e,i){for(var o=0;o<this.modules.length;o++){var n=this.modules[o];if("function"==typeof n[t])return n[t].apply(n,[e,i])}console.error("no method",t)},tt.prototype.register=function(t){this.modules.push(t)},tt.prototype.load=function(){for(var t=0;t<this.modules.length;t++){var e=this.modules[t];e.load&&e.load()}},tt.prototype.leave=function(){for(var t=0;t<this.modules.length;t++){var e=this.modules[t];e.leave&&e.leave()}},tt.prototype.destroy=function(){for(var t=0;t<this.modules.length;t++){var e=this.modules[t];e.destroy&&e.destroy()}document.removeEventListener("visibilitychange",this.visibilitychangeCB),window.removeEventListener("load",this.load),window.removeEventListener("beforeunload",this.leave),window.removeEventListener("unload",this.destroy)},tt.prototype.visibilitychangeCB=function(){"hidden"===document.visibilityState&&this.leave()},tt});
|
package/dist/spy-client.mjs
CHANGED
|
@@ -165,6 +165,7 @@ var SpyClient$1 = /** @class */ (function () {
|
|
|
165
165
|
lid: option.lid,
|
|
166
166
|
check: option.check !== false,
|
|
167
167
|
sample: option.sample,
|
|
168
|
+
localCache: option.localCache,
|
|
168
169
|
logServer: option.logServer || defaultLogServer,
|
|
169
170
|
};
|
|
170
171
|
}
|
|
@@ -176,9 +177,9 @@ var SpyClient$1 = /** @class */ (function () {
|
|
|
176
177
|
method: 'POST',
|
|
177
178
|
credentials: 'include',
|
|
178
179
|
headers: {
|
|
179
|
-
'Content-Type': 'application/json'
|
|
180
|
+
'Content-Type': 'application/json',
|
|
180
181
|
},
|
|
181
|
-
body: JSON.stringify(data)
|
|
182
|
+
body: JSON.stringify(data),
|
|
182
183
|
});
|
|
183
184
|
};
|
|
184
185
|
SpyClient.prototype.sendPost = function (data) {
|
|
@@ -201,6 +202,15 @@ var SpyClient$1 = /** @class */ (function () {
|
|
|
201
202
|
if (!this.check(logItem)) {
|
|
202
203
|
return;
|
|
203
204
|
}
|
|
205
|
+
logItem = assign({
|
|
206
|
+
pid: this.option.pid,
|
|
207
|
+
lid: this.option.lid,
|
|
208
|
+
ts: Date.now(),
|
|
209
|
+
group: 'common',
|
|
210
|
+
}, logItem);
|
|
211
|
+
if (this.option.localCache) {
|
|
212
|
+
this.option.localCache.addLog(logItem);
|
|
213
|
+
}
|
|
204
214
|
// 当前api设置了抽样,
|
|
205
215
|
if (typeof logItem.sample === 'number') {
|
|
206
216
|
if (Math.random() > logItem.sample) {
|
|
@@ -210,12 +220,6 @@ var SpyClient$1 = /** @class */ (function () {
|
|
|
210
220
|
else if (typeof this.option.sample === 'number' && Math.random() > this.option.sample) { // 否则,用全局抽样
|
|
211
221
|
return;
|
|
212
222
|
}
|
|
213
|
-
logItem = assign({
|
|
214
|
-
pid: this.option.pid,
|
|
215
|
-
lid: this.option.lid,
|
|
216
|
-
ts: Date.now(),
|
|
217
|
-
group: 'common',
|
|
218
|
-
}, logItem);
|
|
219
223
|
delete logItem.sample;
|
|
220
224
|
return logItem;
|
|
221
225
|
};
|
|
@@ -1362,8 +1366,25 @@ var SpyClient = /** @class */ (function (_super) {
|
|
|
1362
1366
|
document.addEventListener('visibilitychange', _this.visibilitychangeCB);
|
|
1363
1367
|
window.addEventListener('beforeunload', _this.leave, false);
|
|
1364
1368
|
window.addEventListener('unload', _this.leave, false);
|
|
1369
|
+
_this.handleHead();
|
|
1365
1370
|
return _this;
|
|
1366
1371
|
}
|
|
1372
|
+
SpyClient.prototype.handleHead = function () {
|
|
1373
|
+
var _this = this;
|
|
1374
|
+
if (this.option.localCache) {
|
|
1375
|
+
var spyHead = window.__spyHead;
|
|
1376
|
+
if (spyHead && spyHead.winerrors) {
|
|
1377
|
+
for (var index = 0; index < spyHead.winerrors.length; index++) {
|
|
1378
|
+
var obj = spyHead.winerrors[index];
|
|
1379
|
+
this.option.localCache.addLog(obj);
|
|
1380
|
+
}
|
|
1381
|
+
// Head发送的异常,也保存一份到本地,主要是JS错误和资源加载异常
|
|
1382
|
+
spyHead.interceptor = function (obj) {
|
|
1383
|
+
_this.option.localCache.addLog(obj);
|
|
1384
|
+
};
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
};
|
|
1367
1388
|
SpyClient.prototype.listenFID = function (cb) {
|
|
1368
1389
|
this.invoke('listenFID', cb);
|
|
1369
1390
|
};
|
package/dist/spy-head.js
CHANGED
|
@@ -87,11 +87,32 @@
|
|
|
87
87
|
init: function (conf) {
|
|
88
88
|
this.conf = conf;
|
|
89
89
|
},
|
|
90
|
-
|
|
91
|
-
|
|
90
|
+
addError: function (obj) {
|
|
91
|
+
// 有些错误一下出现很多次,都聚合都一个错误,加上次数
|
|
92
|
+
if (this.winerrors.length > 0) {
|
|
93
|
+
var lastObj = this.winerrors[this.winerrors.length - 1];
|
|
94
|
+
if (obj.info.msg === lastObj.info.msg) {
|
|
95
|
+
lastObj.info.count += (lastObj.info.count || 0);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (this.winerrors.length < 1000) {
|
|
100
|
+
this.winerrors.push(obj);
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
send: function (obj, isSend, logServer) {
|
|
92
104
|
var conf = this.conf;
|
|
105
|
+
obj.type = obj.type || 'except';
|
|
106
|
+
obj.pid = conf.pid;
|
|
107
|
+
obj.lid = conf.lid;
|
|
108
|
+
obj.ts = Date.now();
|
|
109
|
+
this.addError(obj);
|
|
110
|
+
this.interceptor && this.interceptor(obj);
|
|
111
|
+
if (isSend === false) {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
93
114
|
logServer = logServer || conf.logServer;
|
|
94
|
-
var logUrl = logServer + "?pid=" +
|
|
115
|
+
var logUrl = logServer + "?pid=" + obj.pid + "&lid=" + obj.lid + "&ts=" + obj.ts
|
|
95
116
|
+ ("&type=" + obj.type + "&group=" + obj.group + "&info=" + encodeURIComponent(JSON.stringify(obj.info)));
|
|
96
117
|
if (obj.dim) {
|
|
97
118
|
logUrl += '&dim=' + encodeURIComponent(JSON.stringify(obj.dim));
|
|
@@ -147,18 +168,18 @@
|
|
|
147
168
|
}
|
|
148
169
|
// 历史错误
|
|
149
170
|
var historys = [];
|
|
150
|
-
for (var index = 0; index <
|
|
151
|
-
var item =
|
|
152
|
-
var prefix = item.count > 1 ? "(" + item.count + ")" : '';
|
|
153
|
-
historys.push(prefix + item.msg);
|
|
171
|
+
for (var index = 0; index < winerrors.length; index++) {
|
|
172
|
+
var item = winerrors[index];
|
|
173
|
+
var prefix = item.info.count > 1 ? "(" + item.info.count + ")" : '';
|
|
174
|
+
historys.push(prefix + item.info.msg);
|
|
154
175
|
}
|
|
155
176
|
info.hisErrors = historys.join('----');
|
|
156
177
|
var allow = true;
|
|
157
178
|
if (jsError.handler) {
|
|
158
179
|
allow = jsError.handler(obj);
|
|
159
180
|
}
|
|
160
|
-
if (allow !== false
|
|
161
|
-
spyHead.send(obj);
|
|
181
|
+
if (allow !== false) {
|
|
182
|
+
spyHead.send(obj, isSendJserror);
|
|
162
183
|
}
|
|
163
184
|
}
|
|
164
185
|
// 资源错误
|
|
@@ -178,20 +199,11 @@
|
|
|
178
199
|
if (resourceError.handler) {
|
|
179
200
|
allow = resourceError.handler(obj);
|
|
180
201
|
}
|
|
181
|
-
if (allow !== false
|
|
182
|
-
spyHead.send(obj);
|
|
202
|
+
if (allow !== false) {
|
|
203
|
+
spyHead.send(obj, isSendResource);
|
|
183
204
|
}
|
|
184
205
|
resourceErrorCount++;
|
|
185
206
|
}
|
|
186
|
-
// 有些错误一下出现很多次,都聚合都一个错误,加上次数
|
|
187
|
-
if (winerrors.length > 0) {
|
|
188
|
-
var lastInfo = winerrors[winerrors.length - 1];
|
|
189
|
-
if (info.msg === lastInfo.msg) {
|
|
190
|
-
lastInfo.count += (lastInfo.count || 0);
|
|
191
|
-
return;
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
winerrors.push(info);
|
|
195
207
|
}
|
|
196
208
|
catch (e) {
|
|
197
209
|
console.error(e);
|
|
@@ -200,7 +212,7 @@
|
|
|
200
212
|
window.addEventListener('error', spyListenError, true);
|
|
201
213
|
spyHead.errorDestroy = function () {
|
|
202
214
|
window.removeEventListener('error', spyListenError, true);
|
|
203
|
-
spyHead.winerrors =
|
|
215
|
+
spyHead.winerrors = [];
|
|
204
216
|
};
|
|
205
217
|
}
|
|
206
218
|
|
|
@@ -270,8 +282,8 @@
|
|
|
270
282
|
var errors = spyHead.winerrors;
|
|
271
283
|
var historys = [];
|
|
272
284
|
for (var i = 0; i < errors.length; i++) {
|
|
273
|
-
var stack = (errors[i].stack || '').split('\n')[0];
|
|
274
|
-
historys.push("(" + i + ")" + (stack || errors[i].msg));
|
|
285
|
+
var stack = (errors[i].info.stack || '').split('\n')[0];
|
|
286
|
+
historys.push("(" + i + ")" + (stack || errors[i].info.msg));
|
|
275
287
|
}
|
|
276
288
|
return historys.join(';;');
|
|
277
289
|
}
|
|
@@ -301,25 +313,25 @@
|
|
|
301
313
|
}
|
|
302
314
|
return false;
|
|
303
315
|
}
|
|
304
|
-
if (
|
|
316
|
+
if (selector) {
|
|
305
317
|
setTimeout(function () {
|
|
306
|
-
var obj = {
|
|
307
|
-
group: whiteScreenError.group,
|
|
308
|
-
info: {
|
|
309
|
-
msg: '',
|
|
310
|
-
netTime: getNetTime(),
|
|
311
|
-
hisErrors: getHisError(),
|
|
312
|
-
deviceInfo: getDeviceInfo(),
|
|
313
|
-
},
|
|
314
|
-
};
|
|
315
318
|
if (isWhiteScreen()) {
|
|
319
|
+
var obj = {
|
|
320
|
+
group: whiteScreenError.group,
|
|
321
|
+
info: {
|
|
322
|
+
msg: '',
|
|
323
|
+
netTime: getNetTime(),
|
|
324
|
+
hisErrors: getHisError(),
|
|
325
|
+
deviceInfo: getDeviceInfo(),
|
|
326
|
+
},
|
|
327
|
+
};
|
|
316
328
|
obj.info.msg = 'WhiteScren Error';
|
|
317
329
|
var allow = true;
|
|
318
330
|
if (handler) {
|
|
319
331
|
allow = handler(obj);
|
|
320
332
|
}
|
|
321
333
|
if (allow !== false && obj.info.msg) {
|
|
322
|
-
spyHead && spyHead.send(obj);
|
|
334
|
+
spyHead && spyHead.send(obj, isSend);
|
|
323
335
|
}
|
|
324
336
|
}
|
|
325
337
|
}, timeout);
|
package/dist/spy-head.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(e="undefined"!=typeof globalThis?globalThis:e||self).__spyHead=r()}(this,function(){"use strict";function E(e){var r=function(e){if(URL){var r=new URL(e);if(void 0!==r.host)return{protocol:r.protocol,host:r.host,pathname:r.pathname,ext:""}}}(e);if(!r){var n=document.createElement("a");n.href=e,r={protocol:n.protocol,host:n.host||location.host,pathname:n.pathname,ext:""}}var t=r.pathname.split(".");return r.ext=t[t.length-1],r}function
|
|
1
|
+
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(e="undefined"!=typeof globalThis?globalThis:e||self).__spyHead=r()}(this,function(){"use strict";function E(e){var r=function(e){if(URL){var r=new URL(e);if(void 0!==r.host)return{protocol:r.protocol,host:r.host,pathname:r.pathname,ext:""}}}(e);if(!r){var n=document.createElement("a");n.href=e,r={protocol:n.protocol,host:n.host||location.host,pathname:n.pathname,ext:""}}var t=r.pathname.split(".");return r.ext=t[t.length-1],r}function c(e){return+e.toFixed(1)}var T={conf:{},winerrors:[],errorDestroy:function(){},observerDestroy:function(){},entryMap:{},init:function(e){this.conf=e},addError:function(e){if(0<this.winerrors.length){var r=this.winerrors[this.winerrors.length-1];if(e.info.msg===r.info.msg)return void(r.info.count+=r.info.count||0)}this.winerrors.length<1e3&&this.winerrors.push(e)},send:function(e,r,n){var t=this.conf;if(e.type=e.type||"except",e.pid=t.pid,e.lid=t.lid,e.ts=Date.now(),this.addError(e),this.interceptor&&this.interceptor(e),!1!==r){var o=(n=n||t.logServer)+"?pid="+e.pid+"&lid="+e.lid+"&ts="+e.ts+"&type="+e.type+"&group="+e.group+"&info="+encodeURIComponent(JSON.stringify(e.info));e.dim&&(o+="&dim="+encodeURIComponent(JSON.stringify(e.dim)));var i=new Image;i.src=o,i.onload=i.onerror=function(){i=null}}}};function r(e){var h=e.resourceError||{},m=e.jsError||{},g=Math.random()<(m.sample?m.sample:0),v=Math.random()<(h.sample?h.sample:0),w=T.winerrors,y=0;function r(e){try{var r=e.target,n={info:{},dim:{},group:""},t=n.info,o=e.srcElement,i=navigator.connection||{};if(t.downlink=i.downlink,t.effectiveType=i.effectiveType,t.rtt=i.rtt,t.deviceMemory=navigator.deviceMemory||0,t.hardwareConcurrency=navigator.hardwareConcurrency||0,o===window){n.group=m.group;var a=e.error||{};if(t.msg=e.message,t.file=e.filename,t.ln=e.lineno,t.col=e.colno,t.stack=(a.stack||"").split("\n").slice(0,3).join("\n"),-1!==t.msg.indexOf("MODULE_TIMEOUT")){var s=t.msg.match(/^.*Hang:(.*); Miss:(.*)/);s&&s[2]&&(t.msg="MODULE_TIMEOUT for miss:"+s[2])}for(var c=[],f=0;f<w.length;f++){var d=w[f],u=1<d.info.count?"("+d.info.count+")":"";c.push(u+d.info.msg)}t.hisErrors=c.join("----");var p=!0;m.handler&&(p=m.handler(n)),!1!==p&&T.send(n,g)}else{n.group=h.group,n.dim.type=o.tagName.toLowerCase();var l=o.src||o.href;t.msg=l||"unknown load eror",n.dim.host=E(l).host,r&&"IMG"===r.tagName&&(t.xpath=function(e){if(!e)return{xpath:""};for(var r=[];e&&1===e.nodeType&&e!==e.parentNode;){var n=e.tagName.toLowerCase();if(e.getAttribute("id")?n+="[#"+e.getAttribute("id")+"]":e.classList&&e.classList.length&&(n+="[."+e.classList[e.classList.length-1]+"]"),r.push(n),e===document.body)break;e=e.parentNode}return{xpath:r.join("<")}}(r).xpath),y&&(t.hisErrCount=y);p=!0;h.handler&&(p=h.handler(n)),!1!==p&&T.send(n,v),y++}}catch(e){console.error(e)}}window.addEventListener("error",r,!0),T.errorDestroy=function(){window.removeEventListener("error",r,!0),T.winerrors=[]}}function n(e){var n=e.whiteScreenError||{},t=n.handler,o=n.selector,i=n.subSelector,r=n.timeout||6e3,a=Math.random()<(n.sample?n.sample:0);function s(){if(!window.performance)return!1;var e=function(e){return{wait:c(e.domainLookupStart-(e.navigationStart||e.fetchStart||e.startTime)),dns:c(e.domainLookupEnd-e.domainLookupStart),connect:c(e.connectEnd-e.connectStart),req:c(e.responseStart-e.requestStart),res:c(e.responseEnd-e.responseStart)}}(window.performance.timing);return"&wait="+e.wait+"&dns="+e.dns+"&connect="+e.connect+"&requestTime="+e.req+"&resoneTime="+e.res}o&&setTimeout(function(){if(function(){var e=document.querySelector(o);return!e||(!e.querySelector(i)||e.clientHeight<2*window.innerHeight/3)}()){var e={group:n.group,info:{msg:"",netTime:s(),hisErrors:function(){if(!T.winerrors)return!1;for(var e=T.winerrors,r=[],n=0;n<e.length;n++){var t=(e[n].info.stack||"").split("\n")[0];r.push("("+n+")"+(t||e[n].info.msg))}return r.join(";;")}(),deviceInfo:function(){var e={},r=navigator.connection||{};return e.downlink=r.downlink,e.effectiveType=r.effectiveType,e.rtt=r.rtt,e.deviceMemory=navigator.deviceMemory||0,e.hardwareConcurrency=navigator.hardwareConcurrency||0,e}()}};e.info.msg="WhiteScren Error";var r=!0;t&&(r=t(e)),!1!==r&&e.info.msg&&T&&T.send(e,a)}},r)}return T.init=function(e){e.logServer||(e.logServer="https://sp1.baidu.com/5b1ZeDe5KgQFm2e88IuM_a/mwb2.gif"),r(this.conf=e),function(){if(window.PerformanceObserver){var e=new window.PerformanceObserver(function(e){for(var r=T.entryMap,n=e.getEntries(),t=0;t<n.length;t++){var o=n[t];r[o.entryType]||(r[o.entryType]=[]),r[o.entryType].push(o)}});T.observerDestroy=function(){e.disconnect()};try{e.observe({entryTypes:["longtask","layout-shift","first-input","largest-contentful-paint"]})}catch(e){}}}(),n(e)},window.__spyclientConf&&T.init(window.__spyclientConf),T});
|