spy-client 2.1.14 → 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 +29 -18
  4. package/dist/head/base.d.ts +27 -25
  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 -28
  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 -104
  23. package/dist/spy-client-basic.esm.js +298 -294
  24. package/dist/spy-client-basic.iife.js +298 -294
  25. package/dist/spy-client-basic.iife.min.js +1 -1
  26. package/dist/spy-client-basic.js +298 -294
  27. package/dist/spy-client-basic.min.js +1 -1
  28. package/dist/spy-client-basic.mjs +298 -294
  29. package/dist/spy-client.d.ts +32 -32
  30. package/dist/spy-client.esm.js +1430 -1419
  31. package/dist/spy-client.iife.js +1430 -1419
  32. package/dist/spy-client.iife.min.js +1 -1
  33. package/dist/spy-client.js +1430 -1419
  34. package/dist/spy-client.min.js +1 -1
  35. package/dist/spy-client.mjs +1430 -1419
  36. package/dist/spy-head.d.ts +6 -6
  37. package/dist/spy-head.js +359 -355
  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,1450 +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
- // send(data, true) 也能以post发送,但是会有严格校验
365
- // sendPost能以post发送,但没有校验
366
- SpyClient.prototype.sendPost = function (data) {
367
- var logItems = isArray(data) ? data : [data];
368
- var first = logItems[0];
369
- // 需要在页面暴漏出来pid等基本信息,方式调试查看基本信息与兼容目前的监控
370
- var query = {
371
- pid: first.pid,
372
- type: first.type,
373
- group: first.group,
374
- };
375
- var url = this.option.logServer + stringify(query);
376
- this.request(url, data);
377
- };
378
- // 有data时,意味着要用post发送请求
379
- SpyClient.prototype.request = function (url, data) {
380
- if (!(!isLtIos14
381
- && navigator
382
- && navigator.sendBeacon
383
- && navigator.sendBeacon(url, data ? JSON.stringify(data) : undefined))) {
384
- if (data) {
385
- this.fetch(url, data);
386
- }
387
- else {
388
- (new Image()).src = url;
389
- }
390
- }
391
- };
392
- SpyClient.prototype.fetch = function (url, data) {
393
- if (!fetch) {
394
- err('Global fetch method doesn\'t exist');
395
- return;
396
- }
397
- fetch(url, {
398
- method: 'POST',
399
- credentials: 'include',
400
- headers: {
401
- 'Content-Type': 'application/json',
402
- },
403
- body: JSON.stringify(data),
404
- });
405
- };
406
- 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;
407
418
  }());
408
419
 
409
- /**
410
- * @file FID
411
- * @author kaivean
412
- */
413
- var spyclient$3 = window.__spyHead;
414
- var entryType$3 = 'first-input';
415
- var FID = /** @class */ (function () {
416
- function FID() {
417
- var _this = this;
418
- this.observer = null;
419
- if (!window.PerformanceObserver) {
420
- return;
421
- }
422
- if (spyclient$3 && spyclient$3.entryMap && spyclient$3.entryMap[entryType$3]) {
423
- this.handle(spyclient$3.entryMap[entryType$3]);
424
- }
425
- try {
426
- this.observer = new PerformanceObserver(function (list) {
427
- _this.handle(list.getEntries());
428
- });
429
- this.observer.observe({ entryTypes: [entryType$3] });
430
- }
431
- catch (e) { }
432
- }
433
- FID.prototype.listenFID = function (cb) {
434
- this.cb = cb;
435
- this.callCB();
436
- };
437
- FID.prototype.callCB = function () {
438
- if (this.finalValue !== undefined && this.cb) {
439
- this.cb({ fid: this.finalValue });
440
- }
441
- };
442
- FID.prototype.destroy = function () {
443
- this.observer && this.observer.disconnect();
444
- this.observer = null;
445
- };
446
- FID.prototype.handle = function (entries) {
447
- var lastEntry = entries.pop();
448
- if (lastEntry) {
449
- this.finalValue = lastEntry.duration;
450
- this.callCB();
451
- this.destroy();
452
- }
453
- };
454
- 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;
455
466
  }());
456
467
 
457
- /**
458
- * @file LayoutShift
459
- * @author kaivean
460
- */
461
- var spyclient$2 = window.__spyHead;
462
- var entryType$2 = 'layout-shift';
463
- var LayoutShift = /** @class */ (function () {
464
- function LayoutShift() {
465
- var _this = this;
466
- this.observer = null;
467
- this.onceLeave = false;
468
- if (!window.PerformanceObserver) {
469
- return;
470
- }
471
- // 先消费之前的
472
- if (spyclient$2 && spyclient$2.entryMap && spyclient$2.entryMap[entryType$2]) {
473
- this.handle(spyclient$2.entryMap[entryType$2]);
474
- }
475
- try {
476
- this.observer = new PerformanceObserver(function (list) {
477
- _this.handle(list.getEntries());
478
- });
479
- this.observer.observe({ entryTypes: [entryType$2] });
480
- }
481
- catch (e) { }
482
- }
483
- LayoutShift.prototype.listenLayoutShift = function (cb) {
484
- this.cb = cb;
485
- };
486
- LayoutShift.prototype.leave = function () {
487
- if (!this.onceLeave) {
488
- this.onceLeave = true;
489
- this.observer && this.observer.takeRecords && this.observer.takeRecords();
490
- this.finalValue = this.value;
491
- this.callCB();
492
- this.destroy();
493
- }
494
- };
495
- LayoutShift.prototype.callCB = function () {
496
- if (this.finalValue !== undefined && this.cb) {
497
- this.cb({ layoutShift: this.finalValue });
498
- }
499
- };
500
- LayoutShift.prototype.destroy = function () {
501
- this.observer && this.observer.disconnect();
502
- this.observer = null;
503
- };
504
- LayoutShift.prototype.handle = function (entries) {
505
- var _this = this;
506
- entries.map(function (entry) {
507
- // hadRecentInput 如果过去500毫秒内有用户输入,则返回 true, 刚进入页面内500ms,不会认为是layoutShift
508
- if (!entry.hadRecentInput) {
509
- _this.value = (_this.value || 0) + (entry.value || 0);
510
- }
511
- });
512
- };
513
- 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;
514
525
  }());
515
526
 
516
- /**
517
- * @file 简单的公共数据模块,内部模块之间数据交换
518
- * @author kaivean
519
- */
520
- var data = {};
521
- function setData(key, value) {
522
- data[key] = value;
523
- }
524
- function getData(key) {
525
- 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];
526
537
  }
527
538
 
528
- /**
529
- * @file LCP
530
- * @author kaivean
531
- */
532
- var spyclient$1 = window.__spyHead;
533
- var entryType$1 = 'largest-contentful-paint';
534
- var LCP = /** @class */ (function () {
535
- function LCP() {
536
- var _this = this;
537
- this.observer = null;
538
- if (!window.PerformanceObserver) {
539
- return;
540
- }
541
- if (spyclient$1 && spyclient$1.entryMap && spyclient$1.entryMap[entryType$1]) {
542
- this.handle(spyclient$1.entryMap[entryType$1]);
543
- }
544
- try {
545
- // 仅在 img,image,svg,video,css url, block element with text nodes
546
- this.observer = new PerformanceObserver(function (list) {
547
- _this.handle(list.getEntries());
548
- });
549
- this.observer.observe({ entryTypes: [entryType$1] });
550
- }
551
- catch (e) { }
552
- }
553
- LCP.prototype.listenLCP = function (cb) {
554
- this.cb = cb;
555
- this.callCB();
556
- };
557
- LCP.prototype.callCB = function () {
558
- if (this.finalValue && this.cb) {
559
- this.cb({ lcp: this.finalValue });
560
- }
561
- };
562
- LCP.prototype.load = function () {
563
- this.observer && this.observer.takeRecords && this.observer.takeRecords();
564
- this.finalValue = this.value;
565
- setData('lcp', this.value);
566
- this.callCB();
567
- this.destroy();
568
- };
569
- LCP.prototype.destroy = function () {
570
- this.observer && this.observer.disconnect();
571
- this.observer = null;
572
- };
573
- LCP.prototype.handle = function (entries) {
574
- var _this = this;
575
- entries.map(function (entry) {
576
- _this.value = entry.renderTime || entry.loadTime;
577
- });
578
- };
579
- 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;
580
591
  }());
581
592
 
582
- function filterExcludeLogGifs(entry) {
583
- return entry.name.indexOf('.gif?') < 0;
584
- }
585
- var TTI = /** @class */ (function () {
586
- function TTI() {
587
- this.lastLongTask = 0;
588
- this.observer = null;
589
- this.interval = 5000;
590
- this.filterRequest = filterExcludeLogGifs;
591
- this.observerCallback = this.observerCallback.bind(this);
592
- this.ttiCheck = this.ttiCheck.bind(this);
593
- }
594
- TTI.prototype.check = function () {
595
- return window.PerformanceObserver && performance && performance.timing && performance.timing.navigationStart;
596
- };
597
- TTI.prototype.listenTTI = function (cb, option) {
598
- if (!this.check()) {
599
- return;
600
- }
601
- // 监听获取longtask,持续20s
602
- this.observeLongtask(20000);
603
- this.cb = cb;
604
- option = option || {};
605
- if (option.interval) {
606
- this.interval = option.interval;
607
- }
608
- if (option.filterRequest) {
609
- this.filterRequest = option.filterRequest;
610
- }
611
- };
612
- TTI.prototype.load = function () {
613
- if (!this.check()) {
614
- return;
615
- }
616
- // 每 5 秒检查一次是否符合TTI要求
617
- this.ttiTimer = setInterval(this.ttiCheck, this.interval);
618
- };
619
- TTI.prototype.ttiCheck = function () {
620
- if (!this.cb) {
621
- return;
622
- }
623
- var now = performance.now();
624
- if (now - this.lastLongTask < this.interval) {
625
- // debug('tti 没有达成条件,上次 longTask 离现在差' + (now - this.lastLongTask) + 'ms');
626
- return;
627
- }
628
- var networkSilence = this.getNetworkSilenceAt();
629
- if (networkSilence === false) {
630
- // debug('tti 没有达成条件,网络没有静默');
631
- return;
632
- }
633
- if (now - networkSilence < this.interval) {
634
- // debug('tti 没有达成条件,上次网络请求离现在差' + (now - networkSilence) + 'ms');
635
- return;
636
- }
637
- // debug('tti 达成条件');
638
- clearTimeout(this.ttiTimer);
639
- var tti = this.lastLongTask;
640
- // 没有longtask,就用dom ready时间作为tti,默认是认为dom ready已经绑定好时间,可以交换了
641
- if (!tti) {
642
- tti = performance.timing.domContentLoadedEventEnd - performance.timing.navigationStart;
643
- }
644
- // 停止 long task 获取
645
- this.stopObserveLongTask();
646
- this.cb({
647
- tti: tti,
648
- });
649
- };
650
- TTI.prototype.observerCallback = function (list) {
651
- var entries = list.getEntries();
652
- var lastEntry = entries[entries.length - 1];
653
- // debug('long task (no more than ' + lastEntry.duration + 'ms) detected');
654
- // 最新的longTask完成时间
655
- this.lastLongTask = lastEntry.startTime + lastEntry.duration;
656
- };
657
- TTI.prototype.stopObserveLongTask = function () {
658
- if (this.observer) {
659
- this.observer.disconnect();
660
- this.observer = null;
661
- }
662
- if (this.stopLongTaskTimeoutId) {
663
- clearTimeout(this.stopLongTaskTimeoutId);
664
- }
665
- };
666
- TTI.prototype.getNetworkSilenceAt = function () {
667
- // const now = performance.now();
668
- var resources = performance.getEntriesByType('resource')
669
- .filter(this.filterRequest);
670
- var lastResourceEnd = 0;
671
- for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {
672
- var item = resources_1[_i];
673
- // 还没有responseEnd字段,说明网络请求还未结束
674
- if (!item.responseEnd) {
675
- return false;
676
- }
677
- // 取responseEnd最大值
678
- if (item.responseEnd > lastResourceEnd) {
679
- lastResourceEnd = item.responseEnd;
680
- }
681
- }
682
- return lastResourceEnd;
683
- };
684
- TTI.prototype.observeLongtask = function (timeout) {
685
- this.stopObserveLongTask();
686
- try {
687
- this.observer = new PerformanceObserver(this.observerCallback);
688
- this.observer.observe({
689
- entryTypes: ['longtask'],
690
- });
691
- this.stopLongTaskTimeoutId = setTimeout(this.stopObserveLongTask, timeout);
692
- }
693
- catch (e) { }
694
- };
695
- 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;
696
707
  }());
697
708
 
698
- /**
699
- * @file LCP
700
- * @author kaivean
701
- */
702
- var Timing = /** @class */ (function () {
703
- function Timing() {
704
- }
705
- // constructor() {}
706
- Timing.prototype.listenTiming = function (cb) {
707
- if (!window.performance || !window.performance.timing) {
708
- // debug('no performance.timing api');
709
- return;
710
- }
711
- this.cb = cb;
712
- };
713
- Timing.prototype.load = function () {
714
- var _this = this;
715
- setTimeout(function () {
716
- _this.cb && _this.cb(_this.getMetric());
717
- }, 500);
718
- };
719
- Timing.prototype.getMetric = function () {
720
- var metric = {};
721
- var timing = window.performance.timing;
722
- var startTime = timing.navigationStart;
723
- // 基础信息
724
- metric.dns = timing.domainLookupEnd - timing.domainLookupStart;
725
- metric.tcp = timing.connectEnd - timing.connectStart;
726
- metric.request = timing.responseStart - timing.requestStart;
727
- metric.response = timing.responseEnd - timing.responseStart;
728
- // 这是从页面部分数据返回,浏览器开始解析doc元素到最底部的script脚本解析执行完成
729
- // 脚本里触发的异步或绑定了更靠后的事件,不再纳入范围内
730
- metric.parseHtml = timing.domInteractive - timing.domLoading;
731
- // 很多事件绑定是在domContentLoaded事件里的,所以等其结束,一般页面元素的事件绑定好了,用户可以正确交互
732
- // 当然存在在该加载事件之后绑定元素事件情况,但不再此考虑范围内
733
- metric.domReady = timing.domContentLoadedEventEnd - startTime;
734
- metric.loadEventHandle = timing.loadEventEnd - timing.loadEventStart;
735
- // 基本该做的都做完,资源也都加载完成了
736
- // 当然在onload事件处理函数里启动了异步方法,不再纳入范围内
737
- metric.load = timing.loadEventEnd - startTime;
738
- // 浏览器首次绘制与首次内容绘制, ios低版本无getEntriesByType api
739
- if (performance.getEntriesByType) {
740
- var paintEntries = performance.getEntriesByType('paint');
741
- if (paintEntries && paintEntries.length) {
742
- paintEntries.forEach(function (_a) {
743
- var name = _a.name, duration = _a.duration, startTime = _a.startTime;
744
- var time = Math.ceil(duration + startTime);
745
- if (name === 'first-paint') {
746
- metric.fp = time;
747
- }
748
- if (name === 'first-contentful-paint') {
749
- metric.fcp = time;
750
- }
751
- });
752
- }
753
- }
754
- // 端首次绘制与首屏
755
- if (timing.domFirstPaint) {
756
- metric.t7FirstPaint = timing.domFirstPaint - startTime;
757
- }
758
- if (timing.domFirstScreenPaint) {
759
- metric.t7FirstScreen = timing.domFirstScreenPaint - startTime;
760
- }
761
- return metric;
762
- };
763
- 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;
764
775
  }());
765
776
 
766
- var ResType;
767
- (function (ResType) {
768
- ResType["JS"] = "js";
769
- ResType["CSS"] = "css";
770
- ResType["IMG"] = "img";
771
- 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";
772
783
  })(ResType || (ResType = {}));
773
784
 
774
- // 字体
775
- // svg使用场景比较灵活,可能作为一种字体格式,也可能当做图片使用
776
- // 但因woff在所有现代浏览器中都支持,在css中使用iconfont时
777
- // 往往优先加载woff格式字体文件,所以这里将svg划分为图片一类
778
- var FontsTypes;
779
- (function (FontsTypes) {
780
- FontsTypes[FontsTypes["ttf"] = 0] = "ttf";
781
- FontsTypes[FontsTypes["eot"] = 1] = "eot";
782
- FontsTypes[FontsTypes["woff"] = 2] = "woff";
783
- FontsTypes[FontsTypes["woff2"] = 3] = "woff2";
784
- })(FontsTypes || (FontsTypes = {}));
785
- // 忽略图片
786
- // 下述图片路径往往是用来进行日志统计,不是正常图片
787
- var ignoreDefaultPaths = [
788
- '/mwb2.gif',
789
- ];
790
- function ignorePath(url, paths) {
791
- for (var _i = 0, paths_1 = paths; _i < paths_1.length; _i++) {
792
- var path = paths_1[_i];
793
- if (url.indexOf(path) > -1) {
794
- return true;
795
- }
796
- }
797
- return false;
798
- }
799
- function f(n) {
800
- return +n.toFixed(1);
801
- }
802
- var Resource = /** @class */ (function () {
803
- function Resource() {
804
- this.trigger = 'load';
805
- this.jsList = [];
806
- this.cssList = [];
807
- this.imgList = [];
808
- this.fontList = [];
809
- this.hostList = {};
810
- this.bigImgList = {};
811
- this.httpResList = {};
812
- this.slowList = {};
813
- this.resOption = { ignorePaths: [], trigger: 'load' };
814
- this.bigImgOption = { ignorePaths: [], maxSize: 150 * 1024, trigger: 'load' };
815
- this.httpResOption = { ignorePaths: [], trigger: 'load' };
816
- this.slowOption = { ignorePaths: [], trigger: 'load', threshold: 1000 };
817
- }
818
- Resource.prototype.check = function () {
819
- return performance && performance.getEntriesByType;
820
- };
821
- Resource.prototype.listenResource = function (cb, option) {
822
- if (option === void 0) { option = {}; }
823
- if (!this.check()) {
824
- return;
825
- }
826
- this.resOption = assign(this.resOption, option);
827
- this.trigger = this.resOption.trigger;
828
- this.cb = cb;
829
- };
830
- Resource.prototype.listenBigImg = function (cb, option) {
831
- if (option === void 0) { option = {}; }
832
- if (!this.check()) {
833
- return;
834
- }
835
- this.bigImgOption = assign(this.bigImgOption, option);
836
- this.trigger = this.bigImgOption.trigger;
837
- this.bigImgCB = cb;
838
- };
839
- Resource.prototype.listenHttpResource = function (cb, option) {
840
- if (option === void 0) { option = {}; }
841
- if (!this.check()) {
842
- return;
843
- }
844
- this.httpResOption = assign(this.httpResOption, option);
845
- this.trigger = this.httpResOption.trigger;
846
- this.httpResCB = cb;
847
- };
848
- Resource.prototype.listenSlowResource = function (cb, option) {
849
- if (option === void 0) { option = {}; }
850
- if (!this.check()) {
851
- return;
852
- }
853
- this.slowOption = assign(this.slowOption, option);
854
- this.trigger = this.slowOption.trigger;
855
- this.slowResCB = cb;
856
- };
857
- Resource.prototype.report = function () {
858
- var _this = this;
859
- var metricRes = this.getMetric();
860
- if (metricRes) {
861
- var metric = metricRes.metric, hostMetric = metricRes.hostMetric;
862
- this.cb && this.cb(metric, hostMetric);
863
- }
864
- if (this.bigImgCB) {
865
- // 发送大图监控数据
866
- if (typeof window.requestIdleCallback === 'function' && Object.keys(this.bigImgList).length) {
867
- window.requestIdleCallback(function () {
868
- for (var _i = 0, _a = Object.keys(_this.bigImgList); _i < _a.length; _i++) {
869
- var host = _a[_i];
870
- for (var _b = 0, _c = _this.bigImgList[host]; _b < _c.length; _b++) {
871
- var entry = _c[_b];
872
- var timing = entry.timing;
873
- var type = entry.type;
874
- try {
875
- var img = document.body.querySelector('img[src="' + timing.name + '"]');
876
- _this.bigImgCB({
877
- msg: timing.name,
878
- dur: timing.duration,
879
- xpath: getxpath(img).xpath,
880
- host: host,
881
- type: type,
882
- });
883
- }
884
- catch (e) {
885
- console.error(e);
886
- }
887
- }
888
- }
889
- });
890
- }
891
- }
892
- if (this.httpResCB) {
893
- // 发送http资源监控数据
894
- if (typeof window.requestIdleCallback === 'function' && Object.keys(this.httpResList).length) {
895
- window.requestIdleCallback(function () {
896
- for (var _i = 0, _a = Object.keys(_this.httpResList); _i < _a.length; _i++) {
897
- var host = _a[_i];
898
- for (var _b = 0, _c = _this.httpResList[host]; _b < _c.length; _b++) {
899
- var entry = _c[_b];
900
- var timing = entry.timing;
901
- var type = entry.type;
902
- try {
903
- var img = document.body.querySelector('[src="' + timing.name + '"]');
904
- _this.httpResCB({
905
- msg: timing.name,
906
- dur: timing.duration,
907
- xpath: getxpath(img).xpath,
908
- host: host,
909
- type: type,
910
- });
911
- }
912
- catch (e) {
913
- console.error(e);
914
- }
915
- }
916
- }
917
- });
918
- }
919
- }
920
- if (this.slowResCB) {
921
- // 发送慢资源监控数据
922
- if (typeof window.requestIdleCallback === 'function' && Object.keys(this.slowList).length) {
923
- window.requestIdleCallback(function () {
924
- for (var _i = 0, _a = Object.keys(_this.slowList); _i < _a.length; _i++) {
925
- var host = _a[_i];
926
- for (var _b = 0, _c = _this.slowList[host]; _b < _c.length; _b++) {
927
- var entry = _c[_b];
928
- var timing = entry.timing;
929
- var type = entry.type;
930
- try {
931
- var img = document.body.querySelector('[src="' + timing.name + '"]');
932
- var info = getResTiming(timing);
933
- _this.slowResCB(__assign(__assign({}, info), { dur: timing.duration, msg: timing.name, xpath: getxpath(img).xpath, host: host, type: type }));
934
- }
935
- catch (e) {
936
- console.error(e);
937
- }
938
- }
939
- }
940
- });
941
- }
942
- }
943
- };
944
- Resource.prototype.load = function () {
945
- var _this = this;
946
- if (this.trigger !== 'load') {
947
- return;
948
- }
949
- if (!this.check()) {
950
- return;
951
- }
952
- setTimeout(function () {
953
- _this.report();
954
- }, 500);
955
- };
956
- Resource.prototype.leave = function () {
957
- if (this.trigger !== 'leave') {
958
- return;
959
- }
960
- this.report();
961
- };
962
- Resource.prototype.push = function (type, list, timing, urlInfo) {
963
- if (!ignorePath(urlInfo.pathname, this.resOption.ignorePaths || [])) {
964
- list.push(timing);
965
- this.pushWithHost(type, this.hostList, timing, urlInfo);
966
- }
967
- if (!ignorePath(urlInfo.pathname, this.slowOption.ignorePaths || [])) {
968
- if (timing.duration > this.slowOption.threshold) {
969
- this.pushWithHost(type, this.slowList, timing, urlInfo);
970
- }
971
- }
972
- };
973
- Resource.prototype.pushWithHost = function (type, list, timing, urlInfo) {
974
- var host = urlInfo.host;
975
- if (!list[host]) {
976
- list[host] = [];
977
- }
978
- list[host].push({
979
- timing: timing,
980
- type: type,
981
- });
982
- };
983
- Resource.prototype.collectHttpResInHttps = function (type, timing, urlInfo) {
984
- if (location.protocol === 'https:'
985
- && timing.name.indexOf('http://') === 0
986
- && !ignorePath(urlInfo.pathname, this.httpResOption.ignorePaths || [])) {
987
- this.pushWithHost(type, this.httpResList, timing, urlInfo);
988
- }
989
- };
990
- // 有些jsonp也属于script,这里只统计js后缀的文件
991
- Resource.prototype.addScript = function (timing, urlInfo) {
992
- if (urlInfo.ext === 'js') {
993
- if (timing.decodedBodySize !== 0) {
994
- this.push('js', this.jsList, timing, urlInfo);
995
- }
996
- }
997
- };
998
- // 暂时将css文件或代码块发起的请求归位三类(主要为这两类)
999
- // 1、加载字体
1000
- // 2、加载背景图(图片不容易区分,有的没有明确后缀名)
1001
- // 3、光标文件(后缀为.cur,这里也划分为图片)
1002
- // (svg当做图片,前述已说明)
1003
- Resource.prototype.addResFromCss = function (timing, urlInfo) {
1004
- if (urlInfo.ext && FontsTypes.hasOwnProperty(urlInfo.ext)) {
1005
- this.push('font', this.fontList, timing, urlInfo);
1006
- }
1007
- else {
1008
- this.addImg(timing, urlInfo);
1009
- }
1010
- };
1011
- // link一般加载css资源
1012
- // 也可以通过preload可以预下载一些资源
1013
- // 这里只统计js类型的preload
1014
- Resource.prototype.addLink = function (timing, urlInfo) {
1015
- if (urlInfo.ext === 'css') {
1016
- this.push('css', this.cssList, timing, urlInfo);
1017
- }
1018
- // preload as script
1019
- else if (urlInfo.ext === 'js') {
1020
- this.push('js', this.jsList, timing, urlInfo);
1021
- }
1022
- };
1023
- Resource.prototype.addImg = function (timing, urlInfo) {
1024
- this.push('img', this.imgList, timing, urlInfo);
1025
- // 大于指定size的图片采集
1026
- if (timing.decodedBodySize > (this.bigImgOption.maxSize || 0)
1027
- && !ignorePath(urlInfo.pathname, this.bigImgOption.ignorePaths || [])) {
1028
- this.pushWithHost('img', this.bigImgList, timing, urlInfo);
1029
- }
1030
- };
1031
- Resource.prototype.handleTimings = function (list) {
1032
- var len = list.length;
1033
- for (var i = 0; i < len; i++) {
1034
- var timing = list[i];
1035
- var urlInfo = getUrlInfo(timing.name);
1036
- if (ignorePath(urlInfo.pathname, ignoreDefaultPaths)) {
1037
- continue;
1038
- }
1039
- switch (list[i].initiatorType) {
1040
- case 'script':
1041
- this.addScript(timing, urlInfo);
1042
- break;
1043
- case 'css':
1044
- this.addResFromCss(timing, urlInfo);
1045
- break;
1046
- case 'img':
1047
- this.addImg(timing, urlInfo);
1048
- break;
1049
- case 'link':
1050
- this.addLink(timing, urlInfo);
1051
- break;
1052
- case 'audio':
1053
- this.collectHttpResInHttps('audio', timing, urlInfo);
1054
- break;
1055
- case 'video':
1056
- this.collectHttpResInHttps('video', timing, urlInfo);
1057
- break;
1058
- }
1059
- }
1060
- };
1061
- Resource.prototype.getNumAndSize = function (type, list) {
1062
- var obj = {};
1063
- var num = type + 'Num';
1064
- var size = type + 'Size';
1065
- var transferSize = type + 'TransferSize';
1066
- var cacheRate = type + 'CacheRate';
1067
- var duration = type + 'Duration';
1068
- obj[num] = 0;
1069
- obj[size] = 0;
1070
- obj[transferSize] = 0;
1071
- var totalDurationTime = 0;
1072
- list.forEach(function (timing) {
1073
- obj[num]++;
1074
- obj[size] += (timing.decodedBodySize / 1024);
1075
- obj[transferSize] += (timing.transferSize / 1024);
1076
- totalDurationTime += timing.duration;
1077
- });
1078
- obj[duration] = f(obj[num] > 0 ? totalDurationTime / obj[num] : 0);
1079
- if (obj[size]) {
1080
- var diff = obj[size] - obj[transferSize];
1081
- obj[cacheRate] = f(diff >= 0 ? 100 * diff / obj[size] : 0);
1082
- }
1083
- obj[size] = f(obj[size]);
1084
- obj[transferSize] = f(obj[transferSize]);
1085
- return obj;
1086
- };
1087
- Resource.prototype.getMetric = function () {
1088
- // 原来代码
1089
- var mainPageTiming = performance.getEntriesByType('navigation')[0];
1090
- var resourceTimings = performance.getEntriesByType('resource');
1091
- if (mainPageTiming && resourceTimings && resourceTimings.length) {
1092
- this.handleTimings(resourceTimings);
1093
- 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));
1094
- // 主文档大小
1095
- var pageTiming = mainPageTiming;
1096
- metric.docSize = f(pageTiming.decodedBodySize / 1024);
1097
- metric.docTransferSize = f(pageTiming.transferSize / 1024);
1098
- metric.headerSize = f((pageTiming.transferSize - pageTiming.encodedBodySize || 0) / 1024);
1099
- metric.allSize = f(metric.docSize
1100
- + metric.jsSize
1101
- + metric.cssSize
1102
- + metric.imgSize
1103
- + metric.fontSize);
1104
- metric.allTransferSize = f(metric.docTransferSize
1105
- + metric.jsTransferSize
1106
- + metric.cssTransferSize
1107
- + metric.imgTransferSize
1108
- + metric.fontTransferSize);
1109
- var hostMetric = {};
1110
- for (var _i = 0, _a = Object.keys(this.hostList); _i < _a.length; _i++) {
1111
- var host = _a[_i];
1112
- var timings = this.hostList[host].map(function (item) { return item.timing; });
1113
- hostMetric[host] = this.getNumAndSize('host', timings);
1114
- }
1115
- return { metric: metric, hostMetric: hostMetric };
1116
- }
1117
- return;
1118
- };
1119
- 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;
1120
1131
  }());
1121
1132
 
1122
- /**
1123
- * @file Memory
1124
- * @author kaivean
1125
- */
1126
- var initMemory = null;
1127
- if (window.performance && window.performance.memory) {
1128
- initMemory = window.performance.memory;
1129
- }
1130
- var Memory = /** @class */ (function () {
1131
- function Memory() {
1132
- this.onceLeave = false;
1133
- }
1134
- // constructor() {}
1135
- Memory.prototype.listenMemory = function (cb) {
1136
- this.cb = cb;
1137
- };
1138
- Memory.prototype.leave = function () {
1139
- if (!this.onceLeave && initMemory) {
1140
- this.onceLeave = true;
1141
- var curMemory = window.performance.memory;
1142
- // fix 早期浏览器的memroy api 值不更新的问题,将此情况排除
1143
- if (curMemory.usedJSHeapSize === initMemory.usedJSHeapSize
1144
- && curMemory.totalJSHeapSize === initMemory.totalJSHeapSize) {
1145
- return;
1146
- }
1147
- var memory = window.performance.memory;
1148
- this.cb && this.cb({
1149
- usedJSHeapSize: memory.usedJSHeapSize / 1024,
1150
- totalJSHeapSize: memory.totalJSHeapSize / 1024,
1151
- jsHeapSizeLimit: memory.jsHeapSizeLimit / 1024,
1152
- usedJSHeapRate: 100 * memory.usedJSHeapSize / memory.totalJSHeapSize,
1153
- });
1154
- }
1155
- };
1156
- 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;
1157
1168
  }());
1158
1169
 
1159
- /**
1160
- * @file NavigatorInfo
1161
- * @author kaivean
1162
- */
1163
- var NavigatorInfo = /** @class */ (function () {
1164
- function NavigatorInfo() {
1165
- }
1166
- // private cb: NavigatorInfoCB;
1167
- NavigatorInfo.prototype.getNavigatorInfo = function () {
1168
- // this.cb = cb;
1169
- var ret = {};
1170
- var dataConnection = navigator.connection;
1171
- if (typeof dataConnection === 'object') {
1172
- ret = {
1173
- downlink: dataConnection.downlink,
1174
- effectiveType: dataConnection.effectiveType,
1175
- rtt: dataConnection.rtt,
1176
- saveData: !!dataConnection.saveData, // 数据节约模式
1177
- };
1178
- }
1179
- // 内存 G
1180
- if (navigator.deviceMemory) {
1181
- ret.deviceMemory = navigator.deviceMemory;
1182
- }
1183
- // 核数
1184
- if (navigator.hardwareConcurrency) {
1185
- ret.hardwareConcurrency = navigator.deviceMemory;
1186
- }
1187
- return ret;
1188
- };
1189
- NavigatorInfo.prototype.load = function () { };
1190
- 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;
1191
1202
  }());
1192
1203
 
1193
- /**
1194
- * @file Longtask
1195
- * @author kaivean
1196
- */
1197
- var spyclient = window.__spyHead;
1198
- var entryType = 'longtask';
1199
- var Longtask = /** @class */ (function () {
1200
- function Longtask() {
1201
- var _this = this;
1202
- this.lts = [];
1203
- this.observer = null;
1204
- this.onceLeave = false;
1205
- if (spyclient && spyclient.entryMap && spyclient.entryMap[entryType]) {
1206
- this.lts = this.lts.concat(spyclient.entryMap[entryType]);
1207
- }
1208
- try {
1209
- this.observer = new PerformanceObserver(function (list) {
1210
- _this.lts = _this.lts.concat(list.getEntries());
1211
- });
1212
- // buffered 兼容性太差
1213
- this.observer.observe({ entryTypes: [entryType] });
1214
- }
1215
- catch (e) { }
1216
- }
1217
- Longtask.prototype.check = function () {
1218
- return window.PerformanceObserver && performance && performance.timing && performance.timing.navigationStart;
1219
- };
1220
- Longtask.prototype.listenFSPLongTask = function (cb) {
1221
- if (!this.check()) {
1222
- return;
1223
- }
1224
- this.fspCB = cb;
1225
- };
1226
- Longtask.prototype.listenLCPLongTask = function (cb) {
1227
- if (!this.check()) {
1228
- return;
1229
- }
1230
- this.lcpCB = cb;
1231
- };
1232
- Longtask.prototype.listenLoadLongTask = function (cb) {
1233
- if (!this.check()) {
1234
- return;
1235
- }
1236
- this.loadCB = cb;
1237
- };
1238
- Longtask.prototype.listenPageLongTask = function (cb) {
1239
- if (!this.check()) {
1240
- return;
1241
- }
1242
- this.pageCB = cb;
1243
- };
1244
- Longtask.prototype.load = function () {
1245
- var _this = this;
1246
- if (!this.check()) {
1247
- return;
1248
- }
1249
- var data = this.getStatData(Date.now());
1250
- // lcp的值存入data模块也是在load期间,这里延迟一会再获取
1251
- setTimeout(function () {
1252
- _this.loadCB && _this.loadCB({
1253
- loadLongtaskTime: data.time,
1254
- loadTBT: data.tbt,
1255
- loadTotalTime: data.totalTime,
1256
- loadLongtaskRate: data.rate,
1257
- loadLongtaskNum: data.num,
1258
- });
1259
- if (performance.timing && performance.timing.domFirstScreenPaint) {
1260
- var data_1 = _this.getStatData(performance.timing.domFirstScreenPaint);
1261
- _this.fspCB && _this.fspCB({
1262
- fspLongtaskTime: data_1.time,
1263
- fspTBT: data_1.tbt,
1264
- fspTotalTime: data_1.totalTime,
1265
- fspLongtaskRate: data_1.rate,
1266
- fspLongtaskNum: data_1.num,
1267
- });
1268
- }
1269
- if (getData('lcp')) {
1270
- var data_2 = _this.getStatData(performance.timing.navigationStart + getData('lcp'));
1271
- _this.lcpCB && _this.lcpCB({
1272
- lcpLongtaskTime: data_2.time,
1273
- lcpTBT: data_2.tbt,
1274
- lcpTotalTime: data_2.totalTime,
1275
- lcpLongtaskRate: data_2.rate,
1276
- lcpLongtaskNum: data_2.num,
1277
- });
1278
- }
1279
- }, 200);
1280
- };
1281
- Longtask.prototype.leave = function () {
1282
- if (!this.onceLeave) {
1283
- this.onceLeave = true;
1284
- var data = this.getStatData(Date.now());
1285
- this.pageCB && this.pageCB({
1286
- pageLongtaskTime: data.time,
1287
- pageTBT: data.tbt,
1288
- pageTotalTime: data.totalTime,
1289
- pageLongtaskRate: data.rate,
1290
- pageLongtaskNum: data.num,
1291
- pageIframeLongtaskTime: data.iframeTime,
1292
- pageIframeLongtaskRate: data.iframeRate,
1293
- pageIframeLongtaskNum: data.iframeNum,
1294
- });
1295
- }
1296
- };
1297
- Longtask.prototype.destroy = function () {
1298
- this.lts = [];
1299
- this.observer && this.observer.disconnect();
1300
- this.observer = null;
1301
- };
1302
- Longtask.prototype.getStatData = function (finalTime) {
1303
- var navigationStart = performance.timing.navigationStart;
1304
- var time = 0;
1305
- // Total Blocking Time
1306
- var tbt = 0;
1307
- var num = 0;
1308
- var iframeTime = 0;
1309
- var iframeNum = 0;
1310
- var iframeLongtasks = {};
1311
- for (var index = 0; index < this.lts.length; index++) {
1312
- var item = this.lts[index];
1313
- var duration = item.duration;
1314
- var end = navigationStart + item.startTime + duration;
1315
- if (end < finalTime) {
1316
- time += duration;
1317
- // 多出来的时间
1318
- tbt += (duration - 50 > 0 ? duration - 50 : 0);
1319
- num++;
1320
- if (item.attribution && item.attribution[0]) {
1321
- var containerSrc = item.attribution[0].containerSrc;
1322
- if (containerSrc && containerSrc !== location.href) {
1323
- if (!iframeLongtasks[containerSrc]) {
1324
- iframeLongtasks[containerSrc] = [];
1325
- }
1326
- iframeLongtasks[containerSrc].push(duration);
1327
- iframeTime += duration;
1328
- iframeNum++;
1329
- }
1330
- }
1331
- }
1332
- }
1333
- var totalTime = finalTime - navigationStart;
1334
- return {
1335
- num: num,
1336
- time: time,
1337
- tbt: tbt,
1338
- totalTime: totalTime,
1339
- rate: 100 * time / totalTime,
1340
- iframeTime: iframeTime,
1341
- iframeNum: iframeNum,
1342
- iframeRate: 100 * iframeTime / totalTime,
1343
- iframeLongtasks: iframeLongtasks,
1344
- };
1345
- };
1346
- 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;
1347
1358
  }());
1348
1359
 
1349
- /**
1350
- * @file SpyClient
1351
- * @author kaivean
1352
- */
1353
- var SpyClient = /** @class */ (function (_super) {
1354
- __extends(SpyClient, _super);
1355
- function SpyClient(option) {
1356
- var _this = _super.call(this, option) || this;
1357
- _this.modules = [];
1358
- _this.register(new FID());
1359
- _this.register(new LCP());
1360
- _this.register(new LayoutShift());
1361
- _this.register(new TTI());
1362
- _this.register(new Timing());
1363
- _this.register(new Resource());
1364
- _this.register(new Memory());
1365
- _this.register(new NavigatorInfo());
1366
- _this.register(new Longtask());
1367
- _this.visibilitychangeCB = _this.visibilitychangeCB.bind(_this);
1368
- _this.load = _this.load.bind(_this);
1369
- _this.leave = _this.leave.bind(_this);
1370
- if (document.readyState === 'complete') {
1371
- _this.load();
1372
- }
1373
- else {
1374
- window.addEventListener('load', _this.load);
1375
- }
1376
- document.addEventListener('visibilitychange', _this.visibilitychangeCB);
1377
- window.addEventListener('beforeunload', _this.leave, false);
1378
- window.addEventListener('unload', _this.leave, false);
1379
- _this.handleHead();
1380
- return _this;
1381
- }
1382
- SpyClient.prototype.handleHead = function () {
1383
- var _this = this;
1384
- if (this.option.localCache) {
1385
- var spyHead = window.__spyHead;
1386
- if (spyHead && spyHead.winerrors) {
1387
- for (var index = 0; index < spyHead.winerrors.length; index++) {
1388
- var obj = spyHead.winerrors[index];
1389
- this.option.localCache.addLog(obj);
1390
- }
1391
- // Head发送的异常,也保存一份到本地,主要是JS错误和资源加载异常
1392
- spyHead.interceptor = function (obj) {
1393
- _this.option.localCache.addLog(obj);
1394
- };
1395
- }
1396
- }
1397
- };
1398
- SpyClient.prototype.listenFID = function (cb) {
1399
- this.invoke('listenFID', cb);
1400
- };
1401
- SpyClient.prototype.listenLayoutShift = function (cb) {
1402
- this.invoke('listenLayoutShift', cb);
1403
- };
1404
- SpyClient.prototype.listenLCP = function (cb) {
1405
- this.invoke('listenLCP', cb);
1406
- };
1407
- SpyClient.prototype.listenFSPLongTask = function (cb) {
1408
- this.invoke('listenFSPLongTask', cb);
1409
- };
1410
- SpyClient.prototype.listenLCPLongTask = function (cb) {
1411
- this.invoke('listenLCPLongTask', cb);
1412
- };
1413
- SpyClient.prototype.listenLoadLongTask = function (cb) {
1414
- this.invoke('listenLoadLongTask', cb);
1415
- };
1416
- SpyClient.prototype.listenPageLongTask = function (cb) {
1417
- this.invoke('listenPageLongTask', cb);
1418
- };
1419
- SpyClient.prototype.listenMemory = function (cb) {
1420
- this.invoke('listenMemory', cb);
1421
- };
1422
- SpyClient.prototype.getNavigatorInfo = function () {
1423
- return this.invoke('getNavigatorInfo');
1424
- };
1425
- SpyClient.prototype.listenResource = function (cb, option) {
1426
- this.invoke('listenResource', cb, option);
1427
- };
1428
- SpyClient.prototype.listenBigImg = function (cb, option) {
1429
- this.invoke('listenBigImg', cb, option);
1430
- };
1431
- SpyClient.prototype.listenHttpResource = function (cb, option) {
1432
- this.invoke('listenHttpResource', cb, option);
1433
- };
1434
- SpyClient.prototype.listenSlowResource = function (cb, option) {
1435
- this.invoke('listenSlowResource', cb, option);
1436
- };
1437
- SpyClient.prototype.listenTiming = function (cb) {
1438
- this.invoke('listenTiming', cb);
1439
- };
1440
- SpyClient.prototype.listenTTI = function (cb, option) {
1441
- this.invoke('listenTTI', cb, option);
1442
- };
1443
- SpyClient.prototype.invoke = function (name, cb, option) {
1444
- for (var index = 0; index < this.modules.length; index++) {
1445
- var mod = this.modules[index];
1446
- if (typeof mod[name] === 'function') {
1447
- return mod[name].apply(mod, [cb, option]);
1448
- }
1449
- }
1450
- console.error('no method', name);
1451
- };
1452
- SpyClient.prototype.register = function (mod) {
1453
- this.modules.push(mod);
1454
- };
1455
- SpyClient.prototype.load = function () {
1456
- for (var index = 0; index < this.modules.length; index++) {
1457
- var mod = this.modules[index];
1458
- mod.load && mod.load();
1459
- }
1460
- };
1461
- SpyClient.prototype.leave = function () {
1462
- for (var index = 0; index < this.modules.length; index++) {
1463
- var mod = this.modules[index];
1464
- mod.leave && mod.leave();
1465
- }
1466
- };
1467
- SpyClient.prototype.destroy = function () {
1468
- for (var index = 0; index < this.modules.length; index++) {
1469
- var mod = this.modules[index];
1470
- mod.destroy && mod.destroy();
1471
- }
1472
- document.removeEventListener('visibilitychange', this.visibilitychangeCB);
1473
- window.removeEventListener('load', this.load);
1474
- window.removeEventListener('beforeunload', this.leave);
1475
- window.removeEventListener('unload', this.destroy);
1476
- };
1477
- SpyClient.prototype.visibilitychangeCB = function () {
1478
- if (document.visibilityState === 'hidden') {
1479
- this.leave();
1480
- }
1481
- };
1482
- 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;
1483
1494
  }(SpyClient$1));
1484
1495
 
1485
1496
  export { SpyClient as default };