-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.ts
486 lines (460 loc) · 14.6 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/**
* 梅沙科技前端监控脚本 - MeishaFEWatch v1.0.2
* Author: iampomelo <iampomelo@foxmail.com>
* Copyright (c) 2017 Meisha Technology
*/
declare const define: any;
(function (root, factory) {
if (typeof exports === 'object' && typeof module === 'object') {
module.exports = factory();
}
else if (typeof define === 'function' && define.amd) {
define([], factory);
}
else if (typeof exports === 'object') {
exports['MeishaWatch'] = factory();
}
else {
root['MeishaWatch'] = factory();
}
})(window, function () {
const env = {
wechat: !!navigator.userAgent.toLowerCase().match(/MicroMessenger/i),
iOS: !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
Android: !!navigator.userAgent.match(/Android/i),
dev: /127.0.0.1|192.168|localhost/.test(window.location.host)
};
interface Settings {
isReport: boolean; // 是否上报信息
reportURL: string; // 接收错误信息接口的URL
projectId: string; // 项目id
outTime: Number; // 超时时长
}
class MeishaWatch {
private settings: Settings = {
isReport: true,
reportURL: '',
projectId: '',
outTime: 1000
}; // 配置选项
private __logs: object[] = []; // 实际的记录
private logs: object[]; // 追踪的记录
private user: any = ''; // 用户信息
private uniqueId: string = geneUniqueId(); // 本次访问的id
private timer: any = null; // 定时器id
private reportTimes: number = 0; // 已经上报的次数
private isFirstReport: boolean = true; // 是否首次上报,只有首次上报会上报performance
constructor() {
Object.defineProperty(this, 'logs', {
value: [],
configurable: true,
enumerable: true,
writable: true
});
Object.defineProperty(this, 'logs', {
get() {
return this.__logs;
},
set(value) {
this.__logs = value;
if (value.length) {
this.checkLogs();
}
}
});
this.agentConsole();
this.agentAJAX();
this.configSender();
this.configListener();
try {
let logs = JSON.parse(window.localStorage.getItem('_msLogs'));
if (this.isArray(logs)) this.logs = logs;
} catch (error) {
}
}
init(settings: Settings): void {
this.settings = settings;
}
/**
* 收集console打印的记录
*/
agentConsole(): void {
const methodList: string[] = ['error'];
methodList.forEach(type => {
const method = console[type];
console[type] = (...args) => {
if (args.length && args[0] !== '[MeishaWatch Console]') {
this.logs = [...this.logs, ...[{
msg: args.map(v => {
return (typeof v === 'object') ? JSON.stringify(decycle(v, undefined)) : v;
}).join(','),
url: encodeURIComponent(window.location.href),
type,
createTime: Date.now()
}]];
// 每新增一条log,更新localstorage的_msLogs
if (this.settings.isReport) setLogsToLocalStorage(this.logs);
}
method.apply(console, args);
};
});
}
/**
* 收集AJAX请求错误信息
*/
agentAJAX(): void {
const msw = this;
const open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
const req = this;
const args = [].slice.call(arguments), method = args[0], url = args[1];
const onreadystatechange = req.onreadystatechange || function () {
};
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status >= 400) {
msw.logs = [...msw.logs, ...[{
msg: `${method} ${url} ${req.status}`,
url: encodeURIComponent(window.location.href),
type: 'error'
}]];
}
return onreadystatechange.apply(req, arguments);
};
return open.apply(req, args);
};
}
/**
* 收集全局错误信息
*/
configListener(): void {
window.onerror = (msg, url, line, col, error) => {
let errMsg: any = msg;
if (error && error.stack) {
errMsg = processStackMsg(error);
}
this.logs = [...this.logs, ...[{
msg: encodeURIComponent(errMsg.substr(0, 500)),
url: encodeURIComponent(window.location.href),
type: 'error',
line,
col,
createTime: Date.now()
}]];
// 每新增一条log,更新localstorage的_msLogs
if (this.settings.isReport) setLogsToLocalStorage(this.logs);
};
}
/**
* 发送性能和错误信息至后端
*/
configSender(): void {
window.addEventListener('load', () => {
this.report(true);
}, false);
}
/**
* 设置用户信息
* @param user
*/
public setUser(user: any): void {
this.user = user;
}
/**
* 发送请求,错误上报
* @param async 是否异步请求
*/
public report(async: boolean = true): void {
if (this.settings) {
let {reportURL, projectId, isReport = true, outTime} = this.settings;
if (isReport && this.reportTimes < 20) {
if (reportURL && projectId) {
const performance = window.performance;
const times = {
dns: -1,
tcp: -1,
ttfb: -1,
trans: -1,
dom: -1,
res: -1,
firstbyte: -1,
fpt: -1,
tti: -1,
ready: -1,
load: -1,
};
if (performance) {
const t = performance.timing;
times.dns = t.domainLookupEnd - t.domainLookupStart;
times.tcp = t.connectEnd - t.connectStart;
times.ttfb = t.responseStart - t.requestStart;
times.trans = t.responseEnd - t.responseStart;
times.dom = t.domInteractive - t.responseEnd;
times.res = t.loadEventStart - t.domContentLoadedEventEnd;
times.firstbyte = t.responseStart - t.domainLookupStart;
times.fpt = t.responseEnd - t.fetchStart;
times.tti = t.domInteractive - t.fetchStart;
times.ready = t.domContentLoadedEventEnd - t.fetchStart;
times.load = t.loadEventStart - t.fetchStart;
}
const user = (isType(this.user, 'Number') || isType(this.user, 'String')) ? this.user : JSON.stringify(this.user);
const logs = JSON.stringify(decycle(this.logs.slice(), undefined));
const httpHost = window.location.host;
const requestUri = window.location.pathname;
const ua = window.navigator && window.navigator.userAgent;
let params: any = {
project: projectId,
httpHost,
requestUri,
logs,
user,
uniqueId: this.uniqueId,
ua
};
if (this.isFirstReport) {
params.times = JSON.stringify(times);
this.isFirstReport = false;
}
try {
AJAX(reportURL, 'POST', params, async, () => {
this.logs = [];
// 上报后清空当前缓存的_msLogs
window.localStorage && window.localStorage.removeItem('_msLogs');
}, () => {
}, outTime);
} catch (e) {
} finally {
this.reportTimes++;
}
}
}
}
}
/**
* 发送请求,错误上报
* @param async 是否异步请求
*/
public reportPageTime(pageName: string, pageTime: number): void {
if (this.settings) {
let {reportURL, projectId, isReport = true} = this.settings;
if (isReport) {
if (reportURL && projectId) {
const user = (isType(this.user, 'Number') || isType(this.user, 'String')) ? this.user : JSON.stringify(this.user);
const httpHost = window.location.host;
const requestUri = window.location.pathname;
const ua = window.navigator && window.navigator.userAgent;
const pageParams = JSON.stringify({
pageName,
pageTime
})
try {
AJAX(reportURL, 'POST', {
project: projectId,
httpHost,
requestUri,
user,
uniqueId: this.uniqueId,
ua,
pageParams
}, true, () => {
}, () => {
}, 0);
} catch (e) {
} finally {
}
}
}
}
}
/**
* Vue插件调用
* @returns {object}
*/
public useVue(): object {
const msw = this;
return {
install(Vue): void {
const ver: string[] = Vue.version && Vue.version.split('.') || [];
if (+ver[0] >= 2 && +ver[1] >= 2) {
Vue.config.errorHandler = (err, vm, info) => {
console.error('[MeishaWatch Console]', err);
let errMsg: string = err ? (err.stack ? processStackMsg(err) : err) : '';
if (info) {
errMsg = `[Info: ${info}]->${errMsg}`;
}
if (vm && vm.$options && vm.$options.name) {
errMsg = `[Component Name: ${vm.$options.name}]->${errMsg}`;
}
msw.logs = [...msw.logs, ...[{
msg: errMsg,
url: encodeURIComponent(window.location.href),
type: 'error',
createTime: Date.now()
}]];
// 每新增一条log,更新localstorage的_msLogs
if (msw.settings.isReport) setLogsToLocalStorage(msw.logs);
};
}
if (getQueryString('devtools')) {
Vue.config.devtools = true;
}
}
};
}
checkLogs(): void {
clearTimeout(this.timer);
if (this.logs.length >= 5) {
this.report();
} else {
this.timer = setTimeout(this.report, 3000);
}
}
isArray(o): Boolean {
return Object.prototype.toString.call(o).slice(8, -1) === 'Array';
}
}
/**
* 格式化错误信息
* @param error
* @returns {string}
*/
function processStackMsg(error): string {
let stack: string = error.stack
.replace(/\n/gi, '')
.split(/\bat\b/)
.slice(0, 9)
.join('@')
.replace(/\?[^:]+/gi, '');
const msg: string = error.toString();
if (stack.indexOf(msg) < 0) {
stack = msg + '@' + stack;
}
return stack;
}
/**
* 生成唯一的id
* @returns {string}
*/
function geneUniqueId(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
/**
* 获取url参数
* @param param 参数名
* @returns {string}
*/
function getQueryString(param: string): string {
const r = window.location.search.substr(1).match(new RegExp('(^|&)' + param + '=([^&]*)(&|$)', 'i'));
return r ? decodeURI(r[2]) : '';
}
/**
* 将对象转化为url参数字符串
* @param obj
* @returns {string}
*/
function toDataString(obj: object): string {
let str: string = '';
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
str += '&' + prop + '=' + obj[prop];
}
}
return str.slice(1);
}
/**
* 简单的AJAX
* @param url 请求地址
* @param method 请求方法
* @param data 请求参数
* @param async 是否异步请求(默认为true)
* @param successCb 成功回调
* @param errorCb 错误回调
* @param outTime 超时时长
* @constructor
*/
function AJAX(url: string, method: string, data: object, async: boolean = true, successCb, errorCb, outTime: Number): void {
let isTimeOut = false; // 默认没超时
const xhr = new XMLHttpRequest();
let timer = setTimeout(() => {
isTimeOut = true;
xhr.abort();
}, outTime);
xhr.onreadystatechange = () => {
if (isTimeOut) {
return;
};
clearTimeout(timer);
if (xhr.readyState === 4) {
((xhr.status === 200) ? successCb : errorCb)(JSON.parse(xhr.responseText));
}
};
xhr.open(method, method.toUpperCase() === 'GET' ? (url + '?' + toDataString(data)) : url, async);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(toDataString(data));
}
/**
* 判断val是否为type类型的值
* @param val
* @param type 可能的值为Function, Object, Array, Number, String, RegExp, Null, Undefined, Boolean, Symbol, Date等
* @returns {boolean}
*/
function isType(val: any, type: string): boolean {
var toString = Object.prototype.toString;
if (type === 'Number' && (val !== val)) {
return false;
}
return toString.call(val).replace(/.*\s(.*)]$/, '$1') === type;
}
/**
* 去除循环引用
* @param object 待处理的对象
* @param replacer 对对象值遍历处理的方法
* @returns {object} 去除循环引用的对象
*/
function decycle(object: object, replacer: ((value: any) => any) | undefined): object {
const obj2Path: WeakMap<any, string> = new WeakMap();
return (function derez(value: any, path: string) {
let oldPath: string;
let newObj: object;
if (replacer !== undefined) {
value = replacer(value);
}
if (typeof value === 'object' && value !== null &&
!(value instanceof Boolean) &&
!(value instanceof Date) &&
!(value instanceof Number) &&
!(value instanceof RegExp) &&
!(value instanceof String)) {
oldPath = obj2Path.get(value);
if (oldPath !== undefined) {
return {
$ref: oldPath
};
}
obj2Path.set(value, path);
if (Array.isArray(value)) {
newObj = value.map((v, i) => {
return derez(v, path + '[' + i + ']');
});
} else {
newObj = {};
Object.getOwnPropertyNames(value).forEach(key => {
newObj[key] = derez(value[key], path + '[' + key + ']');
});
}
return newObj;
}
return value;
}(object, '$'));
}
/**
* 将log存储到localStorage中
* @param logs
*/
function setLogsToLocalStorage(logs: Array<object>): any {
window.localStorage && logs.length && window.localStorage.setItem('_msLogs', JSON.stringify(logs));
}
return new MeishaWatch();
});