spy-client 2.1.15 → 2.2.1

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.
Files changed (44) hide show
  1. package/.travis.yml +7 -4
  2. package/AGENTS.md +132 -0
  3. package/README.md +27 -19
  4. package/dist/head/base.d.ts +27 -26
  5. package/dist/head/error.d.ts +6 -6
  6. package/dist/head/observer.d.ts +5 -5
  7. package/dist/head/whitescreen.d.ts +6 -6
  8. package/dist/lib/data.d.ts +6 -6
  9. package/dist/lib/huffman.d.ts +9 -9
  10. package/dist/lib/interface.d.ts +209 -209
  11. package/dist/lib/spyHeadInterface.d.ts +36 -36
  12. package/dist/lib/util.d.ts +22 -22
  13. package/dist/module/fid.d.ts +15 -15
  14. package/dist/module/layoutShift.d.ts +18 -18
  15. package/dist/module/lcp.d.ts +17 -17
  16. package/dist/module/longtask.d.ts +46 -46
  17. package/dist/module/memory.d.ts +11 -11
  18. package/dist/module/navigatorInfo.d.ts +9 -9
  19. package/dist/module/resource.d.ts +39 -39
  20. package/dist/module/timing.d.ts +11 -11
  21. package/dist/module/tti.d.ts +19 -19
  22. package/dist/spy-client-basic.d.ts +118 -118
  23. package/dist/spy-client-basic.esm.js +298 -298
  24. package/dist/spy-client-basic.iife.js +298 -298
  25. package/dist/spy-client-basic.iife.min.js +1 -1
  26. package/dist/spy-client-basic.js +298 -298
  27. package/dist/spy-client-basic.min.js +1 -1
  28. package/dist/spy-client-basic.mjs +298 -298
  29. package/dist/spy-client.d.ts +32 -32
  30. package/dist/spy-client.esm.js +1430 -1423
  31. package/dist/spy-client.iife.js +1430 -1423
  32. package/dist/spy-client.iife.min.js +1 -1
  33. package/dist/spy-client.js +1430 -1423
  34. package/dist/spy-client.min.js +1 -1
  35. package/dist/spy-client.mjs +1430 -1423
  36. package/dist/spy-head.d.ts +6 -6
  37. package/dist/spy-head.js +359 -358
  38. package/dist/spy-head.min.js +1 -1
  39. package/dist/spy-local-cache.d.ts +18 -18
  40. package/dist/spy-local-cache.js +718 -711
  41. package/dist/spy-local-cache.min.js +1 -1
  42. package/package.json +26 -73
  43. package/test-results/.last-run.json +4 -0
  44. package/karma.conf.js +0 -111
@@ -1,4 +1,4 @@
1
- /*! *****************************************************************************
1
+ /******************************************************************************
2
2
  Copyright (c) Microsoft Corporation.
3
3
 
4
4
  Permission to use, copy, modify, and/or distribute this software for any
@@ -12,16 +12,18 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
12
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
13
  PERFORMANCE OF THIS SOFTWARE.
14
14
  ***************************************************************************** */
15
- /* global Reflect, Promise */
15
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
16
16
 
17
17
  var extendStatics = function(d, b) {
18
18
  extendStatics = Object.setPrototypeOf ||
19
19
  ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
21
21
  return extendStatics(d, b);
22
22
  };
23
23
 
24
24
  function __extends(d, b) {
25
+ if (typeof b !== "function" && b !== null)
26
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
25
27
  extendStatics(d, b);
26
28
  function __() { this.constructor = d; }
27
29
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
@@ -36,1454 +38,1459 @@ var __assign = function() {
36
38
  return t;
37
39
  };
38
40
  return __assign.apply(this, arguments);
41
+ };
42
+
43
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
44
+ var e = new Error(message);
45
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
39
46
  };
40
47
 
41
- /**
42
- * @file utils
43
- * @author kaivean
44
- */
45
- function assign() {
46
- var args = [];
47
- for (var _i = 0; _i < arguments.length; _i++) {
48
- args[_i] = arguments[_i];
49
- }
50
- var __assign = Object.assign || function __assign(t) {
51
- for (var s = void 0, i = 1, n = arguments.length; i < n; i++) {
52
- // eslint-disable-next-line prefer-rest-params
53
- s = arguments[i];
54
- for (var p in s) {
55
- if (Object.prototype.hasOwnProperty.call(s, p)) {
56
- t[p] = s[p];
57
- }
58
- }
59
- }
60
- return t;
61
- };
62
- return __assign.apply(this, args);
63
- }
64
- function getUrlInfoFromURL(url) {
65
- if (URL && url) {
66
- try {
67
- var obj = new URL(url);
68
- if (obj.host !== undefined) {
69
- return {
70
- protocol: obj.protocol,
71
- host: obj.host,
72
- pathname: obj.pathname,
73
- ext: '',
74
- };
75
- }
76
- }
77
- catch (e) {
78
- console.error(e);
79
- }
80
- }
81
- return;
82
- }
83
- function getUrlInfo(url) {
84
- var info = getUrlInfoFromURL(url);
85
- if (!info) {
86
- var parser = document.createElement('a');
87
- parser.href = url;
88
- info = {
89
- protocol: parser.protocol,
90
- host: parser.host || location.host,
91
- pathname: parser.pathname,
92
- ext: '',
93
- };
94
- }
95
- var split = info.pathname.split('.');
96
- info.ext = split[split.length - 1];
97
- return info;
98
- }
99
- function f$1(n) {
100
- return +n.toFixed(1);
101
- }
102
- function getResTiming(t) {
103
- return {
104
- wait: f$1(t.domainLookupStart - (t.navigationStart || t.fetchStart || t.startTime)),
105
- dns: f$1(t.domainLookupEnd - t.domainLookupStart),
106
- connect: f$1(t.connectEnd - t.connectStart),
107
- req: f$1(t.responseStart - t.requestStart),
108
- res: f$1(t.responseEnd - t.responseStart),
109
- };
110
- }
111
- function getxpath(el) {
112
- if (!el) {
113
- return { xpath: '' };
114
- }
115
- var xpath = [];
116
- while (el && el.nodeType === 1 && el !== el.parentNode) {
117
- var t = el.tagName.toLowerCase();
118
- if (el.getAttribute('id')) {
119
- t += '[#' + el.getAttribute('id') + ']';
120
- }
121
- else if (el.classList && el.classList.length) {
122
- t += '[.' + el.classList[el.classList.length - 1] + ']';
123
- }
124
- xpath.push(t);
125
- if (el === document.body) {
126
- break;
127
- }
128
- el = el.parentNode; // 修复缺陷检查
129
- }
130
- return {
131
- xpath: xpath.join('<'),
132
- };
48
+ /**
49
+ * @file utils
50
+ * @author kaivean
51
+ */
52
+ function assign() {
53
+ var args = [];
54
+ for (var _i = 0; _i < arguments.length; _i++) {
55
+ args[_i] = arguments[_i];
56
+ }
57
+ var __assign = Object.assign || function __assign(t) {
58
+ for (var s = void 0, i = 1, n = arguments.length; i < n; i++) {
59
+ // eslint-disable-next-line prefer-rest-params
60
+ s = arguments[i];
61
+ for (var p in s) {
62
+ if (Object.prototype.hasOwnProperty.call(s, p)) {
63
+ t[p] = s[p];
64
+ }
65
+ }
66
+ }
67
+ return t;
68
+ };
69
+ return __assign.apply(null, args);
70
+ }
71
+ function getUrlInfoFromURL(url) {
72
+ if (URL && url) {
73
+ try {
74
+ var obj = new URL(url);
75
+ if (obj.host !== undefined) {
76
+ return {
77
+ protocol: obj.protocol,
78
+ host: obj.host,
79
+ pathname: obj.pathname,
80
+ ext: '',
81
+ };
82
+ }
83
+ }
84
+ catch (e) {
85
+ console.error(e);
86
+ }
87
+ }
88
+ return;
89
+ }
90
+ function getUrlInfo(url) {
91
+ var info = getUrlInfoFromURL(url);
92
+ if (!info) {
93
+ var parser = document.createElement('a');
94
+ parser.href = url;
95
+ info = {
96
+ protocol: parser.protocol,
97
+ host: parser.host || location.host,
98
+ pathname: parser.pathname,
99
+ ext: '',
100
+ };
101
+ }
102
+ var split = info.pathname.split('.');
103
+ info.ext = split[split.length - 1];
104
+ return info;
105
+ }
106
+ function f$1(n) {
107
+ return +n.toFixed(1);
108
+ }
109
+ function getResTiming(t) {
110
+ return {
111
+ wait: f$1(t.domainLookupStart - (t.navigationStart || t.fetchStart || t.startTime)),
112
+ dns: f$1(t.domainLookupEnd - t.domainLookupStart),
113
+ connect: f$1(t.connectEnd - t.connectStart),
114
+ req: f$1(t.responseStart - t.requestStart),
115
+ res: f$1(t.responseEnd - t.responseStart),
116
+ };
117
+ }
118
+ function getxpath(el) {
119
+ if (!el) {
120
+ return { xpath: '' };
121
+ }
122
+ var xpath = [];
123
+ while (el && el.nodeType === 1 && el !== el.parentNode) {
124
+ var t = el.tagName.toLowerCase();
125
+ if (el.getAttribute('id')) {
126
+ t += '[#' + el.getAttribute('id') + ']';
127
+ }
128
+ else if (el.classList && el.classList.length) {
129
+ t += '[.' + el.classList[el.classList.length - 1] + ']';
130
+ }
131
+ xpath.push(t);
132
+ if (el === document.body) {
133
+ break;
134
+ }
135
+ el = el.parentNode; // 修复缺陷检查
136
+ }
137
+ return {
138
+ xpath: xpath.join('<'),
139
+ };
133
140
  }
134
141
 
135
- /**
136
- * @file SpyClient
137
- * @author kaivean
138
- */
139
- var defaultLogServer = 'https://sp1.baidu.com/5b1ZeDe5KgQFm2e88IuM_a/mwb2.gif?';
140
- // 基础版本兼容非浏览器环境
141
- var ver = navigator && navigator.userAgent ? navigator.userAgent.toLowerCase().match(/cpu iphone os (.*?)_/) : '';
142
- var isLtIos14 = ver && ver[2] && (+ver[2] < 14);
143
- function err(msg) {
144
- console.error("[SpyClient_log]".concat(msg));
145
- // throw new Error(msg);
146
- }
147
- function stringify(obj) {
148
- return Object.keys(obj).map(function (key) {
149
- var value = obj[key];
150
- if (typeof value === 'undefined') {
151
- value = '';
152
- }
153
- else if (typeof value !== 'string') {
154
- value = JSON.stringify(value);
155
- }
156
- return encodeURIComponent(key) + '=' + encodeURIComponent(value);
157
- }).join('&');
158
- }
159
- function isArray(arr) {
160
- return Object.prototype.toString.call(arr) === '[object Array]';
161
- }
162
- var SpyClient$1 = /** @class */ (function () {
163
- function SpyClient(option) {
164
- this.sample = {};
165
- this.markCache = {};
166
- if (!option.pid) {
167
- throw new Error('pid is required');
168
- }
169
- this.option = {
170
- pid: option.pid,
171
- lid: option.lid,
172
- check: option.check !== false,
173
- sample: option.sample,
174
- localCache: option.localCache,
175
- logServer: option.logServer || defaultLogServer,
176
- };
177
- }
178
- SpyClient.prototype.handle = function (logItem) {
179
- if (!this.check(logItem)) {
180
- return;
181
- }
182
- logItem = assign({
183
- pid: this.option.pid,
184
- lid: this.option.lid,
185
- ts: Date.now(),
186
- group: 'common',
187
- }, logItem);
188
- if (this.option.localCache) {
189
- this.option.localCache.addLog(logItem);
190
- }
191
- // 当前api设置了抽样,
192
- if (typeof logItem.sample === 'number') {
193
- if (Math.random() > logItem.sample) {
194
- return;
195
- }
196
- }
197
- else if (typeof this.option.sample === 'number' && Math.random() > this.option.sample) { // 否则,用全局抽样
198
- return;
199
- }
200
- delete logItem.sample;
201
- return logItem;
202
- };
203
- SpyClient.prototype.send = function (data, post) {
204
- if (post === void 0) { post = false; }
205
- var logItems = isArray(data) ? data : [data];
206
- var postData = [];
207
- for (var _i = 0, logItems_1 = logItems; _i < logItems_1.length; _i++) {
208
- var logItem = logItems_1[_i];
209
- logItem = this.handle(logItem);
210
- if (!logItem) {
211
- continue;
212
- }
213
- postData.push(logItem);
214
- // 期望通过post方式上传日志
215
- if (post) {
216
- continue;
217
- }
218
- var url = this.option.logServer + stringify(logItem);
219
- this.request(url);
220
- }
221
- if (post) {
222
- this.sendPost(postData);
223
- }
224
- };
225
- SpyClient.prototype.check = function (query) {
226
- if (!this.option.check) {
227
- return true;
228
- }
229
- var types = ['perf', 'except', 'dist', 'count'];
230
- if (types.indexOf(query.type) === -1) {
231
- err('type only is one of ' + types.join(', '));
232
- return false;
233
- }
234
- if (query.group && query.group.length > 30) {
235
- err('group length execeeds 30');
236
- return false;
237
- }
238
- var simpleReg = /^[a-zA-Z0-9-_]{0,30}$/;
239
- if (query.type === 'except') {
240
- if (!(typeof query.info.msg === 'string' && query.info.msg.length)) {
241
- err('info.msg field must be not empty and is String');
242
- return false;
243
- }
244
- }
245
- else {
246
- for (var _i = 0, _a = Object.keys(query.info); _i < _a.length; _i++) {
247
- var infoKey = _a[_i];
248
- if (!simpleReg.test(infoKey)) {
249
- err("info.".concat(infoKey, " is unexpected. ")
250
- + 'Length must be not more than 30. '
251
- + 'Supported chars: a-zA-Z0-9-_');
252
- return false;
253
- }
254
- var infoVal = query.info[infoKey];
255
- if (query.type === 'dist') {
256
- if (infoVal.length > 30) {
257
- err("info.".concat(infoKey, " value length execeeds 30 when type == 'dist'"));
258
- return false;
259
- }
260
- }
261
- else if (typeof infoVal !== 'number') {
262
- err("info.".concat(infoKey, " value must be number"));
263
- return false;
264
- }
265
- }
266
- }
267
- if (query.dim) {
268
- for (var _b = 0, _c = Object.keys(query.dim); _b < _c.length; _b++) {
269
- var dimKey = _c[_b];
270
- if (!simpleReg.test(dimKey)) {
271
- err("dim key [".concat(dimKey, "] is unexpected. ")
272
- + 'Length must be not more than 30. '
273
- + 'Supported chars: a-zA-Z0-9-_');
274
- return false;
275
- }
276
- var dimVal = query.dim[dimKey];
277
- if (!/^[a-zA-Z0-9\-_\*\.\s\/#\+@\&\u4e00-\u9fa5]{0,30}$/.test(dimVal)) {
278
- err("dim.".concat(dimKey, " value [").concat(dimVal, "] is unexpected. ")
279
- + 'Length must be not more than 30. '
280
- + 'Supported chars: a-zA-Z0-9-_*. /#+@& and Chinese');
281
- return false;
282
- }
283
- }
284
- }
285
- return true;
286
- };
287
- /**
288
- *
289
- * @param option 配置
290
- */
291
- SpyClient.prototype.sendPerf = function (option) {
292
- this.send(assign({
293
- type: 'perf',
294
- }, option));
295
- };
296
- /**
297
- *
298
- * @param option 错误配置项
299
- */
300
- SpyClient.prototype.sendExcept = function (option) {
301
- this.send(assign({
302
- type: 'except',
303
- }, option));
304
- };
305
- /**
306
- *
307
- * @param option 配置
308
- */
309
- SpyClient.prototype.sendDist = function (option) {
310
- this.send(assign({
311
- type: 'dist',
312
- }, option));
313
- };
314
- /**
315
- *
316
- * @param option 配置
317
- */
318
- SpyClient.prototype.sendCount = function (option) {
319
- this.send(assign({
320
- type: 'count',
321
- }, option));
322
- };
323
- /**
324
- *
325
- * @param e 错误实例
326
- * @param option 错误配置项
327
- */
328
- SpyClient.prototype.sendExceptForError = function (e, option) {
329
- var newOpt = assign({}, option);
330
- newOpt.info = assign({}, option.info || {}, {
331
- msg: e.message,
332
- stack: e.stack,
333
- });
334
- this.sendExcept(newOpt);
335
- };
336
- SpyClient.prototype.startMark = function (sign) {
337
- this.markCache[sign] = {
338
- start: Date.now(),
339
- };
340
- };
341
- SpyClient.prototype.endMark = function (sign) {
342
- if (this.markCache[sign]) {
343
- this.markCache[sign].total = Date.now() - this.markCache[sign].start;
344
- return this.markCache[sign].total;
345
- }
346
- return 0;
347
- };
348
- SpyClient.prototype.clearMark = function (sign) {
349
- if (this.markCache[sign]) {
350
- delete this.markCache[sign];
351
- }
352
- };
353
- SpyClient.prototype.getAllMark = function () {
354
- var ret = {};
355
- for (var _i = 0, _a = Object.keys(this.markCache); _i < _a.length; _i++) {
356
- var sign = _a[_i];
357
- ret[sign] = this.markCache[sign].total;
358
- }
359
- return ret;
360
- };
361
- SpyClient.prototype.clearAllMark = function () {
362
- this.markCache = {};
363
- };
364
- /**
365
- * sendPost能以post请求发送,可以承接多个日志项,上报内容size可以提升,但没有前端校验
366
- * send(data, true) 也能以post请求发送,但是会有严格校验
367
- * 要求:发送的多条日志必须是同一个pid,同一类型type,同一分组group
368
- * @param data 日志项或者日志项数组
369
- */
370
- SpyClient.prototype.sendPost = function (data) {
371
- var logItems = isArray(data) ? data : [data];
372
- var first = logItems[0];
373
- // 需要在页面暴漏出来pid等基本信息,方式调试查看基本信息与兼容目前的监控
374
- var query = {
375
- pid: first.pid,
376
- type: first.type,
377
- group: first.group,
378
- };
379
- var url = this.option.logServer + stringify(query);
380
- this.request(url, data);
381
- };
382
- // 有data时,意味着要用post发送请求
383
- SpyClient.prototype.request = function (url, data) {
384
- if (!(!isLtIos14
385
- && navigator
386
- && navigator.sendBeacon
387
- && navigator.sendBeacon(url, data ? JSON.stringify(data) : undefined))) {
388
- if (data) {
389
- this.fetch(url, data);
390
- }
391
- else {
392
- (new Image()).src = url;
393
- }
394
- }
395
- };
396
- SpyClient.prototype.fetch = function (url, data) {
397
- if (!fetch) {
398
- err('Global fetch method doesn\'t exist');
399
- return;
400
- }
401
- fetch(url, {
402
- method: 'POST',
403
- credentials: 'include',
404
- headers: {
405
- 'Content-Type': 'application/json',
406
- },
407
- body: JSON.stringify(data),
408
- });
409
- };
410
- return SpyClient;
142
+ /**
143
+ * @file SpyClient
144
+ * @author kaivean
145
+ */
146
+ var defaultLogServer = 'https://sp1.baidu.com/5b1ZeDe5KgQFm2e88IuM_a/mwb2.gif?';
147
+ // 基础版本兼容非浏览器环境
148
+ var ver = navigator && navigator.userAgent ? navigator.userAgent.toLowerCase().match(/cpu iphone os (.*?)_/) : '';
149
+ var isLtIos14 = ver && ver[2] && (+ver[2] < 14);
150
+ function err(msg) {
151
+ console.error("[SpyClient_log]".concat(msg));
152
+ // throw new Error(msg);
153
+ }
154
+ function stringify(obj) {
155
+ return Object.keys(obj).map(function (key) {
156
+ var value = obj[key];
157
+ if (typeof value === 'undefined') {
158
+ value = '';
159
+ }
160
+ else if (typeof value !== 'string') {
161
+ value = JSON.stringify(value);
162
+ }
163
+ return encodeURIComponent(key) + '=' + encodeURIComponent(value);
164
+ }).join('&');
165
+ }
166
+ function isArray(arr) {
167
+ return Object.prototype.toString.call(arr) === '[object Array]';
168
+ }
169
+ var SpyClient$1 = /** @class */ (function () {
170
+ function SpyClient(option) {
171
+ this.sample = {};
172
+ this.markCache = {};
173
+ if (!option.pid) {
174
+ throw new Error('pid is required');
175
+ }
176
+ this.option = {
177
+ pid: option.pid,
178
+ lid: option.lid,
179
+ check: option.check !== false,
180
+ sample: option.sample,
181
+ localCache: option.localCache,
182
+ logServer: option.logServer || defaultLogServer,
183
+ };
184
+ }
185
+ SpyClient.prototype.handle = function (logItem) {
186
+ if (!this.check(logItem)) {
187
+ return;
188
+ }
189
+ logItem = assign({
190
+ pid: this.option.pid,
191
+ lid: this.option.lid,
192
+ ts: Date.now(),
193
+ group: 'common',
194
+ }, logItem);
195
+ if (this.option.localCache) {
196
+ this.option.localCache.addLog(logItem);
197
+ }
198
+ // 当前api设置了抽样,
199
+ if (typeof logItem.sample === 'number') {
200
+ if (Math.random() > logItem.sample) {
201
+ return;
202
+ }
203
+ }
204
+ else if (typeof this.option.sample === 'number' && Math.random() > this.option.sample) { // 否则,用全局抽样
205
+ return;
206
+ }
207
+ delete logItem.sample;
208
+ return logItem;
209
+ };
210
+ SpyClient.prototype.send = function (data, post) {
211
+ if (post === void 0) { post = false; }
212
+ var logItems = isArray(data) ? data : [data];
213
+ var postData = [];
214
+ for (var _i = 0, logItems_1 = logItems; _i < logItems_1.length; _i++) {
215
+ var logItem = logItems_1[_i];
216
+ logItem = this.handle(logItem);
217
+ if (!logItem) {
218
+ continue;
219
+ }
220
+ postData.push(logItem);
221
+ // 期望通过post方式上传日志
222
+ if (post) {
223
+ continue;
224
+ }
225
+ var url = this.option.logServer + stringify(logItem);
226
+ this.request(url);
227
+ }
228
+ if (post) {
229
+ this.sendPost(postData);
230
+ }
231
+ };
232
+ SpyClient.prototype.check = function (query) {
233
+ if (!this.option.check) {
234
+ return true;
235
+ }
236
+ var types = ['perf', 'except', 'dist', 'count'];
237
+ if (types.indexOf(query.type) === -1) {
238
+ err('type only is one of ' + types.join(', '));
239
+ return false;
240
+ }
241
+ if (query.group && query.group.length > 30) {
242
+ err('group length execeeds 30');
243
+ return false;
244
+ }
245
+ var simpleReg = /^[a-zA-Z0-9-_]{0,30}$/;
246
+ if (query.type === 'except') {
247
+ if (!(typeof query.info.msg === 'string' && query.info.msg.length)) {
248
+ err('info.msg field must be not empty and is String');
249
+ return false;
250
+ }
251
+ }
252
+ else {
253
+ for (var _i = 0, _a = Object.keys(query.info); _i < _a.length; _i++) {
254
+ var infoKey = _a[_i];
255
+ if (!simpleReg.test(infoKey)) {
256
+ err("info.".concat(infoKey, " is unexpected. ")
257
+ + 'Length must be not more than 30. '
258
+ + 'Supported chars: a-zA-Z0-9-_');
259
+ return false;
260
+ }
261
+ var infoVal = query.info[infoKey];
262
+ if (query.type === 'dist') {
263
+ if (infoVal.length > 30) {
264
+ err("info.".concat(infoKey, " value length execeeds 30 when type == 'dist'"));
265
+ return false;
266
+ }
267
+ }
268
+ else if (typeof infoVal !== 'number') {
269
+ err("info.".concat(infoKey, " value must be number"));
270
+ return false;
271
+ }
272
+ }
273
+ }
274
+ if (query.dim) {
275
+ for (var _b = 0, _c = Object.keys(query.dim); _b < _c.length; _b++) {
276
+ var dimKey = _c[_b];
277
+ if (!simpleReg.test(dimKey)) {
278
+ err("dim key [".concat(dimKey, "] is unexpected. ")
279
+ + 'Length must be not more than 30. '
280
+ + 'Supported chars: a-zA-Z0-9-_');
281
+ return false;
282
+ }
283
+ var dimVal = query.dim[dimKey];
284
+ if (!/^[a-zA-Z0-9\-_\*\.\s\/#\+@\&\u4e00-\u9fa5]{0,30}$/.test(dimVal)) {
285
+ err("dim.".concat(dimKey, " value [").concat(dimVal, "] is unexpected. ")
286
+ + 'Length must be not more than 30. '
287
+ + 'Supported chars: a-zA-Z0-9-_*. /#+@& and Chinese');
288
+ return false;
289
+ }
290
+ }
291
+ }
292
+ return true;
293
+ };
294
+ /**
295
+ *
296
+ * @param option 配置
297
+ */
298
+ SpyClient.prototype.sendPerf = function (option) {
299
+ this.send(assign({
300
+ type: 'perf',
301
+ }, option));
302
+ };
303
+ /**
304
+ *
305
+ * @param option 错误配置项
306
+ */
307
+ SpyClient.prototype.sendExcept = function (option) {
308
+ this.send(assign({
309
+ type: 'except',
310
+ }, option));
311
+ };
312
+ /**
313
+ *
314
+ * @param option 配置
315
+ */
316
+ SpyClient.prototype.sendDist = function (option) {
317
+ this.send(assign({
318
+ type: 'dist',
319
+ }, option));
320
+ };
321
+ /**
322
+ *
323
+ * @param option 配置
324
+ */
325
+ SpyClient.prototype.sendCount = function (option) {
326
+ this.send(assign({
327
+ type: 'count',
328
+ }, option));
329
+ };
330
+ /**
331
+ *
332
+ * @param e 错误实例
333
+ * @param option 错误配置项
334
+ */
335
+ SpyClient.prototype.sendExceptForError = function (e, option) {
336
+ var newOpt = assign({}, option);
337
+ newOpt.info = assign({}, option.info || {}, {
338
+ msg: e.message,
339
+ stack: e.stack,
340
+ });
341
+ this.sendExcept(newOpt);
342
+ };
343
+ SpyClient.prototype.startMark = function (sign) {
344
+ this.markCache[sign] = {
345
+ start: Date.now(),
346
+ };
347
+ };
348
+ SpyClient.prototype.endMark = function (sign) {
349
+ if (this.markCache[sign]) {
350
+ this.markCache[sign].total = Date.now() - this.markCache[sign].start;
351
+ return this.markCache[sign].total;
352
+ }
353
+ return 0;
354
+ };
355
+ SpyClient.prototype.clearMark = function (sign) {
356
+ if (this.markCache[sign]) {
357
+ delete this.markCache[sign];
358
+ }
359
+ };
360
+ SpyClient.prototype.getAllMark = function () {
361
+ var ret = {};
362
+ for (var _i = 0, _a = Object.keys(this.markCache); _i < _a.length; _i++) {
363
+ var sign = _a[_i];
364
+ ret[sign] = this.markCache[sign].total;
365
+ }
366
+ return ret;
367
+ };
368
+ SpyClient.prototype.clearAllMark = function () {
369
+ this.markCache = {};
370
+ };
371
+ /**
372
+ * sendPost能以post请求发送,可以承接多个日志项,上报内容size可以提升,但没有前端校验
373
+ * send(data, true) 也能以post请求发送,但是会有严格校验
374
+ * 要求:发送的多条日志必须是同一个pid,同一类型type,同一分组group
375
+ * @param data 日志项或者日志项数组
376
+ */
377
+ SpyClient.prototype.sendPost = function (data) {
378
+ var logItems = isArray(data) ? data : [data];
379
+ var first = logItems[0];
380
+ // 需要在页面暴漏出来pid等基本信息,方式调试查看基本信息与兼容目前的监控
381
+ var query = {
382
+ pid: first.pid,
383
+ type: first.type,
384
+ group: first.group,
385
+ };
386
+ var url = this.option.logServer + stringify(query);
387
+ this.request(url, data);
388
+ };
389
+ // 有data时,意味着要用post发送请求
390
+ SpyClient.prototype.request = function (url, data) {
391
+ if (!(!isLtIos14
392
+ && navigator
393
+ && navigator.sendBeacon
394
+ && navigator.sendBeacon(url, data ? JSON.stringify(data) : undefined))) {
395
+ if (data) {
396
+ this.fetch(url, data);
397
+ }
398
+ else {
399
+ (new Image()).src = url;
400
+ }
401
+ }
402
+ };
403
+ SpyClient.prototype.fetch = function (url, data) {
404
+ if (!fetch) {
405
+ err('Global fetch method doesn\'t exist');
406
+ return;
407
+ }
408
+ fetch(url, {
409
+ method: 'POST',
410
+ credentials: 'include',
411
+ headers: {
412
+ 'Content-Type': 'application/json',
413
+ },
414
+ body: JSON.stringify(data),
415
+ });
416
+ };
417
+ return SpyClient;
411
418
  }());
412
419
 
413
- /**
414
- * @file FID
415
- * @author kaivean
416
- */
417
- var spyclient$3 = window.__spyHead;
418
- var entryType$3 = 'first-input';
419
- var FID = /** @class */ (function () {
420
- function FID() {
421
- var _this = this;
422
- this.observer = null;
423
- if (!window.PerformanceObserver) {
424
- return;
425
- }
426
- if (spyclient$3 && spyclient$3.entryMap && spyclient$3.entryMap[entryType$3]) {
427
- this.handle(spyclient$3.entryMap[entryType$3]);
428
- }
429
- try {
430
- this.observer = new PerformanceObserver(function (list) {
431
- _this.handle(list.getEntries());
432
- });
433
- this.observer.observe({ entryTypes: [entryType$3] });
434
- }
435
- catch (e) { }
436
- }
437
- FID.prototype.listenFID = function (cb) {
438
- this.cb = cb;
439
- this.callCB();
440
- };
441
- FID.prototype.callCB = function () {
442
- if (this.finalValue !== undefined && this.cb) {
443
- this.cb({ fid: this.finalValue });
444
- }
445
- };
446
- FID.prototype.destroy = function () {
447
- this.observer && this.observer.disconnect();
448
- this.observer = null;
449
- };
450
- FID.prototype.handle = function (entries) {
451
- var lastEntry = entries.pop();
452
- if (lastEntry) {
453
- this.finalValue = lastEntry.duration;
454
- this.callCB();
455
- this.destroy();
456
- }
457
- };
458
- return FID;
420
+ /**
421
+ * @file FID
422
+ * @author kaivean
423
+ */
424
+ var spyclient$3 = window.__spyHead;
425
+ var entryType$3 = 'first-input';
426
+ var FID = /** @class */ (function () {
427
+ function FID() {
428
+ var _this = this;
429
+ this.observer = null;
430
+ if (!window.PerformanceObserver) {
431
+ return;
432
+ }
433
+ if (spyclient$3 && spyclient$3.entryMap && spyclient$3.entryMap[entryType$3]) {
434
+ this.handle(spyclient$3.entryMap[entryType$3]);
435
+ }
436
+ try {
437
+ this.observer = new PerformanceObserver(function (list) {
438
+ _this.handle(list.getEntries());
439
+ });
440
+ this.observer.observe({ entryTypes: [entryType$3] });
441
+ }
442
+ catch (e) { }
443
+ }
444
+ FID.prototype.listenFID = function (cb) {
445
+ this.cb = cb;
446
+ this.callCB();
447
+ };
448
+ FID.prototype.callCB = function () {
449
+ if (this.finalValue !== undefined && this.cb) {
450
+ this.cb({ fid: this.finalValue });
451
+ }
452
+ };
453
+ FID.prototype.destroy = function () {
454
+ this.observer && this.observer.disconnect();
455
+ this.observer = null;
456
+ };
457
+ FID.prototype.handle = function (entries) {
458
+ var lastEntry = entries.pop();
459
+ if (lastEntry) {
460
+ this.finalValue = lastEntry.duration;
461
+ this.callCB();
462
+ this.destroy();
463
+ }
464
+ };
465
+ return FID;
459
466
  }());
460
467
 
461
- /**
462
- * @file LayoutShift
463
- * @author kaivean
464
- */
465
- var spyclient$2 = window.__spyHead;
466
- var entryType$2 = 'layout-shift';
467
- var LayoutShift = /** @class */ (function () {
468
- function LayoutShift() {
469
- var _this = this;
470
- this.observer = null;
471
- this.onceLeave = false;
472
- if (!window.PerformanceObserver) {
473
- return;
474
- }
475
- // 先消费之前的
476
- if (spyclient$2 && spyclient$2.entryMap && spyclient$2.entryMap[entryType$2]) {
477
- this.handle(spyclient$2.entryMap[entryType$2]);
478
- }
479
- try {
480
- this.observer = new PerformanceObserver(function (list) {
481
- _this.handle(list.getEntries());
482
- });
483
- this.observer.observe({ entryTypes: [entryType$2] });
484
- }
485
- catch (e) { }
486
- }
487
- LayoutShift.prototype.listenLayoutShift = function (cb) {
488
- this.cb = cb;
489
- };
490
- LayoutShift.prototype.leave = function () {
491
- if (!this.onceLeave) {
492
- this.onceLeave = true;
493
- this.observer && this.observer.takeRecords && this.observer.takeRecords();
494
- this.finalValue = this.value;
495
- this.callCB();
496
- this.destroy();
497
- }
498
- };
499
- LayoutShift.prototype.callCB = function () {
500
- if (this.finalValue !== undefined && this.cb) {
501
- this.cb({ layoutShift: this.finalValue });
502
- }
503
- };
504
- LayoutShift.prototype.destroy = function () {
505
- this.observer && this.observer.disconnect();
506
- this.observer = null;
507
- };
508
- LayoutShift.prototype.handle = function (entries) {
509
- var _this = this;
510
- entries.map(function (entry) {
511
- // hadRecentInput 如果过去500毫秒内有用户输入,则返回 true, 刚进入页面内500ms,不会认为是layoutShift
512
- if (!entry.hadRecentInput) {
513
- _this.value = (_this.value || 0) + (entry.value || 0);
514
- }
515
- });
516
- };
517
- return LayoutShift;
468
+ /**
469
+ * @file LayoutShift
470
+ * @author kaivean
471
+ */
472
+ var spyclient$2 = window.__spyHead;
473
+ var entryType$2 = 'layout-shift';
474
+ var LayoutShift = /** @class */ (function () {
475
+ function LayoutShift() {
476
+ var _this = this;
477
+ this.observer = null;
478
+ this.onceLeave = false;
479
+ if (!window.PerformanceObserver) {
480
+ return;
481
+ }
482
+ // 先消费之前的
483
+ if (spyclient$2 && spyclient$2.entryMap && spyclient$2.entryMap[entryType$2]) {
484
+ this.handle(spyclient$2.entryMap[entryType$2]);
485
+ }
486
+ try {
487
+ this.observer = new PerformanceObserver(function (list) {
488
+ _this.handle(list.getEntries());
489
+ });
490
+ this.observer.observe({ entryTypes: [entryType$2] });
491
+ }
492
+ catch (e) { }
493
+ }
494
+ LayoutShift.prototype.listenLayoutShift = function (cb) {
495
+ this.cb = cb;
496
+ };
497
+ LayoutShift.prototype.leave = function () {
498
+ if (!this.onceLeave) {
499
+ this.onceLeave = true;
500
+ this.observer && this.observer.takeRecords && this.observer.takeRecords();
501
+ this.finalValue = this.value;
502
+ this.callCB();
503
+ this.destroy();
504
+ }
505
+ };
506
+ LayoutShift.prototype.callCB = function () {
507
+ if (this.finalValue !== undefined && this.cb) {
508
+ this.cb({ layoutShift: this.finalValue });
509
+ }
510
+ };
511
+ LayoutShift.prototype.destroy = function () {
512
+ this.observer && this.observer.disconnect();
513
+ this.observer = null;
514
+ };
515
+ LayoutShift.prototype.handle = function (entries) {
516
+ var _this = this;
517
+ entries.map(function (entry) {
518
+ // hadRecentInput 如果过去500毫秒内有用户输入,则返回 true, 刚进入页面内500ms,不会认为是layoutShift
519
+ if (!entry.hadRecentInput) {
520
+ _this.value = (_this.value || 0) + (entry.value || 0);
521
+ }
522
+ });
523
+ };
524
+ return LayoutShift;
518
525
  }());
519
526
 
520
- /**
521
- * @file 简单的公共数据模块,内部模块之间数据交换
522
- * @author kaivean
523
- */
524
- var data = {};
525
- function setData(key, value) {
526
- data[key] = value;
527
- }
528
- function getData(key) {
529
- return data[key];
527
+ /**
528
+ * @file 简单的公共数据模块,内部模块之间数据交换
529
+ * @author kaivean
530
+ */
531
+ var data = {};
532
+ function setData(key, value) {
533
+ data[key] = value;
534
+ }
535
+ function getData(key) {
536
+ return data[key];
530
537
  }
531
538
 
532
- /**
533
- * @file LCP
534
- * @author kaivean
535
- */
536
- var spyclient$1 = window.__spyHead;
537
- var entryType$1 = 'largest-contentful-paint';
538
- var LCP = /** @class */ (function () {
539
- function LCP() {
540
- var _this = this;
541
- this.observer = null;
542
- if (!window.PerformanceObserver) {
543
- return;
544
- }
545
- if (spyclient$1 && spyclient$1.entryMap && spyclient$1.entryMap[entryType$1]) {
546
- this.handle(spyclient$1.entryMap[entryType$1]);
547
- }
548
- try {
549
- // 仅在 img,image,svg,video,css url, block element with text nodes
550
- this.observer = new PerformanceObserver(function (list) {
551
- _this.handle(list.getEntries());
552
- });
553
- this.observer.observe({ entryTypes: [entryType$1] });
554
- }
555
- catch (e) { }
556
- }
557
- LCP.prototype.listenLCP = function (cb) {
558
- this.cb = cb;
559
- this.callCB();
560
- };
561
- LCP.prototype.callCB = function () {
562
- if (this.finalValue && this.cb) {
563
- this.cb({ lcp: this.finalValue });
564
- }
565
- };
566
- LCP.prototype.load = function () {
567
- this.observer && this.observer.takeRecords && this.observer.takeRecords();
568
- this.finalValue = this.value;
569
- setData('lcp', this.value);
570
- this.callCB();
571
- this.destroy();
572
- };
573
- LCP.prototype.destroy = function () {
574
- this.observer && this.observer.disconnect();
575
- this.observer = null;
576
- };
577
- LCP.prototype.handle = function (entries) {
578
- var _this = this;
579
- entries.map(function (entry) {
580
- _this.value = entry.renderTime || entry.loadTime;
581
- });
582
- };
583
- return LCP;
539
+ /**
540
+ * @file LCP
541
+ * @author kaivean
542
+ */
543
+ var spyclient$1 = window.__spyHead;
544
+ var entryType$1 = 'largest-contentful-paint';
545
+ var LCP = /** @class */ (function () {
546
+ function LCP() {
547
+ var _this = this;
548
+ this.observer = null;
549
+ if (!window.PerformanceObserver) {
550
+ return;
551
+ }
552
+ if (spyclient$1 && spyclient$1.entryMap && spyclient$1.entryMap[entryType$1]) {
553
+ this.handle(spyclient$1.entryMap[entryType$1]);
554
+ }
555
+ try {
556
+ // 仅在 img,image,svg,video,css url, block element with text nodes
557
+ this.observer = new PerformanceObserver(function (list) {
558
+ _this.handle(list.getEntries());
559
+ });
560
+ this.observer.observe({ entryTypes: [entryType$1] });
561
+ }
562
+ catch (e) { }
563
+ }
564
+ LCP.prototype.listenLCP = function (cb) {
565
+ this.cb = cb;
566
+ this.callCB();
567
+ };
568
+ LCP.prototype.callCB = function () {
569
+ if (this.finalValue && this.cb) {
570
+ this.cb({ lcp: this.finalValue });
571
+ }
572
+ };
573
+ LCP.prototype.load = function () {
574
+ this.observer && this.observer.takeRecords && this.observer.takeRecords();
575
+ this.finalValue = this.value;
576
+ setData('lcp', this.value);
577
+ this.callCB();
578
+ this.destroy();
579
+ };
580
+ LCP.prototype.destroy = function () {
581
+ this.observer && this.observer.disconnect();
582
+ this.observer = null;
583
+ };
584
+ LCP.prototype.handle = function (entries) {
585
+ var _this = this;
586
+ entries.map(function (entry) {
587
+ _this.value = entry.renderTime || entry.loadTime || 0;
588
+ });
589
+ };
590
+ return LCP;
584
591
  }());
585
592
 
586
- function filterExcludeLogGifs(entry) {
587
- return entry.name.indexOf('.gif?') < 0;
588
- }
589
- var TTI = /** @class */ (function () {
590
- function TTI() {
591
- this.lastLongTask = 0;
592
- this.observer = null;
593
- this.interval = 5000;
594
- this.filterRequest = filterExcludeLogGifs;
595
- this.observerCallback = this.observerCallback.bind(this);
596
- this.ttiCheck = this.ttiCheck.bind(this);
597
- }
598
- TTI.prototype.check = function () {
599
- return window.PerformanceObserver && performance && performance.timing && performance.timing.navigationStart;
600
- };
601
- TTI.prototype.listenTTI = function (cb, option) {
602
- if (!this.check()) {
603
- return;
604
- }
605
- // 监听获取longtask,持续20s
606
- this.observeLongtask(20000);
607
- this.cb = cb;
608
- option = option || {};
609
- if (option.interval) {
610
- this.interval = option.interval;
611
- }
612
- if (option.filterRequest) {
613
- this.filterRequest = option.filterRequest;
614
- }
615
- };
616
- TTI.prototype.load = function () {
617
- if (!this.check()) {
618
- return;
619
- }
620
- // 每 5 秒检查一次是否符合TTI要求
621
- this.ttiTimer = setInterval(this.ttiCheck, this.interval);
622
- };
623
- TTI.prototype.ttiCheck = function () {
624
- if (!this.cb) {
625
- return;
626
- }
627
- var now = performance.now();
628
- if (now - this.lastLongTask < this.interval) {
629
- // debug('tti 没有达成条件,上次 longTask 离现在差' + (now - this.lastLongTask) + 'ms');
630
- return;
631
- }
632
- var networkSilence = this.getNetworkSilenceAt();
633
- if (networkSilence === false) {
634
- // debug('tti 没有达成条件,网络没有静默');
635
- return;
636
- }
637
- if (now - networkSilence < this.interval) {
638
- // debug('tti 没有达成条件,上次网络请求离现在差' + (now - networkSilence) + 'ms');
639
- return;
640
- }
641
- // debug('tti 达成条件');
642
- clearTimeout(this.ttiTimer);
643
- var tti = this.lastLongTask;
644
- // 没有longtask,就用dom ready时间作为tti,默认是认为dom ready已经绑定好时间,可以交换了
645
- if (!tti) {
646
- tti = performance.timing.domContentLoadedEventEnd - performance.timing.navigationStart;
647
- }
648
- // 停止 long task 获取
649
- this.stopObserveLongTask();
650
- this.cb({
651
- tti: tti,
652
- });
653
- };
654
- TTI.prototype.observerCallback = function (list) {
655
- var entries = list.getEntries();
656
- var lastEntry = entries[entries.length - 1];
657
- // debug('long task (no more than ' + lastEntry.duration + 'ms) detected');
658
- // 最新的longTask完成时间
659
- this.lastLongTask = lastEntry.startTime + lastEntry.duration;
660
- };
661
- TTI.prototype.stopObserveLongTask = function () {
662
- if (this.observer) {
663
- this.observer.disconnect();
664
- this.observer = null;
665
- }
666
- if (this.stopLongTaskTimeoutId) {
667
- clearTimeout(this.stopLongTaskTimeoutId);
668
- }
669
- };
670
- TTI.prototype.getNetworkSilenceAt = function () {
671
- // const now = performance.now();
672
- var resources = performance.getEntriesByType('resource')
673
- .filter(this.filterRequest);
674
- var lastResourceEnd = 0;
675
- for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {
676
- var item = resources_1[_i];
677
- // 还没有responseEnd字段,说明网络请求还未结束
678
- if (!item.responseEnd) {
679
- return false;
680
- }
681
- // 取responseEnd最大值
682
- if (item.responseEnd > lastResourceEnd) {
683
- lastResourceEnd = item.responseEnd;
684
- }
685
- }
686
- return lastResourceEnd;
687
- };
688
- TTI.prototype.observeLongtask = function (timeout) {
689
- this.stopObserveLongTask();
690
- try {
691
- this.observer = new PerformanceObserver(this.observerCallback);
692
- this.observer.observe({
693
- entryTypes: ['longtask'],
694
- });
695
- this.stopLongTaskTimeoutId = setTimeout(this.stopObserveLongTask, timeout);
696
- }
697
- catch (e) { }
698
- };
699
- return TTI;
593
+ function filterExcludeLogGifs(entry) {
594
+ return entry.name.indexOf('.gif?') < 0;
595
+ }
596
+ var TTI = /** @class */ (function () {
597
+ function TTI() {
598
+ this.lastLongTask = 0;
599
+ this.observer = null;
600
+ this.interval = 5000;
601
+ this.filterRequest = filterExcludeLogGifs;
602
+ this.observerCallback = this.observerCallback.bind(this);
603
+ this.ttiCheck = this.ttiCheck.bind(this);
604
+ }
605
+ TTI.prototype.check = function () {
606
+ return window.PerformanceObserver && performance && performance.timing && performance.timing.navigationStart;
607
+ };
608
+ TTI.prototype.listenTTI = function (cb, option) {
609
+ if (!this.check()) {
610
+ return;
611
+ }
612
+ // 监听获取longtask,持续20s
613
+ this.observeLongtask(20000);
614
+ this.cb = cb;
615
+ option = option || {};
616
+ if (option.interval) {
617
+ this.interval = option.interval;
618
+ }
619
+ if (option.filterRequest) {
620
+ this.filterRequest = option.filterRequest;
621
+ }
622
+ };
623
+ TTI.prototype.load = function () {
624
+ if (!this.check()) {
625
+ return;
626
+ }
627
+ // 每 5 秒检查一次是否符合TTI要求
628
+ this.ttiTimer = setInterval(this.ttiCheck, this.interval);
629
+ };
630
+ TTI.prototype.ttiCheck = function () {
631
+ if (!this.cb) {
632
+ return;
633
+ }
634
+ var now = performance.now();
635
+ if (now - this.lastLongTask < this.interval) {
636
+ // debug('tti 没有达成条件,上次 longTask 离现在差' + (now - this.lastLongTask) + 'ms');
637
+ return;
638
+ }
639
+ var networkSilence = this.getNetworkSilenceAt();
640
+ if (networkSilence === false) {
641
+ // debug('tti 没有达成条件,网络没有静默');
642
+ return;
643
+ }
644
+ if (now - networkSilence < this.interval) {
645
+ // debug('tti 没有达成条件,上次网络请求离现在差' + (now - networkSilence) + 'ms');
646
+ return;
647
+ }
648
+ // debug('tti 达成条件');
649
+ clearTimeout(this.ttiTimer);
650
+ var tti = this.lastLongTask;
651
+ // 没有longtask,就用dom ready时间作为tti,默认是认为dom ready已经绑定好时间,可以交换了
652
+ if (!tti) {
653
+ tti = performance.timing.domContentLoadedEventEnd - performance.timing.navigationStart;
654
+ }
655
+ // 停止 long task 获取
656
+ this.stopObserveLongTask();
657
+ this.cb({
658
+ tti: tti,
659
+ });
660
+ };
661
+ TTI.prototype.observerCallback = function (list) {
662
+ var entries = list.getEntries();
663
+ var lastEntry = entries[entries.length - 1];
664
+ // debug('long task (no more than ' + lastEntry.duration + 'ms) detected');
665
+ // 最新的longTask完成时间
666
+ this.lastLongTask = lastEntry.startTime + lastEntry.duration;
667
+ };
668
+ TTI.prototype.stopObserveLongTask = function () {
669
+ if (this.observer) {
670
+ this.observer.disconnect();
671
+ this.observer = null;
672
+ }
673
+ if (this.stopLongTaskTimeoutId) {
674
+ clearTimeout(this.stopLongTaskTimeoutId);
675
+ }
676
+ };
677
+ TTI.prototype.getNetworkSilenceAt = function () {
678
+ // const now = performance.now();
679
+ var resources = performance.getEntriesByType('resource')
680
+ .filter(this.filterRequest);
681
+ var lastResourceEnd = 0;
682
+ for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {
683
+ var item = resources_1[_i];
684
+ // 还没有responseEnd字段,说明网络请求还未结束
685
+ if (!item.responseEnd) {
686
+ return false;
687
+ }
688
+ // 取responseEnd最大值
689
+ if (item.responseEnd > lastResourceEnd) {
690
+ lastResourceEnd = item.responseEnd;
691
+ }
692
+ }
693
+ return lastResourceEnd;
694
+ };
695
+ TTI.prototype.observeLongtask = function (timeout) {
696
+ this.stopObserveLongTask();
697
+ try {
698
+ this.observer = new PerformanceObserver(this.observerCallback);
699
+ this.observer.observe({
700
+ entryTypes: ['longtask'],
701
+ });
702
+ this.stopLongTaskTimeoutId = setTimeout(this.stopObserveLongTask, timeout);
703
+ }
704
+ catch (e) { }
705
+ };
706
+ return TTI;
700
707
  }());
701
708
 
702
- /**
703
- * @file LCP
704
- * @author kaivean
705
- */
706
- var Timing = /** @class */ (function () {
707
- function Timing() {
708
- }
709
- // constructor() {}
710
- Timing.prototype.listenTiming = function (cb) {
711
- if (!window.performance || !window.performance.timing) {
712
- // debug('no performance.timing api');
713
- return;
714
- }
715
- this.cb = cb;
716
- };
717
- Timing.prototype.load = function () {
718
- var _this = this;
719
- setTimeout(function () {
720
- _this.cb && _this.cb(_this.getMetric());
721
- }, 500);
722
- };
723
- Timing.prototype.getMetric = function () {
724
- var metric = {};
725
- var timing = window.performance.timing;
726
- var startTime = timing.navigationStart;
727
- // 基础信息
728
- metric.dns = timing.domainLookupEnd - timing.domainLookupStart;
729
- metric.tcp = timing.connectEnd - timing.connectStart;
730
- metric.request = timing.responseStart - timing.requestStart;
731
- metric.response = timing.responseEnd - timing.responseStart;
732
- // 这是从页面部分数据返回,浏览器开始解析doc元素到最底部的script脚本解析执行完成
733
- // 脚本里触发的异步或绑定了更靠后的事件,不再纳入范围内
734
- metric.parseHtml = timing.domInteractive - timing.domLoading;
735
- // 很多事件绑定是在domContentLoaded事件里的,所以等其结束,一般页面元素的事件绑定好了,用户可以正确交互
736
- // 当然存在在该加载事件之后绑定元素事件情况,但不再此考虑范围内
737
- metric.domReady = timing.domContentLoadedEventEnd - startTime;
738
- metric.loadEventHandle = timing.loadEventEnd - timing.loadEventStart;
739
- // 基本该做的都做完,资源也都加载完成了
740
- // 当然在onload事件处理函数里启动了异步方法,不再纳入范围内
741
- metric.load = timing.loadEventEnd - startTime;
742
- // 浏览器首次绘制与首次内容绘制, ios低版本无getEntriesByType api
743
- if (performance.getEntriesByType) {
744
- var paintEntries = performance.getEntriesByType('paint');
745
- if (paintEntries && paintEntries.length) {
746
- paintEntries.forEach(function (_a) {
747
- var name = _a.name, duration = _a.duration, startTime = _a.startTime;
748
- var time = Math.ceil(duration + startTime);
749
- if (name === 'first-paint') {
750
- metric.fp = time;
751
- }
752
- if (name === 'first-contentful-paint') {
753
- metric.fcp = time;
754
- }
755
- });
756
- }
757
- }
758
- // 端首次绘制与首屏
759
- if (timing.domFirstPaint) {
760
- metric.t7FirstPaint = timing.domFirstPaint - startTime;
761
- }
762
- if (timing.domFirstScreenPaint) {
763
- metric.t7FirstScreen = timing.domFirstScreenPaint - startTime;
764
- }
765
- return metric;
766
- };
767
- return Timing;
709
+ /**
710
+ * @file LCP
711
+ * @author kaivean
712
+ */
713
+ var Timing = /** @class */ (function () {
714
+ function Timing() {
715
+ }
716
+ // constructor() {}
717
+ Timing.prototype.listenTiming = function (cb) {
718
+ if (!window.performance || !window.performance.timing) {
719
+ // debug('no performance.timing api');
720
+ return;
721
+ }
722
+ this.cb = cb;
723
+ };
724
+ Timing.prototype.load = function () {
725
+ var _this = this;
726
+ setTimeout(function () {
727
+ _this.cb && _this.cb(_this.getMetric());
728
+ }, 500);
729
+ };
730
+ Timing.prototype.getMetric = function () {
731
+ var metric = {};
732
+ var timing = window.performance.timing;
733
+ var startTime = timing.navigationStart;
734
+ // 基础信息
735
+ metric.dns = timing.domainLookupEnd - timing.domainLookupStart;
736
+ metric.tcp = timing.connectEnd - timing.connectStart;
737
+ metric.request = timing.responseStart - timing.requestStart;
738
+ metric.response = timing.responseEnd - timing.responseStart;
739
+ // 这是从页面部分数据返回,浏览器开始解析doc元素到最底部的script脚本解析执行完成
740
+ // 脚本里触发的异步或绑定了更靠后的事件,不再纳入范围内
741
+ metric.parseHtml = timing.domInteractive - timing.domLoading;
742
+ // 很多事件绑定是在domContentLoaded事件里的,所以等其结束,一般页面元素的事件绑定好了,用户可以正确交互
743
+ // 当然存在在该加载事件之后绑定元素事件情况,但不再此考虑范围内
744
+ metric.domReady = timing.domContentLoadedEventEnd - startTime;
745
+ metric.loadEventHandle = timing.loadEventEnd - timing.loadEventStart;
746
+ // 基本该做的都做完,资源也都加载完成了
747
+ // 当然在onload事件处理函数里启动了异步方法,不再纳入范围内
748
+ metric.load = timing.loadEventEnd - startTime;
749
+ // 浏览器首次绘制与首次内容绘制, ios低版本无getEntriesByType api
750
+ if (performance.getEntriesByType) {
751
+ var paintEntries = performance.getEntriesByType('paint');
752
+ if (paintEntries && paintEntries.length) {
753
+ paintEntries.forEach(function (_a) {
754
+ var name = _a.name, duration = _a.duration, startTime = _a.startTime;
755
+ var time = Math.ceil(duration + startTime);
756
+ if (name === 'first-paint') {
757
+ metric.fp = time;
758
+ }
759
+ if (name === 'first-contentful-paint') {
760
+ metric.fcp = time;
761
+ }
762
+ });
763
+ }
764
+ }
765
+ // 端首次绘制与首屏
766
+ if (timing.domFirstPaint) {
767
+ metric.t7FirstPaint = timing.domFirstPaint - startTime;
768
+ }
769
+ if (timing.domFirstScreenPaint) {
770
+ metric.t7FirstScreen = timing.domFirstScreenPaint - startTime;
771
+ }
772
+ return metric;
773
+ };
774
+ return Timing;
768
775
  }());
769
776
 
770
- var ResType;
771
- (function (ResType) {
772
- ResType["JS"] = "js";
773
- ResType["CSS"] = "css";
774
- ResType["IMG"] = "img";
775
- ResType["FONT"] = "font";
777
+ var ResType;
778
+ (function (ResType) {
779
+ ResType["JS"] = "js";
780
+ ResType["CSS"] = "css";
781
+ ResType["IMG"] = "img";
782
+ ResType["FONT"] = "font";
776
783
  })(ResType || (ResType = {}));
777
784
 
778
- // 字体
779
- // svg使用场景比较灵活,可能作为一种字体格式,也可能当做图片使用
780
- // 但因woff在所有现代浏览器中都支持,在css中使用iconfont时
781
- // 往往优先加载woff格式字体文件,所以这里将svg划分为图片一类
782
- var FontsTypes;
783
- (function (FontsTypes) {
784
- FontsTypes[FontsTypes["ttf"] = 0] = "ttf";
785
- FontsTypes[FontsTypes["eot"] = 1] = "eot";
786
- FontsTypes[FontsTypes["woff"] = 2] = "woff";
787
- FontsTypes[FontsTypes["woff2"] = 3] = "woff2";
788
- })(FontsTypes || (FontsTypes = {}));
789
- // 忽略图片
790
- // 下述图片路径往往是用来进行日志统计,不是正常图片
791
- var ignoreDefaultPaths = [
792
- '/mwb2.gif',
793
- ];
794
- function ignorePath(url, paths) {
795
- for (var _i = 0, paths_1 = paths; _i < paths_1.length; _i++) {
796
- var path = paths_1[_i];
797
- if (url.indexOf(path) > -1) {
798
- return true;
799
- }
800
- }
801
- return false;
802
- }
803
- function f(n) {
804
- return +n.toFixed(1);
805
- }
806
- var Resource = /** @class */ (function () {
807
- function Resource() {
808
- this.trigger = 'load';
809
- this.jsList = [];
810
- this.cssList = [];
811
- this.imgList = [];
812
- this.fontList = [];
813
- this.hostList = {};
814
- this.bigImgList = {};
815
- this.httpResList = {};
816
- this.slowList = {};
817
- this.resOption = { ignorePaths: [], trigger: 'load' };
818
- this.bigImgOption = { ignorePaths: [], maxSize: 150 * 1024, trigger: 'load' };
819
- this.httpResOption = { ignorePaths: [], trigger: 'load' };
820
- this.slowOption = { ignorePaths: [], trigger: 'load', threshold: 1000 };
821
- }
822
- Resource.prototype.check = function () {
823
- return performance && performance.getEntriesByType;
824
- };
825
- Resource.prototype.listenResource = function (cb, option) {
826
- if (option === void 0) { option = {}; }
827
- if (!this.check()) {
828
- return;
829
- }
830
- this.resOption = assign(this.resOption, option);
831
- this.trigger = this.resOption.trigger;
832
- this.cb = cb;
833
- };
834
- Resource.prototype.listenBigImg = function (cb, option) {
835
- if (option === void 0) { option = {}; }
836
- if (!this.check()) {
837
- return;
838
- }
839
- this.bigImgOption = assign(this.bigImgOption, option);
840
- this.trigger = this.bigImgOption.trigger;
841
- this.bigImgCB = cb;
842
- };
843
- Resource.prototype.listenHttpResource = function (cb, option) {
844
- if (option === void 0) { option = {}; }
845
- if (!this.check()) {
846
- return;
847
- }
848
- this.httpResOption = assign(this.httpResOption, option);
849
- this.trigger = this.httpResOption.trigger;
850
- this.httpResCB = cb;
851
- };
852
- Resource.prototype.listenSlowResource = function (cb, option) {
853
- if (option === void 0) { option = {}; }
854
- if (!this.check()) {
855
- return;
856
- }
857
- this.slowOption = assign(this.slowOption, option);
858
- this.trigger = this.slowOption.trigger;
859
- this.slowResCB = cb;
860
- };
861
- Resource.prototype.report = function () {
862
- var _this = this;
863
- var metricRes = this.getMetric();
864
- if (metricRes) {
865
- var metric = metricRes.metric, hostMetric = metricRes.hostMetric;
866
- this.cb && this.cb(metric, hostMetric);
867
- }
868
- if (this.bigImgCB) {
869
- // 发送大图监控数据
870
- if (typeof window.requestIdleCallback === 'function' && Object.keys(this.bigImgList).length) {
871
- window.requestIdleCallback(function () {
872
- for (var _i = 0, _a = Object.keys(_this.bigImgList); _i < _a.length; _i++) {
873
- var host = _a[_i];
874
- for (var _b = 0, _c = _this.bigImgList[host]; _b < _c.length; _b++) {
875
- var entry = _c[_b];
876
- var timing = entry.timing;
877
- var type = entry.type;
878
- try {
879
- var img = document.body.querySelector('img[src="' + timing.name + '"]');
880
- _this.bigImgCB({
881
- msg: timing.name,
882
- dur: timing.duration,
883
- xpath: getxpath(img).xpath,
884
- host: host,
885
- type: type,
886
- });
887
- }
888
- catch (e) {
889
- console.error(e);
890
- }
891
- }
892
- }
893
- });
894
- }
895
- }
896
- if (this.httpResCB) {
897
- // 发送http资源监控数据
898
- if (typeof window.requestIdleCallback === 'function' && Object.keys(this.httpResList).length) {
899
- window.requestIdleCallback(function () {
900
- for (var _i = 0, _a = Object.keys(_this.httpResList); _i < _a.length; _i++) {
901
- var host = _a[_i];
902
- for (var _b = 0, _c = _this.httpResList[host]; _b < _c.length; _b++) {
903
- var entry = _c[_b];
904
- var timing = entry.timing;
905
- var type = entry.type;
906
- try {
907
- var img = document.body.querySelector('[src="' + timing.name + '"]');
908
- _this.httpResCB({
909
- msg: timing.name,
910
- dur: timing.duration,
911
- xpath: getxpath(img).xpath,
912
- host: host,
913
- type: type,
914
- });
915
- }
916
- catch (e) {
917
- console.error(e);
918
- }
919
- }
920
- }
921
- });
922
- }
923
- }
924
- if (this.slowResCB) {
925
- // 发送慢资源监控数据
926
- if (typeof window.requestIdleCallback === 'function' && Object.keys(this.slowList).length) {
927
- window.requestIdleCallback(function () {
928
- for (var _i = 0, _a = Object.keys(_this.slowList); _i < _a.length; _i++) {
929
- var host = _a[_i];
930
- for (var _b = 0, _c = _this.slowList[host]; _b < _c.length; _b++) {
931
- var entry = _c[_b];
932
- var timing = entry.timing;
933
- var type = entry.type;
934
- try {
935
- var img = document.body.querySelector('[src="' + timing.name + '"]');
936
- var info = getResTiming(timing);
937
- _this.slowResCB(__assign(__assign({}, info), { dur: timing.duration, msg: timing.name, xpath: getxpath(img).xpath, host: host, type: type }));
938
- }
939
- catch (e) {
940
- console.error(e);
941
- }
942
- }
943
- }
944
- });
945
- }
946
- }
947
- };
948
- Resource.prototype.load = function () {
949
- var _this = this;
950
- if (this.trigger !== 'load') {
951
- return;
952
- }
953
- if (!this.check()) {
954
- return;
955
- }
956
- setTimeout(function () {
957
- _this.report();
958
- }, 500);
959
- };
960
- Resource.prototype.leave = function () {
961
- if (this.trigger !== 'leave') {
962
- return;
963
- }
964
- this.report();
965
- };
966
- Resource.prototype.push = function (type, list, timing, urlInfo) {
967
- if (!ignorePath(urlInfo.pathname, this.resOption.ignorePaths || [])) {
968
- list.push(timing);
969
- this.pushWithHost(type, this.hostList, timing, urlInfo);
970
- }
971
- if (!ignorePath(urlInfo.pathname, this.slowOption.ignorePaths || [])) {
972
- if (timing.duration > this.slowOption.threshold) {
973
- this.pushWithHost(type, this.slowList, timing, urlInfo);
974
- }
975
- }
976
- };
977
- Resource.prototype.pushWithHost = function (type, list, timing, urlInfo) {
978
- var host = urlInfo.host;
979
- if (!list[host]) {
980
- list[host] = [];
981
- }
982
- list[host].push({
983
- timing: timing,
984
- type: type,
985
- });
986
- };
987
- Resource.prototype.collectHttpResInHttps = function (type, timing, urlInfo) {
988
- if (location.protocol === 'https:'
989
- && timing.name.indexOf('http://') === 0
990
- && !ignorePath(urlInfo.pathname, this.httpResOption.ignorePaths || [])) {
991
- this.pushWithHost(type, this.httpResList, timing, urlInfo);
992
- }
993
- };
994
- // 有些jsonp也属于script,这里只统计js后缀的文件
995
- Resource.prototype.addScript = function (timing, urlInfo) {
996
- if (urlInfo.ext === 'js') {
997
- if (timing.decodedBodySize !== 0) {
998
- this.push('js', this.jsList, timing, urlInfo);
999
- }
1000
- }
1001
- };
1002
- // 暂时将css文件或代码块发起的请求归位三类(主要为这两类)
1003
- // 1、加载字体
1004
- // 2、加载背景图(图片不容易区分,有的没有明确后缀名)
1005
- // 3、光标文件(后缀为.cur,这里也划分为图片)
1006
- // (svg当做图片,前述已说明)
1007
- Resource.prototype.addResFromCss = function (timing, urlInfo) {
1008
- if (urlInfo.ext && FontsTypes.hasOwnProperty(urlInfo.ext)) {
1009
- this.push('font', this.fontList, timing, urlInfo);
1010
- }
1011
- else {
1012
- this.addImg(timing, urlInfo);
1013
- }
1014
- };
1015
- // link一般加载css资源
1016
- // 也可以通过preload可以预下载一些资源
1017
- // 这里只统计js类型的preload
1018
- Resource.prototype.addLink = function (timing, urlInfo) {
1019
- if (urlInfo.ext === 'css') {
1020
- this.push('css', this.cssList, timing, urlInfo);
1021
- }
1022
- // preload as script
1023
- else if (urlInfo.ext === 'js') {
1024
- this.push('js', this.jsList, timing, urlInfo);
1025
- }
1026
- };
1027
- Resource.prototype.addImg = function (timing, urlInfo) {
1028
- this.push('img', this.imgList, timing, urlInfo);
1029
- // 大于指定size的图片采集
1030
- if (timing.decodedBodySize > (this.bigImgOption.maxSize || 0)
1031
- && !ignorePath(urlInfo.pathname, this.bigImgOption.ignorePaths || [])) {
1032
- this.pushWithHost('img', this.bigImgList, timing, urlInfo);
1033
- }
1034
- };
1035
- Resource.prototype.handleTimings = function (list) {
1036
- var len = list.length;
1037
- for (var i = 0; i < len; i++) {
1038
- var timing = list[i];
1039
- var urlInfo = getUrlInfo(timing.name);
1040
- if (ignorePath(urlInfo.pathname, ignoreDefaultPaths)) {
1041
- continue;
1042
- }
1043
- switch (list[i].initiatorType) {
1044
- case 'script':
1045
- this.addScript(timing, urlInfo);
1046
- break;
1047
- case 'css':
1048
- this.addResFromCss(timing, urlInfo);
1049
- break;
1050
- case 'img':
1051
- this.addImg(timing, urlInfo);
1052
- break;
1053
- case 'link':
1054
- this.addLink(timing, urlInfo);
1055
- break;
1056
- case 'audio':
1057
- this.collectHttpResInHttps('audio', timing, urlInfo);
1058
- break;
1059
- case 'video':
1060
- this.collectHttpResInHttps('video', timing, urlInfo);
1061
- break;
1062
- }
1063
- }
1064
- };
1065
- Resource.prototype.getNumAndSize = function (type, list) {
1066
- var obj = {};
1067
- var num = type + 'Num';
1068
- var size = type + 'Size';
1069
- var transferSize = type + 'TransferSize';
1070
- var cacheRate = type + 'CacheRate';
1071
- var duration = type + 'Duration';
1072
- obj[num] = 0;
1073
- obj[size] = 0;
1074
- obj[transferSize] = 0;
1075
- var totalDurationTime = 0;
1076
- list.forEach(function (timing) {
1077
- obj[num]++;
1078
- obj[size] += (timing.decodedBodySize / 1024);
1079
- obj[transferSize] += (timing.transferSize / 1024);
1080
- totalDurationTime += timing.duration;
1081
- });
1082
- obj[duration] = f(obj[num] > 0 ? totalDurationTime / obj[num] : 0);
1083
- if (obj[size]) {
1084
- var diff = obj[size] - obj[transferSize];
1085
- obj[cacheRate] = f(diff >= 0 ? 100 * diff / obj[size] : 0);
1086
- }
1087
- obj[size] = f(obj[size]);
1088
- obj[transferSize] = f(obj[transferSize]);
1089
- return obj;
1090
- };
1091
- Resource.prototype.getMetric = function () {
1092
- // 原来代码
1093
- var mainPageTiming = performance.getEntriesByType('navigation')[0];
1094
- var resourceTimings = performance.getEntriesByType('resource');
1095
- if (mainPageTiming && resourceTimings && resourceTimings.length) {
1096
- this.handleTimings(resourceTimings);
1097
- var metric = __assign(__assign(__assign(__assign({}, this.getNumAndSize(ResType.JS, this.jsList)), this.getNumAndSize(ResType.CSS, this.cssList)), this.getNumAndSize(ResType.IMG, this.imgList)), this.getNumAndSize(ResType.FONT, this.fontList));
1098
- // 主文档大小
1099
- var pageTiming = mainPageTiming;
1100
- metric.docSize = f(pageTiming.decodedBodySize / 1024);
1101
- metric.docTransferSize = f(pageTiming.transferSize / 1024);
1102
- metric.headerSize = f((pageTiming.transferSize - pageTiming.encodedBodySize || 0) / 1024);
1103
- metric.allSize = f(metric.docSize
1104
- + metric.jsSize
1105
- + metric.cssSize
1106
- + metric.imgSize
1107
- + metric.fontSize);
1108
- metric.allTransferSize = f(metric.docTransferSize
1109
- + metric.jsTransferSize
1110
- + metric.cssTransferSize
1111
- + metric.imgTransferSize
1112
- + metric.fontTransferSize);
1113
- var hostMetric = {};
1114
- for (var _i = 0, _a = Object.keys(this.hostList); _i < _a.length; _i++) {
1115
- var host = _a[_i];
1116
- var timings = this.hostList[host].map(function (item) { return item.timing; });
1117
- hostMetric[host] = this.getNumAndSize('host', timings);
1118
- }
1119
- return { metric: metric, hostMetric: hostMetric };
1120
- }
1121
- return;
1122
- };
1123
- return Resource;
785
+ // 字体
786
+ // svg使用场景比较灵活,可能作为一种字体格式,也可能当做图片使用
787
+ // 但因woff在所有现代浏览器中都支持,在css中使用iconfont时
788
+ // 往往优先加载woff格式字体文件,所以这里将svg划分为图片一类
789
+ var FontsTypes;
790
+ (function (FontsTypes) {
791
+ FontsTypes[FontsTypes["ttf"] = 0] = "ttf";
792
+ FontsTypes[FontsTypes["eot"] = 1] = "eot";
793
+ FontsTypes[FontsTypes["woff"] = 2] = "woff";
794
+ FontsTypes[FontsTypes["woff2"] = 3] = "woff2";
795
+ })(FontsTypes || (FontsTypes = {}));
796
+ // 忽略图片
797
+ // 下述图片路径往往是用来进行日志统计,不是正常图片
798
+ var ignoreDefaultPaths = [
799
+ '/mwb2.gif',
800
+ ];
801
+ function ignorePath(url, paths) {
802
+ for (var _i = 0, paths_1 = paths; _i < paths_1.length; _i++) {
803
+ var path = paths_1[_i];
804
+ if (url.indexOf(path) > -1) {
805
+ return true;
806
+ }
807
+ }
808
+ return false;
809
+ }
810
+ function f(n) {
811
+ return +n.toFixed(1);
812
+ }
813
+ var Resource = /** @class */ (function () {
814
+ function Resource() {
815
+ this.trigger = 'load';
816
+ this.jsList = [];
817
+ this.cssList = [];
818
+ this.imgList = [];
819
+ this.fontList = [];
820
+ this.hostList = {};
821
+ this.bigImgList = {};
822
+ this.httpResList = {};
823
+ this.slowList = {};
824
+ this.resOption = { ignorePaths: [], trigger: 'load' };
825
+ this.bigImgOption = { ignorePaths: [], maxSize: 150 * 1024, trigger: 'load' };
826
+ this.httpResOption = { ignorePaths: [], trigger: 'load' };
827
+ this.slowOption = { ignorePaths: [], trigger: 'load', threshold: 1000 };
828
+ }
829
+ Resource.prototype.check = function () {
830
+ return performance && performance.getEntriesByType;
831
+ };
832
+ Resource.prototype.listenResource = function (cb, option) {
833
+ if (option === void 0) { option = {}; }
834
+ if (!this.check()) {
835
+ return;
836
+ }
837
+ this.resOption = assign(this.resOption, option);
838
+ this.trigger = this.resOption.trigger;
839
+ this.cb = cb;
840
+ };
841
+ Resource.prototype.listenBigImg = function (cb, option) {
842
+ if (option === void 0) { option = {}; }
843
+ if (!this.check()) {
844
+ return;
845
+ }
846
+ this.bigImgOption = assign(this.bigImgOption, option);
847
+ this.trigger = this.bigImgOption.trigger;
848
+ this.bigImgCB = cb;
849
+ };
850
+ Resource.prototype.listenHttpResource = function (cb, option) {
851
+ if (option === void 0) { option = {}; }
852
+ if (!this.check()) {
853
+ return;
854
+ }
855
+ this.httpResOption = assign(this.httpResOption, option);
856
+ this.trigger = this.httpResOption.trigger;
857
+ this.httpResCB = cb;
858
+ };
859
+ Resource.prototype.listenSlowResource = function (cb, option) {
860
+ if (option === void 0) { option = {}; }
861
+ if (!this.check()) {
862
+ return;
863
+ }
864
+ this.slowOption = assign(this.slowOption, option);
865
+ this.trigger = this.slowOption.trigger;
866
+ this.slowResCB = cb;
867
+ };
868
+ Resource.prototype.report = function () {
869
+ var _this = this;
870
+ var metricRes = this.getMetric();
871
+ if (metricRes) {
872
+ var metric = metricRes.metric, hostMetric = metricRes.hostMetric;
873
+ this.cb && this.cb(metric, hostMetric);
874
+ }
875
+ if (this.bigImgCB) {
876
+ // 发送大图监控数据
877
+ if (typeof window.requestIdleCallback === 'function' && Object.keys(this.bigImgList).length) {
878
+ window.requestIdleCallback(function () {
879
+ for (var _i = 0, _a = Object.keys(_this.bigImgList); _i < _a.length; _i++) {
880
+ var host = _a[_i];
881
+ for (var _b = 0, _c = _this.bigImgList[host]; _b < _c.length; _b++) {
882
+ var entry = _c[_b];
883
+ var timing = entry.timing;
884
+ var type = entry.type;
885
+ try {
886
+ var img = document.body.querySelector('img[src="' + timing.name + '"]');
887
+ _this.bigImgCB({
888
+ msg: timing.name,
889
+ dur: timing.duration,
890
+ xpath: getxpath(img).xpath,
891
+ host: host,
892
+ type: type,
893
+ });
894
+ }
895
+ catch (e) {
896
+ console.error(e);
897
+ }
898
+ }
899
+ }
900
+ });
901
+ }
902
+ }
903
+ if (this.httpResCB) {
904
+ // 发送http资源监控数据
905
+ if (typeof window.requestIdleCallback === 'function' && Object.keys(this.httpResList).length) {
906
+ window.requestIdleCallback(function () {
907
+ for (var _i = 0, _a = Object.keys(_this.httpResList); _i < _a.length; _i++) {
908
+ var host = _a[_i];
909
+ for (var _b = 0, _c = _this.httpResList[host]; _b < _c.length; _b++) {
910
+ var entry = _c[_b];
911
+ var timing = entry.timing;
912
+ var type = entry.type;
913
+ try {
914
+ var img = document.body.querySelector('[src="' + timing.name + '"]');
915
+ _this.httpResCB({
916
+ msg: timing.name,
917
+ dur: timing.duration,
918
+ xpath: getxpath(img).xpath,
919
+ host: host,
920
+ type: type,
921
+ });
922
+ }
923
+ catch (e) {
924
+ console.error(e);
925
+ }
926
+ }
927
+ }
928
+ });
929
+ }
930
+ }
931
+ if (this.slowResCB) {
932
+ // 发送慢资源监控数据
933
+ if (typeof window.requestIdleCallback === 'function' && Object.keys(this.slowList).length) {
934
+ window.requestIdleCallback(function () {
935
+ for (var _i = 0, _a = Object.keys(_this.slowList); _i < _a.length; _i++) {
936
+ var host = _a[_i];
937
+ for (var _b = 0, _c = _this.slowList[host]; _b < _c.length; _b++) {
938
+ var entry = _c[_b];
939
+ var timing = entry.timing;
940
+ var type = entry.type;
941
+ try {
942
+ var img = document.body.querySelector('[src="' + timing.name + '"]');
943
+ var info = getResTiming(timing);
944
+ _this.slowResCB(__assign(__assign({}, info), { dur: timing.duration, msg: timing.name, xpath: getxpath(img).xpath, host: host, type: type }));
945
+ }
946
+ catch (e) {
947
+ console.error(e);
948
+ }
949
+ }
950
+ }
951
+ });
952
+ }
953
+ }
954
+ };
955
+ Resource.prototype.load = function () {
956
+ var _this = this;
957
+ if (this.trigger !== 'load') {
958
+ return;
959
+ }
960
+ if (!this.check()) {
961
+ return;
962
+ }
963
+ setTimeout(function () {
964
+ _this.report();
965
+ }, 500);
966
+ };
967
+ Resource.prototype.leave = function () {
968
+ if (this.trigger !== 'leave') {
969
+ return;
970
+ }
971
+ this.report();
972
+ };
973
+ Resource.prototype.push = function (type, list, timing, urlInfo) {
974
+ if (!ignorePath(urlInfo.pathname, this.resOption.ignorePaths || [])) {
975
+ list.push(timing);
976
+ this.pushWithHost(type, this.hostList, timing, urlInfo);
977
+ }
978
+ if (!ignorePath(urlInfo.pathname, this.slowOption.ignorePaths || [])) {
979
+ if (timing.duration > this.slowOption.threshold) {
980
+ this.pushWithHost(type, this.slowList, timing, urlInfo);
981
+ }
982
+ }
983
+ };
984
+ Resource.prototype.pushWithHost = function (type, list, timing, urlInfo) {
985
+ var host = urlInfo.host;
986
+ if (!list[host]) {
987
+ list[host] = [];
988
+ }
989
+ list[host].push({
990
+ timing: timing,
991
+ type: type,
992
+ });
993
+ };
994
+ Resource.prototype.collectHttpResInHttps = function (type, timing, urlInfo) {
995
+ if (location.protocol === 'https:'
996
+ && timing.name.indexOf('http://') === 0
997
+ && !ignorePath(urlInfo.pathname, this.httpResOption.ignorePaths || [])) {
998
+ this.pushWithHost(type, this.httpResList, timing, urlInfo);
999
+ }
1000
+ };
1001
+ // 有些jsonp也属于script,这里只统计js后缀的文件
1002
+ Resource.prototype.addScript = function (timing, urlInfo) {
1003
+ if (urlInfo.ext === 'js') {
1004
+ if (timing.decodedBodySize !== 0) {
1005
+ this.push('js', this.jsList, timing, urlInfo);
1006
+ }
1007
+ }
1008
+ };
1009
+ // 暂时将css文件或代码块发起的请求归位三类(主要为这两类)
1010
+ // 1、加载字体
1011
+ // 2、加载背景图(图片不容易区分,有的没有明确后缀名)
1012
+ // 3、光标文件(后缀为.cur,这里也划分为图片)
1013
+ // (svg当做图片,前述已说明)
1014
+ Resource.prototype.addResFromCss = function (timing, urlInfo) {
1015
+ if (urlInfo.ext && FontsTypes.hasOwnProperty(urlInfo.ext)) {
1016
+ this.push('font', this.fontList, timing, urlInfo);
1017
+ }
1018
+ else {
1019
+ this.addImg(timing, urlInfo);
1020
+ }
1021
+ };
1022
+ // link一般加载css资源
1023
+ // 也可以通过preload可以预下载一些资源
1024
+ // 这里只统计js类型的preload
1025
+ Resource.prototype.addLink = function (timing, urlInfo) {
1026
+ if (urlInfo.ext === 'css') {
1027
+ this.push('css', this.cssList, timing, urlInfo);
1028
+ }
1029
+ // preload as script
1030
+ else if (urlInfo.ext === 'js') {
1031
+ this.push('js', this.jsList, timing, urlInfo);
1032
+ }
1033
+ };
1034
+ Resource.prototype.addImg = function (timing, urlInfo) {
1035
+ this.push('img', this.imgList, timing, urlInfo);
1036
+ // 大于指定size的图片采集
1037
+ if (timing.decodedBodySize > (this.bigImgOption.maxSize || 0)
1038
+ && !ignorePath(urlInfo.pathname, this.bigImgOption.ignorePaths || [])) {
1039
+ this.pushWithHost('img', this.bigImgList, timing, urlInfo);
1040
+ }
1041
+ };
1042
+ Resource.prototype.handleTimings = function (list) {
1043
+ var len = list.length;
1044
+ for (var i = 0; i < len; i++) {
1045
+ var timing = list[i];
1046
+ var urlInfo = getUrlInfo(timing.name);
1047
+ if (ignorePath(urlInfo.pathname, ignoreDefaultPaths)) {
1048
+ continue;
1049
+ }
1050
+ switch (list[i].initiatorType) {
1051
+ case 'script':
1052
+ this.addScript(timing, urlInfo);
1053
+ break;
1054
+ case 'css':
1055
+ this.addResFromCss(timing, urlInfo);
1056
+ break;
1057
+ case 'img':
1058
+ this.addImg(timing, urlInfo);
1059
+ break;
1060
+ case 'link':
1061
+ this.addLink(timing, urlInfo);
1062
+ break;
1063
+ case 'audio':
1064
+ this.collectHttpResInHttps('audio', timing, urlInfo);
1065
+ break;
1066
+ case 'video':
1067
+ this.collectHttpResInHttps('video', timing, urlInfo);
1068
+ break;
1069
+ }
1070
+ }
1071
+ };
1072
+ Resource.prototype.getNumAndSize = function (type, list) {
1073
+ var obj = {};
1074
+ var num = type + 'Num';
1075
+ var size = type + 'Size';
1076
+ var transferSize = type + 'TransferSize';
1077
+ var cacheRate = type + 'CacheRate';
1078
+ var duration = type + 'Duration';
1079
+ obj[num] = 0;
1080
+ obj[size] = 0;
1081
+ obj[transferSize] = 0;
1082
+ var totalDurationTime = 0;
1083
+ list.forEach(function (timing) {
1084
+ obj[num]++;
1085
+ obj[size] += (timing.decodedBodySize / 1024);
1086
+ obj[transferSize] += (timing.transferSize / 1024);
1087
+ totalDurationTime += timing.duration;
1088
+ });
1089
+ obj[duration] = f(obj[num] > 0 ? totalDurationTime / obj[num] : 0);
1090
+ if (obj[size]) {
1091
+ var diff = obj[size] - obj[transferSize];
1092
+ obj[cacheRate] = f(diff >= 0 ? 100 * diff / obj[size] : 0);
1093
+ }
1094
+ obj[size] = f(obj[size]);
1095
+ obj[transferSize] = f(obj[transferSize]);
1096
+ return obj;
1097
+ };
1098
+ Resource.prototype.getMetric = function () {
1099
+ // 原来代码
1100
+ var mainPageTiming = performance.getEntriesByType('navigation')[0];
1101
+ var resourceTimings = performance.getEntriesByType('resource');
1102
+ if (mainPageTiming && resourceTimings && resourceTimings.length) {
1103
+ this.handleTimings(resourceTimings);
1104
+ var metric = __assign(__assign(__assign(__assign({}, this.getNumAndSize(ResType.JS, this.jsList)), this.getNumAndSize(ResType.CSS, this.cssList)), this.getNumAndSize(ResType.IMG, this.imgList)), this.getNumAndSize(ResType.FONT, this.fontList));
1105
+ // 主文档大小
1106
+ var pageTiming = mainPageTiming;
1107
+ metric.docSize = f(pageTiming.decodedBodySize / 1024);
1108
+ metric.docTransferSize = f(pageTiming.transferSize / 1024);
1109
+ metric.headerSize = f((pageTiming.transferSize - pageTiming.encodedBodySize || 0) / 1024);
1110
+ metric.allSize = f(metric.docSize
1111
+ + metric.jsSize
1112
+ + metric.cssSize
1113
+ + metric.imgSize
1114
+ + metric.fontSize);
1115
+ metric.allTransferSize = f(metric.docTransferSize
1116
+ + metric.jsTransferSize
1117
+ + metric.cssTransferSize
1118
+ + metric.imgTransferSize
1119
+ + metric.fontTransferSize);
1120
+ var hostMetric = {};
1121
+ for (var _i = 0, _a = Object.keys(this.hostList); _i < _a.length; _i++) {
1122
+ var host = _a[_i];
1123
+ var timings = this.hostList[host].map(function (item) { return item.timing; });
1124
+ hostMetric[host] = this.getNumAndSize('host', timings);
1125
+ }
1126
+ return { metric: metric, hostMetric: hostMetric };
1127
+ }
1128
+ return;
1129
+ };
1130
+ return Resource;
1124
1131
  }());
1125
1132
 
1126
- /**
1127
- * @file Memory
1128
- * @author kaivean
1129
- */
1130
- var initMemory = null;
1131
- if (window.performance && window.performance.memory) {
1132
- initMemory = window.performance.memory;
1133
- }
1134
- var Memory = /** @class */ (function () {
1135
- function Memory() {
1136
- this.onceLeave = false;
1137
- }
1138
- // constructor() {}
1139
- Memory.prototype.listenMemory = function (cb) {
1140
- this.cb = cb;
1141
- };
1142
- Memory.prototype.leave = function () {
1143
- if (!this.onceLeave && initMemory) {
1144
- this.onceLeave = true;
1145
- var curMemory = window.performance.memory;
1146
- // fix 早期浏览器的memroy api 值不更新的问题,将此情况排除
1147
- if (curMemory.usedJSHeapSize === initMemory.usedJSHeapSize
1148
- && curMemory.totalJSHeapSize === initMemory.totalJSHeapSize) {
1149
- return;
1150
- }
1151
- var memory = window.performance.memory;
1152
- this.cb && this.cb({
1153
- usedJSHeapSize: memory.usedJSHeapSize / 1024,
1154
- totalJSHeapSize: memory.totalJSHeapSize / 1024,
1155
- jsHeapSizeLimit: memory.jsHeapSizeLimit / 1024,
1156
- usedJSHeapRate: 100 * memory.usedJSHeapSize / memory.totalJSHeapSize,
1157
- });
1158
- }
1159
- };
1160
- return Memory;
1133
+ /**
1134
+ * @file Memory
1135
+ * @author kaivean
1136
+ */
1137
+ var initMemory = null;
1138
+ if (window.performance && window.performance.memory) {
1139
+ initMemory = window.performance.memory;
1140
+ }
1141
+ var Memory = /** @class */ (function () {
1142
+ function Memory() {
1143
+ this.onceLeave = false;
1144
+ }
1145
+ // constructor() {}
1146
+ Memory.prototype.listenMemory = function (cb) {
1147
+ this.cb = cb;
1148
+ };
1149
+ Memory.prototype.leave = function () {
1150
+ if (!this.onceLeave && initMemory) {
1151
+ this.onceLeave = true;
1152
+ var curMemory = window.performance.memory;
1153
+ // fix 早期浏览器的memroy api 值不更新的问题,将此情况排除
1154
+ if (curMemory.usedJSHeapSize === initMemory.usedJSHeapSize
1155
+ && curMemory.totalJSHeapSize === initMemory.totalJSHeapSize) {
1156
+ return;
1157
+ }
1158
+ var memory = window.performance.memory;
1159
+ this.cb && this.cb({
1160
+ usedJSHeapSize: memory.usedJSHeapSize / 1024,
1161
+ totalJSHeapSize: memory.totalJSHeapSize / 1024,
1162
+ jsHeapSizeLimit: memory.jsHeapSizeLimit / 1024,
1163
+ usedJSHeapRate: 100 * memory.usedJSHeapSize / memory.totalJSHeapSize,
1164
+ });
1165
+ }
1166
+ };
1167
+ return Memory;
1161
1168
  }());
1162
1169
 
1163
- /**
1164
- * @file NavigatorInfo
1165
- * @author kaivean
1166
- */
1167
- var NavigatorInfo = /** @class */ (function () {
1168
- function NavigatorInfo() {
1169
- }
1170
- // private cb: NavigatorInfoCB;
1171
- NavigatorInfo.prototype.getNavigatorInfo = function () {
1172
- // this.cb = cb;
1173
- var ret = {};
1174
- var dataConnection = navigator.connection;
1175
- if (typeof dataConnection === 'object') {
1176
- ret = {
1177
- downlink: dataConnection.downlink,
1178
- effectiveType: dataConnection.effectiveType,
1179
- rtt: dataConnection.rtt,
1180
- saveData: !!dataConnection.saveData, // 数据节约模式
1181
- };
1182
- }
1183
- // 内存 G
1184
- if (navigator.deviceMemory) {
1185
- ret.deviceMemory = navigator.deviceMemory;
1186
- }
1187
- // 核数
1188
- if (navigator.hardwareConcurrency) {
1189
- ret.hardwareConcurrency = navigator.deviceMemory;
1190
- }
1191
- return ret;
1192
- };
1193
- NavigatorInfo.prototype.load = function () { };
1194
- return NavigatorInfo;
1170
+ /**
1171
+ * @file NavigatorInfo
1172
+ * @author kaivean
1173
+ */
1174
+ var NavigatorInfo = /** @class */ (function () {
1175
+ function NavigatorInfo() {
1176
+ }
1177
+ // private cb: NavigatorInfoCB;
1178
+ NavigatorInfo.prototype.getNavigatorInfo = function () {
1179
+ // this.cb = cb;
1180
+ var ret = {};
1181
+ var dataConnection = navigator.connection;
1182
+ if (typeof dataConnection === 'object') {
1183
+ ret = {
1184
+ downlink: dataConnection.downlink, // 网站下载速度 M/s
1185
+ effectiveType: dataConnection.effectiveType, // 网络类型
1186
+ rtt: dataConnection.rtt, // 网络往返时间 ms
1187
+ saveData: !!dataConnection.saveData, // 数据节约模式
1188
+ };
1189
+ }
1190
+ // 内存 G
1191
+ if (navigator.deviceMemory) {
1192
+ ret.deviceMemory = navigator.deviceMemory;
1193
+ }
1194
+ // 核数
1195
+ if (navigator.hardwareConcurrency) {
1196
+ ret.hardwareConcurrency = navigator.deviceMemory;
1197
+ }
1198
+ return ret;
1199
+ };
1200
+ NavigatorInfo.prototype.load = function () { };
1201
+ return NavigatorInfo;
1195
1202
  }());
1196
1203
 
1197
- /**
1198
- * @file Longtask
1199
- * @author kaivean
1200
- */
1201
- var spyclient = window.__spyHead;
1202
- var entryType = 'longtask';
1203
- var Longtask = /** @class */ (function () {
1204
- function Longtask() {
1205
- var _this = this;
1206
- this.lts = [];
1207
- this.observer = null;
1208
- this.onceLeave = false;
1209
- if (spyclient && spyclient.entryMap && spyclient.entryMap[entryType]) {
1210
- this.lts = this.lts.concat(spyclient.entryMap[entryType]);
1211
- }
1212
- try {
1213
- this.observer = new PerformanceObserver(function (list) {
1214
- _this.lts = _this.lts.concat(list.getEntries());
1215
- });
1216
- // buffered 兼容性太差
1217
- this.observer.observe({ entryTypes: [entryType] });
1218
- }
1219
- catch (e) { }
1220
- }
1221
- Longtask.prototype.check = function () {
1222
- return window.PerformanceObserver && performance && performance.timing && performance.timing.navigationStart;
1223
- };
1224
- Longtask.prototype.listenFSPLongTask = function (cb) {
1225
- if (!this.check()) {
1226
- return;
1227
- }
1228
- this.fspCB = cb;
1229
- };
1230
- Longtask.prototype.listenLCPLongTask = function (cb) {
1231
- if (!this.check()) {
1232
- return;
1233
- }
1234
- this.lcpCB = cb;
1235
- };
1236
- Longtask.prototype.listenLoadLongTask = function (cb) {
1237
- if (!this.check()) {
1238
- return;
1239
- }
1240
- this.loadCB = cb;
1241
- };
1242
- Longtask.prototype.listenPageLongTask = function (cb) {
1243
- if (!this.check()) {
1244
- return;
1245
- }
1246
- this.pageCB = cb;
1247
- };
1248
- Longtask.prototype.load = function () {
1249
- var _this = this;
1250
- if (!this.check()) {
1251
- return;
1252
- }
1253
- var data = this.getStatData(Date.now());
1254
- // lcp的值存入data模块也是在load期间,这里延迟一会再获取
1255
- setTimeout(function () {
1256
- _this.loadCB && _this.loadCB({
1257
- loadLongtaskTime: data.time,
1258
- loadTBT: data.tbt,
1259
- loadTotalTime: data.totalTime,
1260
- loadLongtaskRate: data.rate,
1261
- loadLongtaskNum: data.num,
1262
- });
1263
- if (performance.timing && performance.timing.domFirstScreenPaint) {
1264
- var data_1 = _this.getStatData(performance.timing.domFirstScreenPaint);
1265
- _this.fspCB && _this.fspCB({
1266
- fspLongtaskTime: data_1.time,
1267
- fspTBT: data_1.tbt,
1268
- fspTotalTime: data_1.totalTime,
1269
- fspLongtaskRate: data_1.rate,
1270
- fspLongtaskNum: data_1.num,
1271
- });
1272
- }
1273
- if (getData('lcp')) {
1274
- var data_2 = _this.getStatData(performance.timing.navigationStart + getData('lcp'));
1275
- _this.lcpCB && _this.lcpCB({
1276
- lcpLongtaskTime: data_2.time,
1277
- lcpTBT: data_2.tbt,
1278
- lcpTotalTime: data_2.totalTime,
1279
- lcpLongtaskRate: data_2.rate,
1280
- lcpLongtaskNum: data_2.num,
1281
- });
1282
- }
1283
- }, 200);
1284
- };
1285
- Longtask.prototype.leave = function () {
1286
- if (!this.onceLeave) {
1287
- this.onceLeave = true;
1288
- var data = this.getStatData(Date.now());
1289
- this.pageCB && this.pageCB({
1290
- pageLongtaskTime: data.time,
1291
- pageTBT: data.tbt,
1292
- pageTotalTime: data.totalTime,
1293
- pageLongtaskRate: data.rate,
1294
- pageLongtaskNum: data.num,
1295
- pageIframeLongtaskTime: data.iframeTime,
1296
- pageIframeLongtaskRate: data.iframeRate,
1297
- pageIframeLongtaskNum: data.iframeNum,
1298
- });
1299
- }
1300
- };
1301
- Longtask.prototype.destroy = function () {
1302
- this.lts = [];
1303
- this.observer && this.observer.disconnect();
1304
- this.observer = null;
1305
- };
1306
- Longtask.prototype.getStatData = function (finalTime) {
1307
- var navigationStart = performance.timing.navigationStart;
1308
- var time = 0;
1309
- // Total Blocking Time
1310
- var tbt = 0;
1311
- var num = 0;
1312
- var iframeTime = 0;
1313
- var iframeNum = 0;
1314
- var iframeLongtasks = {};
1315
- for (var index = 0; index < this.lts.length; index++) {
1316
- var item = this.lts[index];
1317
- var duration = item.duration;
1318
- var end = navigationStart + item.startTime + duration;
1319
- if (end < finalTime) {
1320
- time += duration;
1321
- // 多出来的时间
1322
- tbt += (duration - 50 > 0 ? duration - 50 : 0);
1323
- num++;
1324
- if (item.attribution && item.attribution[0]) {
1325
- var containerSrc = item.attribution[0].containerSrc;
1326
- if (containerSrc && containerSrc !== location.href) {
1327
- if (!iframeLongtasks[containerSrc]) {
1328
- iframeLongtasks[containerSrc] = [];
1329
- }
1330
- iframeLongtasks[containerSrc].push(duration);
1331
- iframeTime += duration;
1332
- iframeNum++;
1333
- }
1334
- }
1335
- }
1336
- }
1337
- var totalTime = finalTime - navigationStart;
1338
- return {
1339
- num: num,
1340
- time: time,
1341
- tbt: tbt,
1342
- totalTime: totalTime,
1343
- rate: 100 * time / totalTime,
1344
- iframeTime: iframeTime,
1345
- iframeNum: iframeNum,
1346
- iframeRate: 100 * iframeTime / totalTime,
1347
- iframeLongtasks: iframeLongtasks,
1348
- };
1349
- };
1350
- return Longtask;
1204
+ /**
1205
+ * @file Longtask
1206
+ * @author kaivean
1207
+ */
1208
+ var spyclient = window.__spyHead;
1209
+ var entryType = 'longtask';
1210
+ var Longtask = /** @class */ (function () {
1211
+ function Longtask() {
1212
+ var _this = this;
1213
+ this.lts = [];
1214
+ this.observer = null;
1215
+ this.onceLeave = false;
1216
+ if (spyclient && spyclient.entryMap && spyclient.entryMap[entryType]) {
1217
+ this.lts = this.lts.concat(spyclient.entryMap[entryType]);
1218
+ }
1219
+ try {
1220
+ this.observer = new PerformanceObserver(function (list) {
1221
+ _this.lts = _this.lts.concat(list.getEntries());
1222
+ });
1223
+ // buffered 兼容性太差
1224
+ this.observer.observe({ entryTypes: [entryType] });
1225
+ }
1226
+ catch (e) { }
1227
+ }
1228
+ Longtask.prototype.check = function () {
1229
+ return window.PerformanceObserver && performance && performance.timing && performance.timing.navigationStart;
1230
+ };
1231
+ Longtask.prototype.listenFSPLongTask = function (cb) {
1232
+ if (!this.check()) {
1233
+ return;
1234
+ }
1235
+ this.fspCB = cb;
1236
+ };
1237
+ Longtask.prototype.listenLCPLongTask = function (cb) {
1238
+ if (!this.check()) {
1239
+ return;
1240
+ }
1241
+ this.lcpCB = cb;
1242
+ };
1243
+ Longtask.prototype.listenLoadLongTask = function (cb) {
1244
+ if (!this.check()) {
1245
+ return;
1246
+ }
1247
+ this.loadCB = cb;
1248
+ };
1249
+ Longtask.prototype.listenPageLongTask = function (cb) {
1250
+ if (!this.check()) {
1251
+ return;
1252
+ }
1253
+ this.pageCB = cb;
1254
+ };
1255
+ Longtask.prototype.load = function () {
1256
+ var _this = this;
1257
+ if (!this.check()) {
1258
+ return;
1259
+ }
1260
+ var data = this.getStatData(Date.now());
1261
+ // lcp的值存入data模块也是在load期间,这里延迟一会再获取
1262
+ setTimeout(function () {
1263
+ _this.loadCB && _this.loadCB({
1264
+ loadLongtaskTime: data.time,
1265
+ loadTBT: data.tbt,
1266
+ loadTotalTime: data.totalTime,
1267
+ loadLongtaskRate: data.rate,
1268
+ loadLongtaskNum: data.num,
1269
+ });
1270
+ if (performance.timing && performance.timing.domFirstScreenPaint) {
1271
+ var data_1 = _this.getStatData(performance.timing.domFirstScreenPaint);
1272
+ _this.fspCB && _this.fspCB({
1273
+ fspLongtaskTime: data_1.time,
1274
+ fspTBT: data_1.tbt,
1275
+ fspTotalTime: data_1.totalTime,
1276
+ fspLongtaskRate: data_1.rate,
1277
+ fspLongtaskNum: data_1.num,
1278
+ });
1279
+ }
1280
+ if (getData('lcp')) {
1281
+ var data_2 = _this.getStatData(performance.timing.navigationStart + getData('lcp'));
1282
+ _this.lcpCB && _this.lcpCB({
1283
+ lcpLongtaskTime: data_2.time,
1284
+ lcpTBT: data_2.tbt,
1285
+ lcpTotalTime: data_2.totalTime,
1286
+ lcpLongtaskRate: data_2.rate,
1287
+ lcpLongtaskNum: data_2.num,
1288
+ });
1289
+ }
1290
+ }, 200);
1291
+ };
1292
+ Longtask.prototype.leave = function () {
1293
+ if (!this.onceLeave) {
1294
+ this.onceLeave = true;
1295
+ var data = this.getStatData(Date.now());
1296
+ this.pageCB && this.pageCB({
1297
+ pageLongtaskTime: data.time,
1298
+ pageTBT: data.tbt,
1299
+ pageTotalTime: data.totalTime,
1300
+ pageLongtaskRate: data.rate,
1301
+ pageLongtaskNum: data.num,
1302
+ pageIframeLongtaskTime: data.iframeTime,
1303
+ pageIframeLongtaskRate: data.iframeRate,
1304
+ pageIframeLongtaskNum: data.iframeNum,
1305
+ });
1306
+ }
1307
+ };
1308
+ Longtask.prototype.destroy = function () {
1309
+ this.lts = [];
1310
+ this.observer && this.observer.disconnect();
1311
+ this.observer = null;
1312
+ };
1313
+ Longtask.prototype.getStatData = function (finalTime) {
1314
+ var navigationStart = performance.timing.navigationStart;
1315
+ var time = 0;
1316
+ // Total Blocking Time
1317
+ var tbt = 0;
1318
+ var num = 0;
1319
+ var iframeTime = 0;
1320
+ var iframeNum = 0;
1321
+ var iframeLongtasks = {};
1322
+ for (var index = 0; index < this.lts.length; index++) {
1323
+ var item = this.lts[index];
1324
+ var duration = item.duration;
1325
+ var end = navigationStart + item.startTime + duration;
1326
+ if (end < finalTime) {
1327
+ time += duration;
1328
+ // 多出来的时间
1329
+ tbt += (duration - 50 > 0 ? duration - 50 : 0);
1330
+ num++;
1331
+ if (item.attribution && item.attribution[0]) {
1332
+ var containerSrc = item.attribution[0].containerSrc;
1333
+ if (containerSrc && containerSrc !== location.href) {
1334
+ if (!iframeLongtasks[containerSrc]) {
1335
+ iframeLongtasks[containerSrc] = [];
1336
+ }
1337
+ iframeLongtasks[containerSrc].push(duration);
1338
+ iframeTime += duration;
1339
+ iframeNum++;
1340
+ }
1341
+ }
1342
+ }
1343
+ }
1344
+ var totalTime = finalTime - navigationStart;
1345
+ return {
1346
+ num: num,
1347
+ time: time,
1348
+ tbt: tbt,
1349
+ totalTime: totalTime,
1350
+ rate: 100 * time / totalTime,
1351
+ iframeTime: iframeTime,
1352
+ iframeNum: iframeNum,
1353
+ iframeRate: 100 * iframeTime / totalTime,
1354
+ iframeLongtasks: iframeLongtasks,
1355
+ };
1356
+ };
1357
+ return Longtask;
1351
1358
  }());
1352
1359
 
1353
- /**
1354
- * @file SpyClient
1355
- * @author kaivean
1356
- */
1357
- var SpyClient = /** @class */ (function (_super) {
1358
- __extends(SpyClient, _super);
1359
- function SpyClient(option) {
1360
- var _this = _super.call(this, option) || this;
1361
- _this.modules = [];
1362
- _this.register(new FID());
1363
- _this.register(new LCP());
1364
- _this.register(new LayoutShift());
1365
- _this.register(new TTI());
1366
- _this.register(new Timing());
1367
- _this.register(new Resource());
1368
- _this.register(new Memory());
1369
- _this.register(new NavigatorInfo());
1370
- _this.register(new Longtask());
1371
- _this.visibilitychangeCB = _this.visibilitychangeCB.bind(_this);
1372
- _this.load = _this.load.bind(_this);
1373
- _this.leave = _this.leave.bind(_this);
1374
- if (document.readyState === 'complete') {
1375
- _this.load();
1376
- }
1377
- else {
1378
- window.addEventListener('load', _this.load);
1379
- }
1380
- document.addEventListener('visibilitychange', _this.visibilitychangeCB);
1381
- window.addEventListener('beforeunload', _this.leave, false);
1382
- window.addEventListener('unload', _this.leave, false);
1383
- _this.handleHead();
1384
- return _this;
1385
- }
1386
- SpyClient.prototype.handleHead = function () {
1387
- var _this = this;
1388
- if (this.option.localCache) {
1389
- var spyHead = window.__spyHead;
1390
- if (spyHead && spyHead.winerrors) {
1391
- for (var index = 0; index < spyHead.winerrors.length; index++) {
1392
- var obj = spyHead.winerrors[index];
1393
- this.option.localCache.addLog(obj);
1394
- }
1395
- // Head发送的异常,也保存一份到本地,主要是JS错误和资源加载异常
1396
- spyHead.interceptor = function (obj) {
1397
- _this.option.localCache.addLog(obj);
1398
- };
1399
- }
1400
- }
1401
- };
1402
- SpyClient.prototype.listenFID = function (cb) {
1403
- this.invoke('listenFID', cb);
1404
- };
1405
- SpyClient.prototype.listenLayoutShift = function (cb) {
1406
- this.invoke('listenLayoutShift', cb);
1407
- };
1408
- SpyClient.prototype.listenLCP = function (cb) {
1409
- this.invoke('listenLCP', cb);
1410
- };
1411
- SpyClient.prototype.listenFSPLongTask = function (cb) {
1412
- this.invoke('listenFSPLongTask', cb);
1413
- };
1414
- SpyClient.prototype.listenLCPLongTask = function (cb) {
1415
- this.invoke('listenLCPLongTask', cb);
1416
- };
1417
- SpyClient.prototype.listenLoadLongTask = function (cb) {
1418
- this.invoke('listenLoadLongTask', cb);
1419
- };
1420
- SpyClient.prototype.listenPageLongTask = function (cb) {
1421
- this.invoke('listenPageLongTask', cb);
1422
- };
1423
- SpyClient.prototype.listenMemory = function (cb) {
1424
- this.invoke('listenMemory', cb);
1425
- };
1426
- SpyClient.prototype.getNavigatorInfo = function () {
1427
- return this.invoke('getNavigatorInfo');
1428
- };
1429
- SpyClient.prototype.listenResource = function (cb, option) {
1430
- this.invoke('listenResource', cb, option);
1431
- };
1432
- SpyClient.prototype.listenBigImg = function (cb, option) {
1433
- this.invoke('listenBigImg', cb, option);
1434
- };
1435
- SpyClient.prototype.listenHttpResource = function (cb, option) {
1436
- this.invoke('listenHttpResource', cb, option);
1437
- };
1438
- SpyClient.prototype.listenSlowResource = function (cb, option) {
1439
- this.invoke('listenSlowResource', cb, option);
1440
- };
1441
- SpyClient.prototype.listenTiming = function (cb) {
1442
- this.invoke('listenTiming', cb);
1443
- };
1444
- SpyClient.prototype.listenTTI = function (cb, option) {
1445
- this.invoke('listenTTI', cb, option);
1446
- };
1447
- SpyClient.prototype.invoke = function (name, cb, option) {
1448
- for (var index = 0; index < this.modules.length; index++) {
1449
- var mod = this.modules[index];
1450
- if (typeof mod[name] === 'function') {
1451
- return mod[name].apply(mod, [cb, option]);
1452
- }
1453
- }
1454
- console.error('no method', name);
1455
- };
1456
- SpyClient.prototype.register = function (mod) {
1457
- this.modules.push(mod);
1458
- };
1459
- SpyClient.prototype.load = function () {
1460
- for (var index = 0; index < this.modules.length; index++) {
1461
- var mod = this.modules[index];
1462
- mod.load && mod.load();
1463
- }
1464
- };
1465
- SpyClient.prototype.leave = function () {
1466
- for (var index = 0; index < this.modules.length; index++) {
1467
- var mod = this.modules[index];
1468
- mod.leave && mod.leave();
1469
- }
1470
- };
1471
- SpyClient.prototype.destroy = function () {
1472
- for (var index = 0; index < this.modules.length; index++) {
1473
- var mod = this.modules[index];
1474
- mod.destroy && mod.destroy();
1475
- }
1476
- document.removeEventListener('visibilitychange', this.visibilitychangeCB);
1477
- window.removeEventListener('load', this.load);
1478
- window.removeEventListener('beforeunload', this.leave);
1479
- window.removeEventListener('unload', this.destroy);
1480
- };
1481
- SpyClient.prototype.visibilitychangeCB = function () {
1482
- if (document.visibilityState === 'hidden') {
1483
- this.leave();
1484
- }
1485
- };
1486
- return SpyClient;
1360
+ /**
1361
+ * @file SpyClient
1362
+ * @author kaivean
1363
+ */
1364
+ var SpyClient = /** @class */ (function (_super) {
1365
+ __extends(SpyClient, _super);
1366
+ function SpyClient(option) {
1367
+ var _this = _super.call(this, option) || this;
1368
+ _this.modules = [];
1369
+ _this.register(new FID());
1370
+ _this.register(new LCP());
1371
+ _this.register(new LayoutShift());
1372
+ _this.register(new TTI());
1373
+ _this.register(new Timing());
1374
+ _this.register(new Resource());
1375
+ _this.register(new Memory());
1376
+ _this.register(new NavigatorInfo());
1377
+ _this.register(new Longtask());
1378
+ _this.visibilitychangeCB = _this.visibilitychangeCB.bind(_this);
1379
+ _this.load = _this.load.bind(_this);
1380
+ _this.leave = _this.leave.bind(_this);
1381
+ if (document.readyState === 'complete') {
1382
+ _this.load();
1383
+ }
1384
+ else {
1385
+ window.addEventListener('load', _this.load);
1386
+ }
1387
+ document.addEventListener('visibilitychange', _this.visibilitychangeCB);
1388
+ window.addEventListener('beforeunload', _this.leave, false);
1389
+ window.addEventListener('unload', _this.leave, false);
1390
+ _this.handleHead();
1391
+ return _this;
1392
+ }
1393
+ SpyClient.prototype.handleHead = function () {
1394
+ var _this = this;
1395
+ if (this.option.localCache) {
1396
+ var spyHead = window.__spyHead;
1397
+ if (spyHead && spyHead.winerrors) {
1398
+ for (var index = 0; index < spyHead.winerrors.length; index++) {
1399
+ var obj = spyHead.winerrors[index];
1400
+ this.option.localCache.addLog(obj);
1401
+ }
1402
+ // Head发送的异常,也保存一份到本地,主要是JS错误和资源加载异常
1403
+ spyHead.interceptor = function (obj) {
1404
+ _this.option.localCache.addLog(obj);
1405
+ };
1406
+ }
1407
+ }
1408
+ };
1409
+ SpyClient.prototype.listenFID = function (cb) {
1410
+ this.invoke('listenFID', cb);
1411
+ };
1412
+ SpyClient.prototype.listenLayoutShift = function (cb) {
1413
+ this.invoke('listenLayoutShift', cb);
1414
+ };
1415
+ SpyClient.prototype.listenLCP = function (cb) {
1416
+ this.invoke('listenLCP', cb);
1417
+ };
1418
+ SpyClient.prototype.listenFSPLongTask = function (cb) {
1419
+ this.invoke('listenFSPLongTask', cb);
1420
+ };
1421
+ SpyClient.prototype.listenLCPLongTask = function (cb) {
1422
+ this.invoke('listenLCPLongTask', cb);
1423
+ };
1424
+ SpyClient.prototype.listenLoadLongTask = function (cb) {
1425
+ this.invoke('listenLoadLongTask', cb);
1426
+ };
1427
+ SpyClient.prototype.listenPageLongTask = function (cb) {
1428
+ this.invoke('listenPageLongTask', cb);
1429
+ };
1430
+ SpyClient.prototype.listenMemory = function (cb) {
1431
+ this.invoke('listenMemory', cb);
1432
+ };
1433
+ SpyClient.prototype.getNavigatorInfo = function () {
1434
+ return this.invoke('getNavigatorInfo');
1435
+ };
1436
+ SpyClient.prototype.listenResource = function (cb, option) {
1437
+ this.invoke('listenResource', cb, option);
1438
+ };
1439
+ SpyClient.prototype.listenBigImg = function (cb, option) {
1440
+ this.invoke('listenBigImg', cb, option);
1441
+ };
1442
+ SpyClient.prototype.listenHttpResource = function (cb, option) {
1443
+ this.invoke('listenHttpResource', cb, option);
1444
+ };
1445
+ SpyClient.prototype.listenSlowResource = function (cb, option) {
1446
+ this.invoke('listenSlowResource', cb, option);
1447
+ };
1448
+ SpyClient.prototype.listenTiming = function (cb) {
1449
+ this.invoke('listenTiming', cb);
1450
+ };
1451
+ SpyClient.prototype.listenTTI = function (cb, option) {
1452
+ this.invoke('listenTTI', cb, option);
1453
+ };
1454
+ SpyClient.prototype.invoke = function (name, cb, option) {
1455
+ for (var index = 0; index < this.modules.length; index++) {
1456
+ var mod = this.modules[index];
1457
+ if (typeof mod[name] === 'function') {
1458
+ return mod[name].apply(mod, [cb, option]);
1459
+ }
1460
+ }
1461
+ console.error('no method', name);
1462
+ };
1463
+ SpyClient.prototype.register = function (mod) {
1464
+ this.modules.push(mod);
1465
+ };
1466
+ SpyClient.prototype.load = function () {
1467
+ for (var index = 0; index < this.modules.length; index++) {
1468
+ var mod = this.modules[index];
1469
+ mod.load && mod.load();
1470
+ }
1471
+ };
1472
+ SpyClient.prototype.leave = function () {
1473
+ for (var index = 0; index < this.modules.length; index++) {
1474
+ var mod = this.modules[index];
1475
+ mod.leave && mod.leave();
1476
+ }
1477
+ };
1478
+ SpyClient.prototype.destroy = function () {
1479
+ for (var index = 0; index < this.modules.length; index++) {
1480
+ var mod = this.modules[index];
1481
+ mod.destroy && mod.destroy();
1482
+ }
1483
+ document.removeEventListener('visibilitychange', this.visibilitychangeCB);
1484
+ window.removeEventListener('load', this.load);
1485
+ window.removeEventListener('beforeunload', this.leave);
1486
+ window.removeEventListener('unload', this.destroy);
1487
+ };
1488
+ SpyClient.prototype.visibilitychangeCB = function () {
1489
+ if (document.visibilityState === 'hidden') {
1490
+ this.leave();
1491
+ }
1492
+ };
1493
+ return SpyClient;
1487
1494
  }(SpyClient$1));
1488
1495
 
1489
1496
  export { SpyClient as default };