web-error-monitor
Version:
ts实现前端项目源码上传、错误信息监控
7 lines (6 loc) • 15.3 kB
JavaScript
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).WebErrorTracker={})}(this,(function(e){"use strict";const n=e=>{if("object"!=typeof e||null==typeof e)return e;let r;r=e instanceof Array?[]:{};for(let t in e)e.hasOwnProperty(t)&&(r[t]=n(e[t]));return r};var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var o={exports:{}};
/**
* https://github.com/csnover/TraceKit
* @license MIT
* @namespace TraceKit
*/!function(e){!function(n){if(n){var r={},t=n.TraceKit,o=[].slice,i="?",s=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;r.noConflict=function(){return n.TraceKit=t,r},r.wrap=function(e){return function(){try{return e.apply(this,arguments)}catch(e){throw r.report(e),e}}},r.report=function(){var e,t,o,i,l=[],a=null,u=null;function f(e,n,t){var o=null;if(!n||r.collectWindowErrors){for(var i in l)if(c(l,i))try{l[i](e,n,t)}catch(e){o=e}if(o)throw o}}function p(n,t,o,i,c){if(u)r.computeStackTrace.augmentStackTraceWithInitialElement(u,t,o,n),d();else if(c)f(r.computeStackTrace(c),!0,c);else{var l,a={url:t,line:o,column:i},p=n;if("[object String]"==={}.toString.call(n)){var m=n.match(s);m&&(l=m[1],p=m[2])}a.func=r.computeStackTrace.guessFunctionName(a.url,a.line),a.context=r.computeStackTrace.gatherContext(a.url,a.line),f({name:l,message:p,mode:"onerror",stack:[a]},!0,null)}return!!e&&e.apply(this,arguments)}function m(e){f(r.computeStackTrace(e.reason),!0,e.reason)}function d(){var e=u,n=a;u=null,a=null,f(e,!1,n)}function h(e){if(u){if(a===e)return;d()}var n=r.computeStackTrace(e);throw u=n,a=e,setTimeout((function(){a===e&&d()}),n.incomplete?2e3:0),e}return h.subscribe=function(r){!function(){if(!0===t)return;e=n.onerror,n.onerror=p,t=!0}(),function(){if(!0===i)return;o=n.onunhandledrejection,n.onunhandledrejection=m,i=!0}(),l.push(r)},h.unsubscribe=function(r){for(var s=l.length-1;s>=0;--s)l[s]===r&&l.splice(s,1);0===l.length&&(t&&(n.onerror=e,t=!1),i&&(n.onunhandledrejection=o,i=!1))},h}(),r.computeStackTrace=function(){var e={};function t(t){if("string"!=typeof t)return[];if(!c(e,t)){var o="",i="";try{i=n.document.domain}catch(e){}var s=/(.*)\:\/\/([^:\/]+)([:\d]*)\/{0,1}([\s\S]*)/.exec(t);s&&s[2]===i&&(o=function(e){if(!r.remoteFetching)return"";try{var t=function(){try{return new n.XMLHttpRequest}catch(e){return new n.ActiveXObject("Microsoft.XMLHTTP")}}();return t.open("GET",e,!1),t.send(""),t.responseText}catch(e){return""}}(t)),e[t]=o?o.split("\n"):[]}return e[t]}function o(e,n){var r,o=/function ([^(]*)\(([^)]*)\)/,s=/['"]?([0-9A-Za-z$_]+)['"]?\s*[:=]\s*(function|eval|new Function)/,c="",a=t(e);if(!a.length)return i;for(var u=0;u<10;++u)if(!l(c=a[n-u]+c)){if(r=s.exec(c))return r[1];if(r=o.exec(c))return r[1]}return i}function s(e,n){var o=t(e);if(!o.length)return null;var i=[],s=Math.floor(r.linesOfContext/2),c=s+r.linesOfContext%2,a=Math.max(0,n-s-1),u=Math.min(o.length,n+c-1);n-=1;for(var f=a;f<u;++f)l(o[f])||i.push(o[f]);return i.length>0?i:null}function a(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#]/g,"\\$&")}function u(e){return a(e).replace("<","(?:<|<)").replace(">","(?:>|>)").replace("&","(?:&|&)").replace('"','(?:"|")').replace(/\s+/g,"\\s+")}function f(e,n){for(var r,o,i=0,s=n.length;i<s;++i)if((r=t(n[i])).length&&(r=r.join("\n"),o=e.exec(r)))return{url:n[i],line:r.substring(0,o.index).split("\n").length,column:o.index-r.lastIndexOf("\n",o.index)-1};return null}function p(e,n,r){var o,i=t(n),s=new RegExp("\\b"+a(e)+"\\b");return r-=1,i&&i.length>r&&(o=s.exec(i[r]))?o.index:null}function m(e){if(!l(n&&n.document)){for(var r,t,o,i,s=[n.location.href],c=n.document.getElementsByTagName("script"),p=""+e,m=0;m<c.length;++m){var d=c[m];d.src&&s.push(d.src)}if(o=/^function(?:\s+([\w$]+))?\s*\(([\w\s,]*)\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/.exec(p)){var h=o[1]?"\\s+"+o[1]:"",g=o[2].split(",").join("\\s*,\\s*");r=a(o[3]).replace(/;$/,";?"),t=new RegExp("function"+h+"\\s*\\(\\s*"+g+"\\s*\\)\\s*{\\s*"+r+"\\s*}")}else t=new RegExp(a(p).replace(/\s+/g,"\\s+"));if(i=f(t,s))return i;if(o=/^function on([\w$]+)\s*\(event\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/.exec(p)){var v=o[1];if(r=u(o[2]),i=f(t=new RegExp("on"+v+"=[\\'\"]\\s*"+r+"\\s*[\\'\"]","i"),s[0]))return i;if(i=f(t=new RegExp(r),s))return i}return null}}function d(e){if(!e.stack)return null;for(var n,r,t,c=/^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,a=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,u=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,f=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,m=/\((\S*)(?::(\d+))(?::(\d+))\)/,d=e.stack.split("\n"),h=[],g=/^(.*) is undefined$/.exec(e.message),v=0,x=d.length;v<x;++v){if(r=c.exec(d[v])){var y=r[2]&&0===r[2].indexOf("native");r[2]&&0===r[2].indexOf("eval")&&(n=m.exec(r[2]))&&(r[2]=n[1],r[3]=n[2],r[4]=n[3]),t={url:y?null:r[2],func:r[1]||i,args:y?[r[2]]:[],line:r[3]?+r[3]:null,column:r[4]?+r[4]:null}}else if(r=u.exec(d[v]))t={url:r[2],func:r[1]||i,args:[],line:+r[3],column:r[4]?+r[4]:null};else{if(!(r=a.exec(d[v])))continue;r[3]&&r[3].indexOf(" > eval")>-1&&(n=f.exec(r[3]))?(r[3]=n[1],r[4]=n[2],r[5]=null):0!==v||r[5]||l(e.columnNumber)||(h[0].column=e.columnNumber+1),t={url:r[3],func:r[1]||i,args:r[2]?r[2].split(","):[],line:r[4]?+r[4]:null,column:r[5]?+r[5]:null}}!t.func&&t.line&&(t.func=o(t.url,t.line)),t.context=t.line?s(t.url,t.line):null,h.push(t)}return h.length?(h[0]&&h[0].line&&!h[0].column&&g&&(h[0].column=p(g[1],h[0].url,h[0].line)),{mode:"stack",name:e.name,message:e.message,stack:h}):null}function h(e,n,r,t){var i={url:n,line:r};if(i.url&&i.line){e.incomplete=!1,i.func||(i.func=o(i.url,i.line)),i.context||(i.context=s(i.url,i.line));var c=/ '([^']+)' /.exec(t);if(c&&(i.column=p(c[1],i.url,i.line)),e.stack.length>0&&e.stack[0].url===i.url){if(e.stack[0].line===i.line)return!1;if(!e.stack[0].line&&e.stack[0].func===i.func)return e.stack[0].line=i.line,e.stack[0].context=i.context,!1}return e.stack.unshift(i),e.partial=!0,!0}return e.incomplete=!0,!1}function g(e,n){for(var t,s,c,l=/function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,a=[],u={},f=!1,d=g.caller;d&&!f;d=d.caller)if(d!==v&&d!==r.report){if(s={url:null,func:i,args:[],line:null,column:null},d.name?s.func=d.name:(t=l.exec(d.toString()))&&(s.func=t[1]),void 0===s.func)try{s.func=t.input.substring(0,t.input.indexOf("{"))}catch(e){}if(c=m(d)){s.url=c.url,s.line=c.line,s.func===i&&(s.func=o(s.url,s.line));var x=/ '([^']+)' /.exec(e.message||e.description);x&&(s.column=p(x[1],c.url,c.line))}u[""+d]?f=!0:u[""+d]=!0,a.push(s)}n&&a.splice(0,n);var y={mode:"callers",name:e.name,message:e.message,stack:a};return h(y,e.sourceURL||e.fileName,e.line||e.lineNumber,e.message||e.description),y}function v(e,r){var i=null;r=null==r?0:+r;try{if(i=function(e){var n=e.stacktrace;if(n){for(var r,t=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,i=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^\)]+))\((.*)\))? in (.*):\s*$/i,c=n.split("\n"),l=[],a=0;a<c.length;a+=2){var u=null;if((r=t.exec(c[a]))?u={url:r[2],line:+r[1],column:null,func:r[3],args:[]}:(r=i.exec(c[a]))&&(u={url:r[6],line:+r[1],column:+r[2],func:r[3]||r[4],args:r[5]?r[5].split(","):[]}),u){if(!u.func&&u.line&&(u.func=o(u.url,u.line)),u.line)try{u.context=s(u.url,u.line)}catch(e){}u.context||(u.context=[c[a+1]]),l.push(u)}}return l.length?{mode:"stacktrace",name:e.name,message:e.message,stack:l}:null}}(e),i)return i}catch(e){}try{if(i=d(e))return i}catch(e){}try{if(i=function(e){var r=e.message.split("\n");if(r.length<4)return null;var i,l=/^\s*Line (\d+) of linked script ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,a=/^\s*Line (\d+) of inline#(\d+) script in ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,p=/^\s*Line (\d+) of function script\s*$/i,m=[],d=n&&n.document&&n.document.getElementsByTagName("script"),h=[];for(var g in d)c(d,g)&&!d[g].src&&h.push(d[g]);for(var v=2;v<r.length;v+=2){var x=null;if(i=l.exec(r[v]))x={url:i[2],func:i[3],args:[],line:+i[1],column:null};else if(i=a.exec(r[v])){x={url:i[3],func:i[4],args:[],line:+i[1],column:null};var y=+i[1],w=h[i[2]-1];if(w){var b=t(x.url);if(b){var k=(b=b.join("\n")).indexOf(w.innerText);k>=0&&(x.line=y+b.substring(0,k).split("\n").length)}}}else if(i=p.exec(r[v])){var S=n.location.href.replace(/#.*$/,""),E=f(new RegExp(u(r[v+1])),[S]);x={url:S,func:"",args:[],line:E?E.line:i[1],column:null}}if(x){x.func||(x.func=o(x.url,x.line));var T=s(x.url,x.line),$=T?T[Math.floor(T.length/2)]:null;T&&$.replace(/^\s*/,"")===r[v+1].replace(/^\s*/,"")?x.context=T:x.context=[r[v+1]],m.push(x)}}return m.length?{mode:"multiline",name:e.name,message:r[0],stack:m}:null}(e),i)return i}catch(e){}try{if(i=g(e,r+1))return i}catch(e){}return{name:e.name,message:e.message,mode:"failed"}}return v.augmentStackTraceWithInitialElement=h,v.computeStackTraceFromStackProp=d,v.guessFunctionName=o,v.gatherContext=s,v.ofCaller=function(e){e=1+(null==e?0:+e);try{throw new Error}catch(n){return v(n,e+1)}},v.getSource=t,v}(),r.extendToAsynchronousCallbacks=function(){var e=function(e){var t=n[e];n[e]=function(){var e=o.call(arguments),n=e[0];return"function"==typeof n&&(e[0]=r.wrap(n)),t.apply?t.apply(this,e):t(e[0],e[1])}};e("setTimeout"),e("setInterval")},r.remoteFetching||(r.remoteFetching=!0),r.collectWindowErrors||(r.collectWindowErrors=!0),(!r.linesOfContext||r.linesOfContext<1)&&(r.linesOfContext=11),e.exports&&n.module!==e?e.exports=r:n.TraceKit=r}function c(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function l(e){return void 0===e}}("undefined"!=typeof window?window:r)}(o);var i=t(o.exports);function s(){const e=new Date,n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),t=String(e.getDate()).padStart(2,"0"),o=e.getHours(),i=String(e.getMinutes()).padStart(2,"0"),s=String(e.getSeconds()).padStart(2,"0");let c,l="";o<12?(c=0===o?12:o,l="上午"):(c=12===o?12:o-12,l="下午");return`${n}-${r}-${t} ${["星期日","星期一","星期二","星期三","星期四","星期五","星期六"][e.getDay()]} ${l} ${o>=12?String(o).padStart(2,"0"):c}:${i}:${s}`}function c(e,n,r,t){return{packingMethod:e,errorType:{1:"jsError",2:"resourceError",3:"vueError",4:"httpError"}[n],message:r,stack:t,date:s()}}const l=require("http"),a=require("url"),u=require("fs"),f=require("path");class p{outputPath;jsmapsDir;packTools;constructor(e){this.packTools=e,this.jsmapsDir=f.resolve(process.cwd(),"dist-jsmaps"),"vite"===this.packTools&&this.viteWayInit()}viteWayInit(){this.outputPath=f.resolve(process.cwd(),"dist/assets"),this.createDir(this.jsmapsDir)}async getJsmaps(e){return(await u.promises.readdir(e)).filter((e=>e.endsWith(".js.map")))}async moveJsMaps(e,n,r){const t=e.map((async e=>{const t=f.join(n,e),o=f.join(r,e);await async function(e,n){u.access(e,(r=>{r&&console.error(`access文件不存在: ${e}`),u.rename(e,n,(r=>{r&&console.error(`Error moving file from ${e} to ${n}: ${r.message}`)}))}))}(t,o)}));try{await Promise.all(t),console.log("All files moved successfully."+t.length)}catch(e){console.error(`Error moving some files: ${e.message}`)}}createDir(e){try{this.removeDir("dist-jsmaps"),u.promises.mkdir(e,{recursive:!0})}catch(e){console.error(`Error creating maps directory: ${e}`)}}removeDir(e){const n=f.resolve(process.cwd(),e);u.rmSync(n,{recursive:!0,force:!0})}}const m=async(e,n,r,t)=>{const o=function(e,n){return e.map((e=>{const r=f.join(n,e);return{fileName:e,fileContent:u.readFileSync(r,"utf8")}}))}(e,n),i={mapsArr:o,storageDir:t};try{const e=await((e,n)=>new Promise(((r,t)=>{const o=JSON.stringify(n),i=a.parse(e),s={hostname:i.hostname,port:i.port||80,path:i.path,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(o)}},c=l.request(s,(e=>{let n="";e.on("data",(e=>{n+=e})),e.on("end",(()=>{r(n)}))}));c.on("error",(e=>{console.log("Error: ",e.message),t(e)})),c.write(o),c.end()})))(r,i);console.log("上传完成->",e),200===e.code&&console.log(e.data.msg)}catch(e){console.error(`错误: ${e}`)}};const d="vite-source-maps",h="source-maps";e.ErrorReport=class{options;reportApi;vueExample;packingMethod;constructor(e){this.options=e,this.reportApi=e.reportApi,this.vueExample=e.vue,this.packingMethod=e.packingMethod,console.log("项目分类---",e.module),this.init()}init(){this.formatErrorInfo(),this.vueErrorHandler(),this.resourceErrorHandler()}formatErrorInfo(){i.report.subscribe((e=>{console.log("TraceKit格式化后错误信息=",e);const{message:n,stack:r}=e||{};if(!r?.length||!n)return console.log("没有stack信息、不使用TraceKit处理错误。"),!1;const t={column:r[0].column,line:r[0].line,url:r[0].url,func:r[0].func},o=c(this.packingMethod,3,n,t);this.reportViaImg(o)}))}reportViaImg(e){const n=new Image(1,1),r=this.reportApi;n.src=r+JSON.stringify(e)}vueErrorHandler(){this.vueExample.config.errorHandler=function(e,n,r){try{console.log("-----vue-error",e,n,r),i.report(e)}catch(e){console.error("vue-errorHandler错误:",e)}}}async resourceStatus(e){try{const n=await fetch(e);return{status:n.status,statusText:n.statusText}}catch(e){console.error("fetct请求资源,错误捕获:",e)}}resourceErrorHandler(){window.addEventListener("error",(async e=>{const n=e.target;let r;if(n instanceof HTMLImageElement?r=n.src:n instanceof HTMLAnchorElement&&(r=n.href),r){console.log("-----js-资源错误",e);const t=n.baseURI||"",o=new URL(r),i=this.createResourceErrorObject(n,o,t,r),s=`资源错误:在[${i.routePath}]路由中发现,值为[${i.path}]`;this.reportViaImg(c(this.packingMethod,2,s,i))}else console.log("非资源加载错误",e)}),!0)}createResourceErrorObject(e,n,r,t){return{resourceType:e instanceof HTMLImageElement?"img":e.localName,url:t,origin:n.origin,path:n.pathname,routePath:r.split("#")[1]||""}}jsError(){window.onerror=(e,n,r,t,o)=>{console.log("js-执行错误"),console.log("🚀🚀 ~ file: errorReport.js:173 ~ jsError ~ msg, url, line, col, error:",e,n,r,t,o)}}promiseError(){window.addEventListener("unhandledrejection",(e=>{console.log("promise错误:",e)}),!0)}},e.SourceMapUploaderWebpack=class{options;constructor(e={uploadURL:"",enable:!1}){this.options=e}apply(e){this.options.enable||"production"===e.options.mode&&e.hooks.done.tap("SourceMapUploaderWebpack",(async e=>{try{const{jsmapsDir:e,getJsmaps:n}=new p("webpack"),r=await n(e);m(r,e,this.options.uploadURL,h)}catch(e){throw console.error(`Error uploading source maps: ${e.message}`),e}}))}},e.deepClone=n,e.formatErrorDatas=c,e.sourceMapUploaderVite=(e={uploadURL:"",enable:!1})=>({name:"source-map-uploader-vite",apply:"build",async closeBundle(){if(e.enable)return;const{outputPath:n,jsmapsDir:r,getJsmaps:t,moveJsMaps:o}=new p("vite"),i=await t(n);o(i,n,r),m(i,n,e.uploadURL,d)}}),e.test="=======> typescript plugin-zip-pack..."}));