jason-trace-log 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +7 -0
- package/README.md +50 -0
- package/dist/lib/baseTrace.js +405 -0
- package/dist/lib/baseTrace.js.map +1 -0
- package/dist/lib/constants.js +26 -0
- package/dist/lib/constants.js.map +1 -0
- package/dist/lib/core/fetch.js +138 -0
- package/dist/lib/core/fetch.js.map +1 -0
- package/dist/lib/core/fingerprint.js +66 -0
- package/dist/lib/core/fingerprint.js.map +1 -0
- package/dist/lib/core/interface.js +3 -0
- package/dist/lib/core/interface.js.map +1 -0
- package/dist/lib/core/request.js +26 -0
- package/dist/lib/core/request.js.map +1 -0
- package/dist/lib/core/send.js +176 -0
- package/dist/lib/core/send.js.map +1 -0
- package/dist/lib/core/util.js +186 -0
- package/dist/lib/core/util.js.map +1 -0
- package/dist/lib/core/webvitals.js +63 -0
- package/dist/lib/core/webvitals.js.map +1 -0
- package/dist/lib/index.js +19 -0
- package/dist/lib/index.js.map +1 -0
- package/dist/lib/trace.js +27 -0
- package/dist/lib/trace.js.map +1 -0
- package/dist/lib/typings/common.js +131 -0
- package/dist/lib/typings/common.js.map +1 -0
- package/dist/trace-log.esm.js +1391 -0
- package/dist/trace-log.esm.js.map +1 -0
- package/dist/trace-log.umd.js +1400 -0
- package/dist/trace-log.umd.js.map +1 -0
- package/dist/trace-sdk.esm.js +1391 -0
- package/dist/trace-sdk.esm.js.map +1 -0
- package/dist/trace-sdk.umd.js +1401 -0
- package/dist/trace-sdk.umd.js.map +1 -0
- package/dist/types/baseTrace.d.ts +58 -0
- package/dist/types/constants.d.ts +12 -0
- package/dist/types/core/fetch.d.ts +21 -0
- package/dist/types/core/fingerprint.d.ts +14 -0
- package/dist/types/core/interface.d.ts +10 -0
- package/dist/types/core/request.d.ts +3 -0
- package/dist/types/core/send.d.ts +84 -0
- package/dist/types/core/util.d.ts +19 -0
- package/dist/types/core/webvitals.d.ts +8 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/trace.d.ts +3 -0
- package/dist/types/typings/common.d.ts +84 -0
- package/package.json +140 -0
|
@@ -0,0 +1,1391 @@
|
|
|
1
|
+
/*! *****************************************************************************
|
|
2
|
+
Copyright (c) Microsoft Corporation. All rights reserved.
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
4
|
+
this file except in compliance with the License. You may obtain a copy of the
|
|
5
|
+
License at http://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
|
|
7
|
+
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
8
|
+
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
|
9
|
+
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
|
10
|
+
MERCHANTABLITY OR NON-INFRINGEMENT.
|
|
11
|
+
|
|
12
|
+
See the Apache Version 2.0 License for specific language governing permissions
|
|
13
|
+
and limitations under the License.
|
|
14
|
+
***************************************************************************** */
|
|
15
|
+
/* global Reflect, Promise */
|
|
16
|
+
|
|
17
|
+
var extendStatics = function(d, b) {
|
|
18
|
+
extendStatics = Object.setPrototypeOf ||
|
|
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]; };
|
|
21
|
+
return extendStatics(d, b);
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
function __extends(d, b) {
|
|
25
|
+
extendStatics(d, b);
|
|
26
|
+
function __() { this.constructor = d; }
|
|
27
|
+
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
var __assign = function() {
|
|
31
|
+
__assign = Object.assign || function __assign(t) {
|
|
32
|
+
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
33
|
+
s = arguments[i];
|
|
34
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
|
|
35
|
+
}
|
|
36
|
+
return t;
|
|
37
|
+
};
|
|
38
|
+
return __assign.apply(this, arguments);
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
function __awaiter(thisArg, _arguments, P, generator) {
|
|
42
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
43
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
44
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
45
|
+
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
|
|
46
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function __generator(thisArg, body) {
|
|
51
|
+
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
|
52
|
+
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
53
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
54
|
+
function step(op) {
|
|
55
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
56
|
+
while (_) try {
|
|
57
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
58
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
59
|
+
switch (op[0]) {
|
|
60
|
+
case 0: case 1: t = op; break;
|
|
61
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
62
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
63
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
64
|
+
default:
|
|
65
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
66
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
67
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
68
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
69
|
+
if (t[2]) _.ops.pop();
|
|
70
|
+
_.trys.pop(); continue;
|
|
71
|
+
}
|
|
72
|
+
op = body.call(thisArg, _);
|
|
73
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
74
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
var e,n,t,i,a=-1,o=function(e){addEventListener("pageshow",(function(n){n.persisted&&(a=n.timeStamp,e(n));}),!0);},c=function(){return window.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},u=function(){var e=c();return e&&e.activationStart||0},f=function(e,n){var t=c(),i="navigate";a>=0?i="back-forward-cache":t&&(document.prerendering||u()>0?i="prerender":document.wasDiscarded?i="restore":t.type&&(i=t.type.replace(/_/g,"-")));return {name:e,value:void 0===n?-1:n,rating:"good",delta:0,entries:[],id:"v3-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:i}},s=function(e,n,t){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var i=new PerformanceObserver((function(e){Promise.resolve().then((function(){n(e.getEntries());}));}));return i.observe(Object.assign({type:e,buffered:!0},t||{})),i}}catch(e){}},d=function(e,n,t,i){var r,a;return function(o){n.value>=0&&(o||i)&&((a=n.value-(r||0))||void 0===r)&&(r=n.value,n.delta=a,n.rating=function(e,n){return e>n[1]?"poor":e>n[0]?"needs-improvement":"good"}(n.value,t),e(n));}},l=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}));},p=function(e){var n=function(n){"pagehide"!==n.type&&"hidden"!==document.visibilityState||e(n);};addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0);},v=function(e){var n=!1;return function(t){n||(e(t),n=!0);}},m=-1,h=function(){return "hidden"!==document.visibilityState||document.prerendering?1/0:0},g=function(e){"hidden"===document.visibilityState&&m>-1&&(m="visibilitychange"===e.type?e.timeStamp:0,T());},y=function(){addEventListener("visibilitychange",g,!0),addEventListener("prerenderingchange",g,!0);},T=function(){removeEventListener("visibilitychange",g,!0),removeEventListener("prerenderingchange",g,!0);},E=function(){return m<0&&(m=h(),y(),o((function(){setTimeout((function(){m=h(),y();}),0);}))),{get firstHiddenTime(){return m}}},C=function(e){document.prerendering?addEventListener("prerenderingchange",(function(){return e()}),!0):e();},L=[1800,3e3],w=function(e,n){n=n||{},C((function(){var t,i=E(),r=f("FCP"),a=s("paint",(function(e){e.forEach((function(e){"first-contentful-paint"===e.name&&(a.disconnect(),e.startTime<i.firstHiddenTime&&(r.value=Math.max(e.startTime-u(),0),r.entries.push(e),t(!0)));}));}));a&&(t=d(e,r,L,n.reportAllChanges),o((function(i){r=f("FCP"),t=d(e,r,L,n.reportAllChanges),l((function(){r.value=performance.now()-i.timeStamp,t(!0);}));})));}));},b=[.1,.25],S=function(e,n){n=n||{},w(v((function(){var t,i=f("CLS",0),r=0,a=[],c=function(e){e.forEach((function(e){if(!e.hadRecentInput){var n=a[0],t=a[a.length-1];r&&e.startTime-t.startTime<1e3&&e.startTime-n.startTime<5e3?(r+=e.value,a.push(e)):(r=e.value,a=[e]);}})),r>i.value&&(i.value=r,i.entries=a,t());},u=s("layout-shift",c);u&&(t=d(e,i,b,n.reportAllChanges),p((function(){c(u.takeRecords()),t(!0);})),o((function(){r=0,i=f("CLS",0),t=d(e,i,b,n.reportAllChanges),l((function(){return t()}));})),setTimeout(t,0));})));},A={passive:!0,capture:!0},I=new Date,P=function(i,r){e||(e=r,n=i,t=new Date,k(removeEventListener),F());},F=function(){if(n>=0&&n<t-I){var r={entryType:"first-input",name:e.type,target:e.target,cancelable:e.cancelable,startTime:e.timeStamp,processingStart:e.timeStamp+n};i.forEach((function(e){e(r);})),i=[];}},M=function(e){if(e.cancelable){var n=(e.timeStamp>1e12?new Date:performance.now())-e.timeStamp;"pointerdown"==e.type?function(e,n){var t=function(){P(e,n),r();},i=function(){r();},r=function(){removeEventListener("pointerup",t,A),removeEventListener("pointercancel",i,A);};addEventListener("pointerup",t,A),addEventListener("pointercancel",i,A);}(n,e):P(n,e);}},k=function(e){["mousedown","keydown","touchstart","pointerdown"].forEach((function(n){return e(n,M,A)}));},D=[100,300],x=function(t,r){r=r||{},C((function(){var a,c=E(),u=f("FID"),l=function(e){e.startTime<c.firstHiddenTime&&(u.value=e.processingStart-e.startTime,u.entries.push(e),a(!0));},m=function(e){e.forEach(l);},h=s("first-input",m);a=d(t,u,D,r.reportAllChanges),h&&p(v((function(){m(h.takeRecords()),h.disconnect();}))),h&&o((function(){var o;u=f("FID"),a=d(t,u,D,r.reportAllChanges),i=[],n=-1,e=null,k(addEventListener),o=l,i.push(o),F();}));}));},U=[2500,4e3],V={},W=function(e,n){n=n||{},C((function(){var t,i=E(),r=f("LCP"),a=function(e){var n=e[e.length-1];n&&n.startTime<i.firstHiddenTime&&(r.value=Math.max(n.startTime-u(),0),r.entries=[n],t());},c=s("largest-contentful-paint",a);if(c){t=d(e,r,U,n.reportAllChanges);var m=v((function(){V[r.id]||(a(c.takeRecords()),c.disconnect(),V[r.id]=!0,t(!0));}));["keydown","click"].forEach((function(e){addEventListener(e,(function(){return setTimeout(m,0)}),!0);})),p(m),o((function(i){r=f("LCP"),t=d(e,r,U,n.reportAllChanges),l((function(){r.value=performance.now()-i.timeStamp,V[r.id]=!0,t(!0);}));}));}}));};
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* @typedef {Object<string,any>} Result
|
|
82
|
+
* @typedef {import('web-vitals').Metric | Object<string,any>} Metric
|
|
83
|
+
* @typedef {{ effectiveType: 'slow-2g' | '2g' | '3g' | '4g', rtt: number, downlink: number }} NetworkInformation
|
|
84
|
+
*
|
|
85
|
+
* @typedef {object} CreateApiReporterOptions
|
|
86
|
+
* @prop {object} [initial]
|
|
87
|
+
* @prop {(metric: Metric, result: Result) => Result} [mapMetric]
|
|
88
|
+
* @prop {(result: Result) => Result | void} [beforeSend]
|
|
89
|
+
* @prop {(url: string, result: Result) => any} [onSend]
|
|
90
|
+
*/
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Create Web Vitals API reporter, that accepts `Metric` values and sends it to `url`
|
|
94
|
+
* using `navigator.sendBeacon` when available or fallbacks back to XMLHttpRequest.
|
|
95
|
+
*
|
|
96
|
+
* The function sends request only once.
|
|
97
|
+
* Use `onSend` to implement a custom logic.
|
|
98
|
+
*
|
|
99
|
+
* @param {string} url
|
|
100
|
+
* @param {CreateApiReporterOptions} [opts]
|
|
101
|
+
* @return {(metric: Metric) => void}
|
|
102
|
+
*/
|
|
103
|
+
|
|
104
|
+
function createApiReporter(url, opts = {}) {
|
|
105
|
+
let isSent = false;
|
|
106
|
+
let isCalled = false;
|
|
107
|
+
let result = /** @type {Result} */ ({ id: generateUniqueId(), ...opts.initial });
|
|
108
|
+
|
|
109
|
+
const sendValues = () => {
|
|
110
|
+
if (isSent) return // data is already sent
|
|
111
|
+
if (!isCalled) return // no data collected
|
|
112
|
+
|
|
113
|
+
result.duration = now();
|
|
114
|
+
if (opts.beforeSend) {
|
|
115
|
+
const newResult = opts.beforeSend(result);
|
|
116
|
+
if (newResult) result = { ...result, ...newResult };
|
|
117
|
+
}
|
|
118
|
+
isSent = true;
|
|
119
|
+
if (opts.onSend) {
|
|
120
|
+
opts.onSend(url, result);
|
|
121
|
+
} else {
|
|
122
|
+
if (typeof navigator === 'undefined') return
|
|
123
|
+
if (navigator.sendBeacon) return navigator.sendBeacon(url, JSON.stringify(result))
|
|
124
|
+
const client = new XMLHttpRequest();
|
|
125
|
+
client.open('POST', url, false); // third parameter indicates sync xhr
|
|
126
|
+
client.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
|
|
127
|
+
client.send(JSON.stringify(result));
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const mapMetric =
|
|
132
|
+
opts.mapMetric ||
|
|
133
|
+
function (metric) {
|
|
134
|
+
const isWebVital = ['FCP', 'TTFB', 'LCP', 'CLS', 'FID'].indexOf(metric.name) !== -1;
|
|
135
|
+
return { [metric.name]: isWebVital ? round(metric.value, metric.name === 'CLS' ? 4 : 0) : metric.value }
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/** @param {Metric} metric */
|
|
139
|
+
const report = (metric) => {
|
|
140
|
+
if (!isCalled) isCalled = true;
|
|
141
|
+
result = { ...result, ...mapMetric(metric, result) };
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
// should be the last call to capture latest CLS
|
|
145
|
+
setTimeout(() => {
|
|
146
|
+
// Safari does not fire "visibilitychange" on the tab close
|
|
147
|
+
// So we have 2 options: loose Safari data, or loose LCP/CLS that depends on "visibilitychange" logic.
|
|
148
|
+
// Current solution: if LCP/CLS supported, use `onHidden` otherwise, use `pagehide` to fire the callback in the end.
|
|
149
|
+
//
|
|
150
|
+
// More details: https://github.com/treosh/web-vitals-reporter/issues/3
|
|
151
|
+
const supportedEntryTypes = (PerformanceObserver && PerformanceObserver.supportedEntryTypes) || [];
|
|
152
|
+
const isLatestVisibilityChangeSupported = supportedEntryTypes.indexOf('layout-shift') !== -1;
|
|
153
|
+
|
|
154
|
+
if (isLatestVisibilityChangeSupported) {
|
|
155
|
+
const onVisibilityChange = () => {
|
|
156
|
+
if (document.visibilityState === 'hidden') {
|
|
157
|
+
sendValues();
|
|
158
|
+
removeEventListener('visibilitychange', onVisibilityChange, true);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
addEventListener('visibilitychange', onVisibilityChange, true);
|
|
162
|
+
} else {
|
|
163
|
+
addEventListener('pagehide', sendValues, { capture: true, once: true });
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
return report
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Get device information.
|
|
172
|
+
* - Effective connection type: https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation
|
|
173
|
+
* - Device memory: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/deviceMemory
|
|
174
|
+
*/
|
|
175
|
+
|
|
176
|
+
function getDeviceInfo() {
|
|
177
|
+
const nav = /** @type {null | (Navigator & { deviceMemory: number, connection: NetworkInformation })} */ (typeof navigator ===
|
|
178
|
+
'undefined'
|
|
179
|
+
? null
|
|
180
|
+
: navigator);
|
|
181
|
+
const conn = nav && nav.connection ? nav.connection : null;
|
|
182
|
+
return {
|
|
183
|
+
url: location ? location.href : null,
|
|
184
|
+
referrer: document ? document.referrer : null,
|
|
185
|
+
userAgent: nav ? nav.userAgent : null,
|
|
186
|
+
memory: nav ? nav.deviceMemory : undefined,
|
|
187
|
+
cpus: nav ? nav.hardwareConcurrency : undefined,
|
|
188
|
+
connection: conn ? { effectiveType: conn.effectiveType, rtt: conn.rtt, downlink: conn.downlink } : undefined,
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Get time since a session started.
|
|
194
|
+
*/
|
|
195
|
+
|
|
196
|
+
function now() {
|
|
197
|
+
const perf = typeof performance === 'undefined' ? null : performance;
|
|
198
|
+
return perf && perf.now ? round(perf.now()) : null
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Round, source: https://stackoverflow.com/a/18358056
|
|
203
|
+
*
|
|
204
|
+
* @param {number} val
|
|
205
|
+
* @param {number} [precision]
|
|
206
|
+
* @return {number}
|
|
207
|
+
*/
|
|
208
|
+
|
|
209
|
+
function round(val, precision = 0) {
|
|
210
|
+
// @ts-ignore
|
|
211
|
+
return +(Math.round(`${val}e+${precision}`) + `e-${precision}`)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Generate a unique id, copied from:
|
|
216
|
+
* https://github.com/GoogleChrome/web-vitals/blob/master/src/lib/generateUniqueID.ts
|
|
217
|
+
*/
|
|
218
|
+
|
|
219
|
+
function generateUniqueId() {
|
|
220
|
+
return `v1-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
var SCORE_RANGE_LCP = [2500, 4500];
|
|
224
|
+
var SCORE_RANGE_FID = [100, 300];
|
|
225
|
+
var SCORE_RANGE_CLS = [0.1, 0.25];
|
|
226
|
+
var score = function (value, range) {
|
|
227
|
+
return value < range[0] ? 'good' : value < range[1] ? 'needs improvement' : 'poor';
|
|
228
|
+
};
|
|
229
|
+
function generateUniqueId$1() {
|
|
230
|
+
return "v1-".concat(Date.now(), "-").concat(Math.floor(Math.random() * (9e12 - 1)) + 1e12);
|
|
231
|
+
}
|
|
232
|
+
function round$1(val, precision) {
|
|
233
|
+
if (precision === void 0) { precision = 0; }
|
|
234
|
+
// @ts-ignore
|
|
235
|
+
return +(Math.round("".concat(val, "e+").concat(precision)) + "e-".concat(precision));
|
|
236
|
+
}
|
|
237
|
+
function mapMetric(metric) {
|
|
238
|
+
var _a;
|
|
239
|
+
var isWebVital = ['FCP', 'TTFB', 'LCP', 'CLS', 'FID'].indexOf(metric.name) !== -1;
|
|
240
|
+
return _a = {},
|
|
241
|
+
_a[metric.name] = isWebVital ? round$1(metric.value, metric.name === 'CLS' ? 4 : 0) : metric.value,
|
|
242
|
+
_a["".concat(metric.name, "Rating")] = metric.rating,
|
|
243
|
+
_a;
|
|
244
|
+
}
|
|
245
|
+
var sendToAnalytics = createApiReporter('/analytics', {
|
|
246
|
+
initial: getDeviceInfo(),
|
|
247
|
+
beforeSend: function (result) {
|
|
248
|
+
console.log('beforeSend');
|
|
249
|
+
var LCP = result.LCP, FID = result.FID, CLS = result.CLS;
|
|
250
|
+
console.info('web-vitals: ', result);
|
|
251
|
+
if (!LCP || !FID || !CLS)
|
|
252
|
+
return; // Core Web Vitals are not supported
|
|
253
|
+
// return extra attributes to merge into the final result
|
|
254
|
+
return {
|
|
255
|
+
LCPScore: score(LCP, SCORE_RANGE_LCP),
|
|
256
|
+
// FIDScore: FID < 100 ? 'good' : FID < 300 ? 'needs improvement' : 'poor',
|
|
257
|
+
FIDScore: score(FID, SCORE_RANGE_FID),
|
|
258
|
+
// CLSScore: CLS < 0.1 ? 'good' : CLS < 0.25 ? 'needs improvement' : 'poor'
|
|
259
|
+
CLSScore: score(CLS, SCORE_RANGE_CLS),
|
|
260
|
+
};
|
|
261
|
+
},
|
|
262
|
+
});
|
|
263
|
+
var onVitals = function (saveMetric) {
|
|
264
|
+
console.log('webvitals setup');
|
|
265
|
+
W(saveMetric);
|
|
266
|
+
x(saveMetric);
|
|
267
|
+
S(saveMetric);
|
|
268
|
+
// onTTFB(saveMetric)
|
|
269
|
+
// onINP(saveMetric)
|
|
270
|
+
// onFCP(saveMetric)
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* base64.ts
|
|
275
|
+
*
|
|
276
|
+
* Licensed under the BSD 3-Clause License.
|
|
277
|
+
* http://opensource.org/licenses/BSD-3-Clause
|
|
278
|
+
*
|
|
279
|
+
* References:
|
|
280
|
+
* http://en.wikipedia.org/wiki/Base64
|
|
281
|
+
*
|
|
282
|
+
* @author Dan Kogai (https://github.com/dankogai)
|
|
283
|
+
*/
|
|
284
|
+
const _hasBuffer = typeof Buffer === 'function';
|
|
285
|
+
const _TD = typeof TextDecoder === 'function' ? new TextDecoder() : undefined;
|
|
286
|
+
const _TE = typeof TextEncoder === 'function' ? new TextEncoder() : undefined;
|
|
287
|
+
const b64ch = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
|
|
288
|
+
const b64chs = Array.prototype.slice.call(b64ch);
|
|
289
|
+
const b64tab = ((a) => {
|
|
290
|
+
let tab = {};
|
|
291
|
+
a.forEach((c, i) => tab[c] = i);
|
|
292
|
+
return tab;
|
|
293
|
+
})(b64chs);
|
|
294
|
+
const _fromCC = String.fromCharCode.bind(String);
|
|
295
|
+
const _U8Afrom = typeof Uint8Array.from === 'function'
|
|
296
|
+
? Uint8Array.from.bind(Uint8Array)
|
|
297
|
+
: (it) => new Uint8Array(Array.prototype.slice.call(it, 0));
|
|
298
|
+
const _mkUriSafe = (src) => src
|
|
299
|
+
.replace(/=/g, '').replace(/[+\/]/g, (m0) => m0 == '+' ? '-' : '_');
|
|
300
|
+
/**
|
|
301
|
+
* polyfill version of `btoa`
|
|
302
|
+
*/
|
|
303
|
+
const btoaPolyfill = (bin) => {
|
|
304
|
+
// console.log('polyfilled');
|
|
305
|
+
let u32, c0, c1, c2, asc = '';
|
|
306
|
+
const pad = bin.length % 3;
|
|
307
|
+
for (let i = 0; i < bin.length;) {
|
|
308
|
+
if ((c0 = bin.charCodeAt(i++)) > 255 ||
|
|
309
|
+
(c1 = bin.charCodeAt(i++)) > 255 ||
|
|
310
|
+
(c2 = bin.charCodeAt(i++)) > 255)
|
|
311
|
+
throw new TypeError('invalid character found');
|
|
312
|
+
u32 = (c0 << 16) | (c1 << 8) | c2;
|
|
313
|
+
asc += b64chs[u32 >> 18 & 63]
|
|
314
|
+
+ b64chs[u32 >> 12 & 63]
|
|
315
|
+
+ b64chs[u32 >> 6 & 63]
|
|
316
|
+
+ b64chs[u32 & 63];
|
|
317
|
+
}
|
|
318
|
+
return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
|
|
319
|
+
};
|
|
320
|
+
/**
|
|
321
|
+
* does what `window.btoa` of web browsers do.
|
|
322
|
+
* @param {String} bin binary string
|
|
323
|
+
* @returns {string} Base64-encoded string
|
|
324
|
+
*/
|
|
325
|
+
const _btoa = typeof btoa === 'function' ? (bin) => btoa(bin)
|
|
326
|
+
: _hasBuffer ? (bin) => Buffer.from(bin, 'binary').toString('base64')
|
|
327
|
+
: btoaPolyfill;
|
|
328
|
+
const _fromUint8Array = _hasBuffer
|
|
329
|
+
? (u8a) => Buffer.from(u8a).toString('base64')
|
|
330
|
+
: (u8a) => {
|
|
331
|
+
// cf. https://stackoverflow.com/questions/12710001/how-to-convert-uint8-array-to-base64-encoded-string/12713326#12713326
|
|
332
|
+
const maxargs = 0x1000;
|
|
333
|
+
let strs = [];
|
|
334
|
+
for (let i = 0, l = u8a.length; i < l; i += maxargs) {
|
|
335
|
+
strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
|
|
336
|
+
}
|
|
337
|
+
return _btoa(strs.join(''));
|
|
338
|
+
};
|
|
339
|
+
// This trick is found broken https://github.com/dankogai/js-base64/issues/130
|
|
340
|
+
// const utob = (src: string) => unescape(encodeURIComponent(src));
|
|
341
|
+
// reverting good old fationed regexp
|
|
342
|
+
const cb_utob = (c) => {
|
|
343
|
+
if (c.length < 2) {
|
|
344
|
+
var cc = c.charCodeAt(0);
|
|
345
|
+
return cc < 0x80 ? c
|
|
346
|
+
: cc < 0x800 ? (_fromCC(0xc0 | (cc >>> 6))
|
|
347
|
+
+ _fromCC(0x80 | (cc & 0x3f)))
|
|
348
|
+
: (_fromCC(0xe0 | ((cc >>> 12) & 0x0f))
|
|
349
|
+
+ _fromCC(0x80 | ((cc >>> 6) & 0x3f))
|
|
350
|
+
+ _fromCC(0x80 | (cc & 0x3f)));
|
|
351
|
+
}
|
|
352
|
+
else {
|
|
353
|
+
var cc = 0x10000
|
|
354
|
+
+ (c.charCodeAt(0) - 0xD800) * 0x400
|
|
355
|
+
+ (c.charCodeAt(1) - 0xDC00);
|
|
356
|
+
return (_fromCC(0xf0 | ((cc >>> 18) & 0x07))
|
|
357
|
+
+ _fromCC(0x80 | ((cc >>> 12) & 0x3f))
|
|
358
|
+
+ _fromCC(0x80 | ((cc >>> 6) & 0x3f))
|
|
359
|
+
+ _fromCC(0x80 | (cc & 0x3f)));
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
const re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
|
|
363
|
+
/**
|
|
364
|
+
* @deprecated should have been internal use only.
|
|
365
|
+
* @param {string} src UTF-8 string
|
|
366
|
+
* @returns {string} UTF-16 string
|
|
367
|
+
*/
|
|
368
|
+
const utob = (u) => u.replace(re_utob, cb_utob);
|
|
369
|
+
//
|
|
370
|
+
const _encode = _hasBuffer
|
|
371
|
+
? (s) => Buffer.from(s, 'utf8').toString('base64')
|
|
372
|
+
: _TE
|
|
373
|
+
? (s) => _fromUint8Array(_TE.encode(s))
|
|
374
|
+
: (s) => _btoa(utob(s));
|
|
375
|
+
/**
|
|
376
|
+
* converts a UTF-8-encoded string to a Base64 string.
|
|
377
|
+
* @param {boolean} [urlsafe] if `true` make the result URL-safe
|
|
378
|
+
* @returns {string} Base64 string
|
|
379
|
+
*/
|
|
380
|
+
const encode = (src, urlsafe = false) => urlsafe
|
|
381
|
+
? _mkUriSafe(_encode(src))
|
|
382
|
+
: _encode(src);
|
|
383
|
+
|
|
384
|
+
var TraceDataSeverity;
|
|
385
|
+
(function (TraceDataSeverity) {
|
|
386
|
+
// 其他
|
|
387
|
+
TraceDataSeverity["Else"] = "else";
|
|
388
|
+
// 错误级别
|
|
389
|
+
TraceDataSeverity["Error"] = "error";
|
|
390
|
+
// 告警级别
|
|
391
|
+
TraceDataSeverity["Warning"] = "warning";
|
|
392
|
+
// 日志级别
|
|
393
|
+
TraceDataSeverity["Info"] = "info";
|
|
394
|
+
// 调试级别
|
|
395
|
+
TraceDataSeverity["Debug"] = "debug";
|
|
396
|
+
/** 上报的错误等级 */
|
|
397
|
+
// 低危级别
|
|
398
|
+
TraceDataSeverity["Low"] = "low";
|
|
399
|
+
// 普通级别
|
|
400
|
+
TraceDataSeverity["Normal"] = "normal";
|
|
401
|
+
// 高危级别
|
|
402
|
+
TraceDataSeverity["High"] = "high";
|
|
403
|
+
// 极其严重
|
|
404
|
+
TraceDataSeverity["Critical"] = "critical";
|
|
405
|
+
})(TraceDataSeverity || (TraceDataSeverity = {}));
|
|
406
|
+
var TraceTypes;
|
|
407
|
+
(function (TraceTypes) {
|
|
408
|
+
// PVUV
|
|
409
|
+
TraceTypes["PAGE_VIEW"] = "PageView";
|
|
410
|
+
// Event
|
|
411
|
+
TraceTypes["EVENT"] = "EVENT";
|
|
412
|
+
// 性能
|
|
413
|
+
TraceTypes["PERF"] = "Perf";
|
|
414
|
+
// 资源
|
|
415
|
+
TraceTypes["RESOURCE"] = "Resource";
|
|
416
|
+
// 动作、行为类型
|
|
417
|
+
TraceTypes["ACTION"] = "Action";
|
|
418
|
+
// 请求类型
|
|
419
|
+
TraceTypes["FETCH"] = "Fetch";
|
|
420
|
+
// 代码错误
|
|
421
|
+
TraceTypes["CODE_ERROR"] = "CodeError";
|
|
422
|
+
// 日志
|
|
423
|
+
TraceTypes["CONSOLE"] = "Console";
|
|
424
|
+
// 其它
|
|
425
|
+
TraceTypes["CUSTOMER"] = "Customer";
|
|
426
|
+
})(TraceTypes || (TraceTypes = {}));
|
|
427
|
+
var TraceClientTypes;
|
|
428
|
+
(function (TraceClientTypes) {
|
|
429
|
+
// 安卓
|
|
430
|
+
TraceClientTypes["ANDROID_H5"] = "android";
|
|
431
|
+
// iOS
|
|
432
|
+
TraceClientTypes["IOS_H5"] = "ios";
|
|
433
|
+
// PC端
|
|
434
|
+
TraceClientTypes["PC_H5"] = "pc";
|
|
435
|
+
// 浏览器
|
|
436
|
+
TraceClientTypes["BROWSER_H5"] = "browser";
|
|
437
|
+
})(TraceClientTypes || (TraceClientTypes = {}));
|
|
438
|
+
var BrowserType;
|
|
439
|
+
(function (BrowserType) {
|
|
440
|
+
// 手机端浏览器
|
|
441
|
+
BrowserType["MOBILE"] = "mobile";
|
|
442
|
+
// PC浏览器
|
|
443
|
+
BrowserType["PC"] = "pc";
|
|
444
|
+
// webview
|
|
445
|
+
BrowserType["WEBVIEW"] = "webview";
|
|
446
|
+
// 小程序
|
|
447
|
+
BrowserType["MINI_PROGRAM"] = "miniProgram";
|
|
448
|
+
})(BrowserType || (BrowserType = {}));
|
|
449
|
+
var TraceLevelType;
|
|
450
|
+
(function (TraceLevelType) {
|
|
451
|
+
// 告警级别
|
|
452
|
+
TraceLevelType["Error"] = "error";
|
|
453
|
+
// 预警级别
|
|
454
|
+
TraceLevelType["Warn"] = "warn";
|
|
455
|
+
// 普通日志
|
|
456
|
+
TraceLevelType["Info"] = "info";
|
|
457
|
+
// 调试日志
|
|
458
|
+
TraceLevelType["Debug"] = "debug";
|
|
459
|
+
})(TraceLevelType || (TraceLevelType = {}));
|
|
460
|
+
var BreadcrumbTypes;
|
|
461
|
+
(function (BreadcrumbTypes) {
|
|
462
|
+
BreadcrumbTypes["ROUTE"] = "Route";
|
|
463
|
+
BreadcrumbTypes["CLICK"] = "UI.Click";
|
|
464
|
+
BreadcrumbTypes["CONSOLE"] = "Console";
|
|
465
|
+
BreadcrumbTypes["FETCH"] = "Fetch";
|
|
466
|
+
BreadcrumbTypes["UNHANDLEDREJECTION"] = "Unhandledrejection";
|
|
467
|
+
BreadcrumbTypes["RESOURCE"] = "Resource";
|
|
468
|
+
BreadcrumbTypes["CODE_ERROR"] = "Code Error";
|
|
469
|
+
BreadcrumbTypes["CUSTOMER"] = "Customer";
|
|
470
|
+
})(BreadcrumbTypes || (BreadcrumbTypes = {}));
|
|
471
|
+
var TraceDataTypes;
|
|
472
|
+
(function (TraceDataTypes) {
|
|
473
|
+
TraceDataTypes["UNKNOWN"] = "UNKNOWN";
|
|
474
|
+
TraceDataTypes["UNKNOWN_FUNCTION"] = "UNKNOWN_FUNCTION";
|
|
475
|
+
TraceDataTypes["JAVASCRIPT"] = "JAVASCRIPT";
|
|
476
|
+
TraceDataTypes["LOG"] = "LOG";
|
|
477
|
+
TraceDataTypes["HTTP"] = "HTTP";
|
|
478
|
+
TraceDataTypes["VUE"] = "VUE";
|
|
479
|
+
TraceDataTypes["REACT"] = "REACT";
|
|
480
|
+
TraceDataTypes["RESOURCE"] = "RESOURCE";
|
|
481
|
+
TraceDataTypes["PROMISE"] = "PROMISE";
|
|
482
|
+
TraceDataTypes["ROUTE"] = "ROUTE";
|
|
483
|
+
TraceDataTypes["PERF"] = "PERF";
|
|
484
|
+
})(TraceDataTypes || (TraceDataTypes = {}));
|
|
485
|
+
var BreadcrumbsCategorys;
|
|
486
|
+
(function (BreadcrumbsCategorys) {
|
|
487
|
+
BreadcrumbsCategorys["Http"] = "http";
|
|
488
|
+
BreadcrumbsCategorys["User"] = "user";
|
|
489
|
+
BreadcrumbsCategorys["Debug"] = "debug";
|
|
490
|
+
BreadcrumbsCategorys["Exception"] = "exception";
|
|
491
|
+
BreadcrumbsCategorys["Lifecycle"] = "lifecycle";
|
|
492
|
+
})(BreadcrumbsCategorys || (BreadcrumbsCategorys = {}));
|
|
493
|
+
var TraceBaseDataName;
|
|
494
|
+
(function (TraceBaseDataName) {
|
|
495
|
+
TraceBaseDataName["Fetch"] = "Fetch";
|
|
496
|
+
TraceBaseDataName["TypeError"] = "TypeError";
|
|
497
|
+
TraceBaseDataName["Unhandledrejection"] = "Unhandledrejection";
|
|
498
|
+
TraceBaseDataName["Log"] = "Log";
|
|
499
|
+
TraceBaseDataName["Perf"] = "Perf";
|
|
500
|
+
TraceBaseDataName["Resource"] = "Resource";
|
|
501
|
+
})(TraceBaseDataName || (TraceBaseDataName = {}));
|
|
502
|
+
var SendMethod;
|
|
503
|
+
(function (SendMethod) {
|
|
504
|
+
// 图片
|
|
505
|
+
SendMethod["IMG"] = "img";
|
|
506
|
+
// beacon
|
|
507
|
+
SendMethod["BEACON"] = "beacon";
|
|
508
|
+
// 华为云日志 lts
|
|
509
|
+
SendMethod["LTS"] = "lts";
|
|
510
|
+
})(SendMethod || (SendMethod = {}));
|
|
511
|
+
|
|
512
|
+
// 获取时间
|
|
513
|
+
var getTimestamp = function () { return Date.now(); };
|
|
514
|
+
var isResourceTarget = function (target) {
|
|
515
|
+
return target instanceof HTMLScriptElement ||
|
|
516
|
+
target instanceof HTMLLinkElement ||
|
|
517
|
+
target instanceof HTMLImageElement ||
|
|
518
|
+
target instanceof HTMLVideoElement ||
|
|
519
|
+
target instanceof HTMLAudioElement;
|
|
520
|
+
};
|
|
521
|
+
/**
|
|
522
|
+
* 根据字符串生成hashcode
|
|
523
|
+
*
|
|
524
|
+
* @export
|
|
525
|
+
* @param {string} str
|
|
526
|
+
* @return {*} {number} 可为正数和负数
|
|
527
|
+
*/
|
|
528
|
+
function hashCode(str) {
|
|
529
|
+
var hash = 0;
|
|
530
|
+
if (str.length == 0)
|
|
531
|
+
return hash;
|
|
532
|
+
for (var i = 0; i < str.length; i++) {
|
|
533
|
+
var char = str.charCodeAt(i);
|
|
534
|
+
hash = (hash << 5) - hash + char;
|
|
535
|
+
hash = hash & hash;
|
|
536
|
+
}
|
|
537
|
+
return hash;
|
|
538
|
+
}
|
|
539
|
+
function dataTypes2BreadcrumbsType(data) {
|
|
540
|
+
switch (data) {
|
|
541
|
+
case TraceDataTypes.JAVASCRIPT:
|
|
542
|
+
case TraceDataTypes.UNKNOWN:
|
|
543
|
+
case TraceDataTypes.UNKNOWN_FUNCTION:
|
|
544
|
+
case TraceDataTypes.REACT:
|
|
545
|
+
case TraceDataTypes.VUE:
|
|
546
|
+
return BreadcrumbTypes.CODE_ERROR;
|
|
547
|
+
case TraceDataTypes.PROMISE:
|
|
548
|
+
return BreadcrumbTypes.UNHANDLEDREJECTION;
|
|
549
|
+
case TraceDataTypes.HTTP:
|
|
550
|
+
return BreadcrumbTypes.FETCH;
|
|
551
|
+
case TraceDataTypes.PERF:
|
|
552
|
+
case TraceDataTypes.LOG:
|
|
553
|
+
return BreadcrumbTypes.CONSOLE;
|
|
554
|
+
case TraceDataTypes.RESOURCE:
|
|
555
|
+
return BreadcrumbTypes.RESOURCE;
|
|
556
|
+
case TraceDataTypes.ROUTE:
|
|
557
|
+
return BreadcrumbTypes.ROUTE;
|
|
558
|
+
default:
|
|
559
|
+
return BreadcrumbTypes.CUSTOMER;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
function dataCategory2BreadcrumbsCategory(data) {
|
|
563
|
+
switch (data) {
|
|
564
|
+
case TraceDataTypes.JAVASCRIPT:
|
|
565
|
+
case TraceDataTypes.UNKNOWN:
|
|
566
|
+
case TraceDataTypes.UNKNOWN_FUNCTION:
|
|
567
|
+
return BreadcrumbsCategorys.Exception;
|
|
568
|
+
case TraceDataTypes.REACT:
|
|
569
|
+
case TraceDataTypes.VUE:
|
|
570
|
+
return BreadcrumbsCategorys.Lifecycle;
|
|
571
|
+
case TraceDataTypes.PROMISE:
|
|
572
|
+
return BreadcrumbsCategorys.Exception;
|
|
573
|
+
case TraceDataTypes.HTTP:
|
|
574
|
+
return BreadcrumbsCategorys.Http;
|
|
575
|
+
case TraceDataTypes.PERF:
|
|
576
|
+
case TraceDataTypes.LOG:
|
|
577
|
+
return BreadcrumbsCategorys.Debug;
|
|
578
|
+
case TraceDataTypes.RESOURCE:
|
|
579
|
+
return BreadcrumbsCategorys.Http;
|
|
580
|
+
case TraceDataTypes.ROUTE:
|
|
581
|
+
return BreadcrumbsCategorys.Lifecycle;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
function getTraceDataLevel(level) {
|
|
585
|
+
switch (level) {
|
|
586
|
+
case TraceDataSeverity.High:
|
|
587
|
+
case TraceDataSeverity.Critical:
|
|
588
|
+
case TraceDataSeverity.Error:
|
|
589
|
+
return TraceLevelType.Error;
|
|
590
|
+
case TraceDataSeverity.Warning:
|
|
591
|
+
return TraceLevelType.Warn;
|
|
592
|
+
case TraceDataSeverity.Debug:
|
|
593
|
+
case TraceDataSeverity.Low:
|
|
594
|
+
return TraceLevelType.Debug;
|
|
595
|
+
default:
|
|
596
|
+
return TraceLevelType.Info;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
function getTraceDataType(type) {
|
|
600
|
+
switch (type) {
|
|
601
|
+
case TraceDataTypes.PROMISE:
|
|
602
|
+
case TraceDataTypes.UNKNOWN:
|
|
603
|
+
case TraceDataTypes.UNKNOWN_FUNCTION:
|
|
604
|
+
case TraceDataTypes.JAVASCRIPT:
|
|
605
|
+
return TraceTypes.CODE_ERROR;
|
|
606
|
+
case TraceDataTypes.REACT:
|
|
607
|
+
case TraceDataTypes.VUE:
|
|
608
|
+
case TraceDataTypes.ROUTE:
|
|
609
|
+
return TraceTypes.EVENT;
|
|
610
|
+
case TraceDataTypes.PERF:
|
|
611
|
+
return TraceTypes.PERF;
|
|
612
|
+
case TraceDataTypes.HTTP:
|
|
613
|
+
return TraceTypes.FETCH;
|
|
614
|
+
case TraceDataTypes.RESOURCE:
|
|
615
|
+
return TraceTypes.RESOURCE;
|
|
616
|
+
default:
|
|
617
|
+
return TraceTypes.CUSTOMER;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
function getPerfLevel(data) {
|
|
621
|
+
var level = TraceLevelType.Info;
|
|
622
|
+
if (data.LCPRating === 'poor'
|
|
623
|
+
|| data.FIDRating === 'poor'
|
|
624
|
+
|| data.FCPRating === 'poor'
|
|
625
|
+
|| data.TTFBRating === 'poor'
|
|
626
|
+
|| data.CLSRating === 'poor'
|
|
627
|
+
|| data.INPRating === 'poor') {
|
|
628
|
+
// console.log('[getPerfLevel] error')
|
|
629
|
+
level = TraceLevelType.Error;
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
if (data.LCPRating === 'needs improvement'
|
|
633
|
+
|| data.CLSRating === 'needs improvement'
|
|
634
|
+
|| data.FCPRating === 'needs improvement'
|
|
635
|
+
|| data.FIDRating === 'needs improvement'
|
|
636
|
+
|| data.INPRating === 'needs improvement'
|
|
637
|
+
|| data.TTFBRating === 'needs improvement') {
|
|
638
|
+
// console.log('[getPerfLevel] warn')
|
|
639
|
+
level = TraceLevelType.Warn;
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
return level;
|
|
643
|
+
}
|
|
644
|
+
function uuid() {
|
|
645
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
|
646
|
+
/* tslint:disable */
|
|
647
|
+
var r = (Math.random() * 16) | 0;
|
|
648
|
+
/* tslint:disable */
|
|
649
|
+
var v = c === 'x' ? r : (r & 0x3) | 0x8;
|
|
650
|
+
return v.toString(16);
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
function safeStringify(obj) {
|
|
654
|
+
var set = new Set();
|
|
655
|
+
var str = JSON.stringify(obj, function (_key, value) {
|
|
656
|
+
if (set.has(value)) {
|
|
657
|
+
return '';
|
|
658
|
+
}
|
|
659
|
+
typeof value === 'object' && set.add(value);
|
|
660
|
+
return value;
|
|
661
|
+
});
|
|
662
|
+
set.clear();
|
|
663
|
+
return str;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
var originFetch = window.fetch;
|
|
667
|
+
// 拦截fetch
|
|
668
|
+
var interceptFetch = function (_a) {
|
|
669
|
+
var pagePath = _a.pagePath, onError = _a.onError, onBefore = _a.onBefore, onAfter = _a.onAfter;
|
|
670
|
+
return function () {
|
|
671
|
+
var args = [];
|
|
672
|
+
for (var _i = 0; _i < arguments.length; _i++) {
|
|
673
|
+
args[_i] = arguments[_i];
|
|
674
|
+
}
|
|
675
|
+
return __awaiter(void 0, void 0, void 0, function () {
|
|
676
|
+
var url, options, startTime, traceId, traceSegmentId, appId, appVersion, traceIdStr, segmentId, service, instance, endpoint, peer, index, values, res, err_1;
|
|
677
|
+
return __generator(this, function (_a) {
|
|
678
|
+
switch (_a.label) {
|
|
679
|
+
case 0:
|
|
680
|
+
url = args[0], options = args[1];
|
|
681
|
+
startTime = getTimestamp();
|
|
682
|
+
traceId = uuid();
|
|
683
|
+
traceSegmentId = uuid();
|
|
684
|
+
appId = uuid();
|
|
685
|
+
appVersion = 'v1.0.0';
|
|
686
|
+
if (Object.prototype.toString.call(args[0]) === '[object Request]') {
|
|
687
|
+
url = new URL(url.url);
|
|
688
|
+
}
|
|
689
|
+
else {
|
|
690
|
+
if (args[0].startsWith('http://') || args[0].startsWith('https://')) {
|
|
691
|
+
url = new URL(args[0]);
|
|
692
|
+
}
|
|
693
|
+
else if (args[0].startsWith('//')) {
|
|
694
|
+
url = new URL("".concat(window.location.protocol).concat(args[0]));
|
|
695
|
+
}
|
|
696
|
+
else {
|
|
697
|
+
url = new URL(window.location.href);
|
|
698
|
+
url.pathname = args[0];
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
traceIdStr = String(encode(traceId));
|
|
702
|
+
segmentId = String(encode(traceSegmentId));
|
|
703
|
+
service = String(encode(appId));
|
|
704
|
+
instance = String(encode(appVersion));
|
|
705
|
+
endpoint = String(encode(pagePath));
|
|
706
|
+
peer = String(encode(url.host));
|
|
707
|
+
index = 1;
|
|
708
|
+
values = "".concat(1, "-").concat(traceIdStr, "-").concat(segmentId, "-").concat(index, "-").concat(service, "-").concat(instance, "-").concat(endpoint, "-").concat(peer);
|
|
709
|
+
if (!options) {
|
|
710
|
+
options = {};
|
|
711
|
+
}
|
|
712
|
+
if (!options.headers) {
|
|
713
|
+
options.headers = {};
|
|
714
|
+
}
|
|
715
|
+
options.headers['sw8'] = values;
|
|
716
|
+
_a.label = 1;
|
|
717
|
+
case 1:
|
|
718
|
+
_a.trys.push([1, 3, , 4]);
|
|
719
|
+
onBefore && onBefore({
|
|
720
|
+
url: url,
|
|
721
|
+
method: options.method,
|
|
722
|
+
options: options
|
|
723
|
+
});
|
|
724
|
+
return [4 /*yield*/, originFetch(url, options)];
|
|
725
|
+
case 2:
|
|
726
|
+
res = _a.sent();
|
|
727
|
+
onAfter && onAfter(res);
|
|
728
|
+
return [3 /*break*/, 4];
|
|
729
|
+
case 3:
|
|
730
|
+
err_1 = _a.sent();
|
|
731
|
+
if (!!options.signal && err_1.name == 'AbortError') {
|
|
732
|
+
onError({
|
|
733
|
+
url: url,
|
|
734
|
+
status: res.status,
|
|
735
|
+
statusText: res.statusText,
|
|
736
|
+
method: options.method,
|
|
737
|
+
body: options.body,
|
|
738
|
+
elapsedTime: getTimestamp() - startTime,
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
else {
|
|
742
|
+
throw err_1;
|
|
743
|
+
}
|
|
744
|
+
return [3 /*break*/, 4];
|
|
745
|
+
case 4:
|
|
746
|
+
if (!(res.ok && res.status >= 200 && res.status < 300)) {
|
|
747
|
+
onError({
|
|
748
|
+
url: url,
|
|
749
|
+
status: res.status,
|
|
750
|
+
statusText: res.statusText,
|
|
751
|
+
method: options.method,
|
|
752
|
+
body: options.body,
|
|
753
|
+
elapsedTime: getTimestamp() - startTime,
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
return [2 /*return*/, res];
|
|
757
|
+
}
|
|
758
|
+
});
|
|
759
|
+
});
|
|
760
|
+
};
|
|
761
|
+
};
|
|
762
|
+
|
|
763
|
+
// https://www.cnblogs.com/cute/p/13142139.html
|
|
764
|
+
function bin2hex(str) {
|
|
765
|
+
// discuss at: http://phpjs.org/functions/bin2hex/
|
|
766
|
+
// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
|
|
767
|
+
// bugfixed by: Onno Marsman
|
|
768
|
+
// bugfixed by: Linuxworld
|
|
769
|
+
// improved by: ntoniazzi (http://phpjs.org/functions/bin2hex:361#comment_177616)
|
|
770
|
+
// example 1: bin2hex('Kev');
|
|
771
|
+
// returns 1: '4b6576'
|
|
772
|
+
// example 2: bin2hex(String.fromCharCode(0x00));
|
|
773
|
+
// returns 2: '00'
|
|
774
|
+
// https://gist.github.com/cythrawll/8603752
|
|
775
|
+
// let i = 0
|
|
776
|
+
var o = '';
|
|
777
|
+
// let l: number
|
|
778
|
+
var n = null;
|
|
779
|
+
str += '';
|
|
780
|
+
for (var i = 0, l = str.length; i < l; i++) {
|
|
781
|
+
n = str.charCodeAt(i).toString(16);
|
|
782
|
+
o += n.length < 2 ? '0' + n : n;
|
|
783
|
+
}
|
|
784
|
+
return o;
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* 生成唯一ID(非用户ID)
|
|
788
|
+
* 通过HTML5 Canvas API创建一个接近不重复的唯一指纹ID
|
|
789
|
+
* @param content
|
|
790
|
+
* @returns
|
|
791
|
+
*/
|
|
792
|
+
var getFingerprintId = function (content, options) {
|
|
793
|
+
if (!content) {
|
|
794
|
+
console.error("content is empty");
|
|
795
|
+
return null;
|
|
796
|
+
}
|
|
797
|
+
var canvas = document.createElement('canvas');
|
|
798
|
+
var ctx = canvas.getContext("2d");
|
|
799
|
+
// 如果不存在,则返回空值,说明不支持Canvas指纹
|
|
800
|
+
if (!ctx)
|
|
801
|
+
return null;
|
|
802
|
+
var txt = content || 'geekbang';
|
|
803
|
+
ctx.textBaseline = options && options.textBaseline ? options.textBaseline : "top";
|
|
804
|
+
ctx.font = options && options.font ? options.font : "14px 'Arial'";
|
|
805
|
+
ctx.fillStyle = options && options.reactStyle ? options.reactStyle : "#f60";
|
|
806
|
+
// 先画一个62x20矩形内容
|
|
807
|
+
ctx.fillRect(125, 1, 62, 20);
|
|
808
|
+
ctx.fillStyle = options && options.contentStyle ? options.contentStyle : "#069";
|
|
809
|
+
// 把字填充到矩形内
|
|
810
|
+
ctx.fillText(txt, 2, 15);
|
|
811
|
+
// ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
|
|
812
|
+
// ctx.fillText(txt, 4, 17);
|
|
813
|
+
var b64 = canvas.toDataURL().replace("data:image/png;base64,", "");
|
|
814
|
+
var bin = atob(b64);
|
|
815
|
+
var crc = bin2hex(bin.slice(-16, -12));
|
|
816
|
+
return crc;
|
|
817
|
+
};
|
|
818
|
+
|
|
819
|
+
function unwrapExports (x) {
|
|
820
|
+
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
function createCommonjsModule(fn, module) {
|
|
824
|
+
return module = { exports: {} }, fn(module, module.exports), module.exports;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
var websdk_min = createCommonjsModule(function (module, exports) {
|
|
828
|
+
!function(e,t){module.exports=t();}(window,function(){return n=[function(e,t,n){function o(e){return (o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,function(e){e=function(e,t){if("object"!==o(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0===n)return ("string"===t?String:Number)(e);n=n.call(e,t||"default");if("object"!==o(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return "symbol"===o(e)?e:String(e)}(r.key),r);}}Object.defineProperty(t,"__esModule",{value:!0}),t.webPrint=void 0;var c=n(3),n=function(){function e(){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function");this.logLevel=c.LogLevel.OFF;}var t,n;return t=e,(n=[{key:"initLogLevel",value:function(e){e&&(c.LogLevel[e.debug]?this.logLevel=e.debug:e.debug&&"boolean"==typeof e.debug?this.logLevel=c.LogLevel.DEBUG:this.logLevel=c.LogLevel.OFF);}},{key:"log",value:function(e){1<=this.isEnumVal(this.logLevel)&&console.log("LTSSDK:".concat(e));}},{key:"warn",value:function(e){2<=this.isEnumVal(this.logLevel)&&console.warn("LTSSDK:".concat(e));}},{key:"error",value:function(e){3<=this.isEnumVal(this.logLevel)&&console.error("LTSSDK:".concat(e));}},{key:"isEnumVal",value:function(e){return [c.LogLevel.OFF,c.LogLevel.INFO,c.LogLevel.WARN,c.LogLevel.ERROR,c.LogLevel.DEBUG].indexOf(e)}}])&&i(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.webPrint=new n;},function(e,n,t){function r(e){return (r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(n,"__esModule",{value:!0}),n.checkConfigKey=n.checkLabels=n.checkObjectTypeAndLength=n.checkPattern=n.checkLogParamString=n.excludeObject=n.isValidString=n.isEmpty=void 0;var o=t(0),i="The length of $1 exceeds the maximum value of $2.",c="$1 is null.",a="$1 is invalid.";function l(e){return !e||""===e}n.isEmpty=l;n.isValidString=function(e,t){return l(e)?(o.webPrint.warn("LTS.0001|".concat(c.replace("$1",t))),!1):"string"==typeof e||(o.webPrint.warn("LTS.0002|".concat(a.replace("$1",t))),!1)},n.excludeObject=function(e,t){return "object"!==r(e)||(o.webPrint.warn("LTS.0002|".concat(a.replace("$1",t))),!1)},n.checkLogParamString=function(e,t,n){return t?!(String(t).length>n&&(o.webPrint.warn("LTS.0003|".concat(i.replace("$1",e).replace("$2",n))),1)):(o.webPrint.warn("LTS.0001|".concat(c.replace("$1",e))),!1)},n.checkPattern=function(e,t,n){return !!n.test(t)||(o.webPrint.warn("LTS.0006|".concat(e," doesn't match pattern.")),!1)},n.checkObjectTypeAndLength=function(e,t,n){return e&&"object"!==r(e)||"boolean"==typeof e?(o.webPrint.warn("LTS.0002|".concat(a.replace("$1",t))),!1):!(Object.keys(e).length>n&&(o.webPrint.warn("LTS.0003|".concat(i.replace("$1",t).replace("$2",n))),1))},n.checkLabels=function(e){var t;return !e||!(!(0, n.checkObjectTypeAndLength)(e,"labels",50)||!(0, n.checkLogParamString)("labels value",JSON.stringify(e),30720))&&(t=!0,Object.keys(e||{}).forEach(function(e){(0, n.checkLogParamString)("labels key:".concat(e),e,64)||(t=!1),(0, n.checkPattern)("labels key:".concat(e),e,/^[a-zA-Z][A-Za-z0-9_]*$/)||(t=!1);}),t)};n.checkConfigKey=function(e){var t,n=new Set(["url","region","projectId","groupId","streamId","group","cacheThreshold","timeThreshold","debug","platform","logLevel","timeInterval"]);return !e||(t=!0,Object.keys(e).forEach(function(e){n.has(e)||(t=!1);}),t||o.webPrint.warn("LTS.0007|Invalid configuration parameters."),t)};},function(e,t,n){function r(e){return function(e){if(Array.isArray(e))return o(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){var n;if(e)return "string"==typeof e?o(e,t):"Map"===(n="Object"===(n=Object.prototype.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?o(e,t):void 0}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}Object.defineProperty(t,"__esModule",{value:!0}),t.getLabelMap=t.getHeader=t.getBodyArray=void 0;var i=n(9),c=n(10).version,a=(t.getBodyArray=function(e,t,n){return l(n,e)?a(t,n):null},function(e,t){return {labels:e&&JSON.parse(e)||{},logs:(t||[]).map(function(e){return {contents:[Object.assign(Object.assign({},null==e?void 0:e.content),{__client_time__:e.log_time_ns})]}})}}),l=function(e,t){return !(!e||0===e.length||(t=(e=t||{}).groupId,e=e.streamId,!t)||!e)},u=(t.getLabelMap=function(e){var t=new Map;return e.forEach(function(e){t.has(e.labels)?t.set(e.labels,[].concat(r(t.get(e.labels)),[e])):t.set(e.labels,[e]);}),t},t.getHeader=function(e){var t="X-Sdk-date",n="Lts-Sdk-Version",r={"Content-Type":"application/json"};return r["Lts-Sdk-Request-Id"]=i.UUID.create(),r[n]=c,r[t]=u(),Object.assign(Object.assign({},r),e)},function(){try{return (new Date).toISOString().replace(/\.[\d]{3}Z/,"Z").replace(/(\:)|(\-)/g,"")}catch(e){return ""}});},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=t.REGIONS=t.POLICY_CONSTANTS=void 0,t.POLICY_CONSTANTS={TIME_MIN:1,TIME_MAX:1800,THRESHOLD_MIN:30,THRESHOLD_MAX:1e3},t.REGIONS={"cn-north-7":"cn-north-7","cn-north-4":"cn-north-4","cn-north-6":"cn-north-6","cn-north-5":"cn-north-5","cn-north-9":"cn-north-9","cn-east-3":"cn-east-3","cn-south-1":"cn-south-1","ru-northwest-2":"ru-northwest-2","af-south-1":"af-south-1","cn-north-1":"cn-north-1","cn-east-2":"cn-east-2","cn-south-4":"cn-south-4","cn-south-2":"cn-south-2","cn-southwest-2":"cn-southwest-2","ap-southeast-2":"ap-southeast-2","ap-southeast-3":"ap-southeast-3","ap-southeast-1":"ap-southeast-1","cn-north-2":"cn-north-2"},t.LogLevel={OFF:"OFF",INFO:"INFO",WARN:"WARN",ERROR:"ERROR",DEBUG:"DEBUG"};},function(e,t,n){e.exports=n(5);},function(e,t,n){function o(e){return (o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,function(e){e=function(e,t){if("object"!==o(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0===n)return ("string"===t?String:Number)(e);n=n.call(e,t||"default");if("object"!==o(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return "symbol"===o(e)?e:String(e)}(r.key),r);}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var c=n(6),a=n(11),l=n(0),u=n(1),n=function(){function t(e){if(!(this instanceof t))throw new TypeError("Cannot call a class as a function");this.uploading=!1,this.sendService={reportFlag:!1,url:""},this.logRecords=[],this.config(e);}var e,n;return e=t,(n=[{key:"config",value:function(e){(0, u.checkObjectTypeAndLength)(e,"Configuration",11)&&(this.webConfig=Object.assign(Object.assign({},this.webConfig),e),l.webPrint.initLogLevel(this.webConfig),this.webConfig.timeThreshold=(null==(e=this.webConfig)?void 0:e.timeInterval)||(null==(e=this.webConfig)?void 0:e.timeThreshold)||3),a.default.checkConfig(this.webConfig)?(this.sendService.reportFlag=!0,this.sendService.url=a.default.updateUrl(this.webConfig),this.logUploadPolicyScheduleTime(),l.webPrint.log("init success")):(this.sendService.reportFlag=!1,l.webPrint.error("Failed to initialize the sdk."));}},{key:"reportImmediately",value:function(e,t){l.webPrint.initLogLevel(this.webConfig),this.sendService.reportFlag?(c.default.writeLog(Object.assign(Object.assign({},this.webConfig),this.sendService),this.logRecords,e,t),c.default.uploadData(Object.assign(Object.assign({},this.webConfig),this.sendService),this.logRecords)):l.webPrint.log("LTS.0100|The LTSSDK is not initialized.");}},{key:"report",value:function(e,t){l.webPrint.initLogLevel(this.webConfig),this.sendService.reportFlag?e?c.default.writeLog(Object.assign(Object.assign({},this.webConfig),this.sendService),this.logRecords,e,t):l.webPrint.warn("LTS.0001|Content is null."):l.webPrint.log("LTS.0100|The LTSSDK is not initialized.");}},{key:"logUploadPolicyScheduleTime",value:function(){var e;this.webConfig.timeThreshold&&!this.uploading&&(e=1e3*this.webConfig.timeThreshold,this.setHeartbeatFunc(e));}},{key:"setHeartbeatFunc",value:function(e){var t=this;this.sendTimer=setTimeout(function(){t.uploading=!0,t.logRecords=t.logRecords.filter(function(e){return "SUCCESS"!==e.sendState}),c.default.uploadData(Object.assign(Object.assign({},t.webConfig),t.sendService),t.logRecords),t.uploading=!1,t.logUploadPolicyScheduleTime();},e);}}])&&i(e.prototype,n),Object.defineProperty(e,"prototype",{writable:!1}),t}();t.default=n;},function(e,t,n){function o(e){return (o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,function(e){e=function(e,t){if("object"!==o(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0===n)return ("string"===t?String:Number)(e);n=n.call(e,t||"default");if("object"!==o(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return "symbol"===o(e)?e:String(e)}(r.key),r);}}Object.defineProperty(t,"__esModule",{value:!0});var c=n(7),a=n(2),l=n(1),u=n(0),n=function(){function e(){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function");this.failTime=0,this.failTimer=null,this.failLockTime=1,this.censor=function(e,t){return t==1/0||t==-1/0?String(t):t};}var t,n;return t=e,(n=[{key:"uploadData",value:function(n,e){var r=this;n.reportFlag&&(10<=this.failTime?this.initTimeLock():(e=e.filter(function(e){return "READY"===e.sendState||"RESEND"===e.sendState}),(e=(0, a.getLabelMap)(e))&&0!==e.size&&e.forEach(function(e,t){e=r.getLogListSplitByBodyLimit(e);r.sendDataByPackage(e,t,n);})));}},{key:"getLogListSplitByBodyLimit",value:function(t){var n,r,o,i;return t&&0!==t.length?(n=[],i=o=r=0,t.forEach(function(e){e=JSON.stringify(e).length;96256<=(i+=e)&&(n.push(t.slice(r,o)),i=e,r=o),o++;}),r!==o&&n.push(t.slice(r,o)),n):[]}},{key:"sendDataByPackage",value:function(e,r,o){var i=this;e.forEach(function(t){var e,n=(0, a.getBodyArray)(o,r,t);"string"==typeof n&&(0, l.isEmpty)(n)||(e=(0, a.getHeader)({}),t.forEach(function(e){e.sendState="SENDING";}),(0, c.default)(n,e,o).then(function(){i.doUploadSuccess(t,o);},function(e){i.doUploadFail(o,t,e);}).catch(function(e){i.doUploadFail(o,t,e);}));});}},{key:"initTimeLock",value:function(){var e=this;this.failTimer||(this.failLockTime=this.failLockTime<32?2*this.failLockTime:32,this.failTimer=setTimeout(function(){e.failTime=0,e.failTimer=null;},6e4*this.failLockTime));}},{key:"doUploadFail",value:function(e,t,n){this.failTime++,t.forEach(function(e){e.sendState="RESEND";}),u.webPrint.initLogLevel(e),u.webPrint.error("LTS.0300|Request failed, response code=".concat(n.status||"--",", error=").concat(n.statusText||"send fail","."));}},{key:"doUploadSuccess",value:function(e,t){this.failTime=0,this.failLockTime=1,e.forEach(function(e){e.sendState="SUCCESS";}),u.webPrint.initLogLevel(t),u.webPrint.log("senddata success.");}},{key:"logUploadPolicyThreshold",value:function(e,t){e.cacheThreshold&&t.filter(function(e){return "READY"===e.sendState||"RESEND"===e.sendState}).length>=e.cacheThreshold&&this.uploadData(e,t);}},{key:"writeLog",value:function(t,n,e,r){var o=this;e&&(0, l.checkLabels)(r)&&(Array.isArray(e)?e.forEach(function(e){o.addLogToList(t,n,e,r);}):this.addLogToList(t,n,e,r));}},{key:"addLogToList",value:function(e,t,n,r){(0, l.checkObjectTypeAndLength)(n,"content",300)?(r={labels:JSON.stringify(r,this.censor),content:this.formatLogContent(n),sendState:"READY",log_time_ns:(new Date).getTime()},t.push(r),this.logUploadPolicyThreshold(e,t)):(u.webPrint.initLogLevel(e),u.webPrint.warn("LTS.0002|Log content is invalid."));}},{key:"formatLogContent",value:function(e){var t=JSON.stringify(e,this.censor);return 30720<(null==t?void 0:t.length)?{content:t.substring(0,30720)}:e}}])&&i(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.default=new n;},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var r=n(8);t.default=function(e,t,n){return (new r.default).webRequest(e,t,n)};},function(e,t,n){function o(e){return (o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,function(e){e=function(e,t){if("object"!==o(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0===n)return ("string"===t?String:Number)(e);n=n.call(e,t||"default");if("object"!==o(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return "symbol"===o(e)?e:String(e)}(r.key),r);}}Object.defineProperty(t,"__esModule",{value:!0});var c=n(2),n=function(){function e(){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function")}var t,n;return t=e,(n=[{key:"webRequest",value:function(e,t,n){return n.url?(t=(0, c.getHeader)(t),null!==window&&void 0!==window&&window.XMLHttpRequest?this.sendByAjax(e,t,n):"undefined"!=typeof fetch?this.sendByBeacon(e,t,n):Promise.reject(new Error("not supported"))):Promise.reject(new Error("check the config."))}},{key:"sendByBeacon",value:function(e,r,t){var o;return "undefined"!=typeof fetch?(o=null==t?void 0:t.url,new Promise(function(t,n){fetch(o,{method:"POST",body:JSON.stringify(e),headers:r}).then(function(e){200===e.status?t():n(e);}).catch(function(e){n(e);});})):Promise.reject(new Error("missing fetch method"))}},{key:"sendByAjax",value:function(f,d,b){return new Promise(function(e,t){var n=null==b?void 0:b.url;if(window.XMLHttpRequest&&n){var r=new XMLHttpRequest;if(r.timeout=15e3,r.onabort=function(){t(new Error("The request was aborted!"));},r.onerror=function(){t(new Error("An error occurred during the transaction!"));},r.ontimeout=function(){t(new Error("Timeout!"));},r.onload=function(){r.readyState===r.DONE&&200===r.status?e():t(new Error("senddata fail!"));},b&&"get"===String(b.method).toLocaleLowerCase()){r.open("GET",n+"?"+f,!0);for(var o=0,i=Object.keys(d);o<i.length;o++){var c=i[o];r.setRequestHeader(c,d[c]);}r.send();}else{var a=b&&b.async;r.open("POST",n,null==a||a);for(var l=0,u=Object.keys(d);l<u.length;l++){var s=u[l];r.setRequestHeader(s,d[s]);}r.send(JSON.stringify(f));}}else t(new Error("url is missing"));})}}])&&i(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.default=n;},function(e,t,n){function o(e){return (o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,function(e){e=function(e,t){if("object"!==o(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0===n)return ("string"===t?String:Number)(e);n=n.call(e,t||"default");if("object"!==o(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return "symbol"===o(e)?e:String(e)}(r.key),r);}}Object.defineProperty(t,"__esModule",{value:!0}),t.UUID=void 0;var r=function(){function e(){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function")}var t,n;return t=e,(n=[{key:"create",value:function(){var e=Math.floor(Math.random()*(Math.pow(2,12)-1+1))+0,t=Math.floor(Math.random()*(Math.pow(2,32)-1+1))+0,n=Math.floor(Math.random()*(Math.pow(2,16)-1+1))+0,r=Math.floor(Math.random()*(Math.pow(2,6)-1+1))+0,o=Math.floor(Math.random()*(Math.pow(2,8)-1+1))+0,i=(0|Math.random()*(1<<30))+(0|Math.random()*(1<<18))*(1<<30);function c(e,t,n){n=n||"0";for(var r=t-(e=String(e)).length;0<r;r>>>=1,n+=n)1&r&&(e=n+e);return e}return [c(t.toString(16),8),c(n.toString(16),4),c((16384|e).toString(16),4),c((128|r).toString(16),2),c(o.toString(16),2),c(i.toString(16),12)].join("")}}])&&i(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.UUID=new r;},function(e){e.exports=JSON.parse('{"name":"@cloud/lts-web-sdk","version":"1.0.24","description":"lts-web-sdk","main":"./websdk.min.js","license":"MIT","scripts":{"debug":"http-serve -p 8080","build":"rimraf dist && cross-env NODE_ENV=development webpack --config webpack.config.js","build:prod":"rimraf dist && tsc -p tsconfig.json && cross-env NODE_ENV=production webpack --config webpack.config.js","lint":"eslint --ext .js src/","jest":"jest --coverage --watch","fix-lint":"eslint --ext .js src/ --fix","build:baidu":"rimraf lib && npx babel src --out-dir dist/src","build:bd":"rimraf dist && tsc -p tsconfig.json && cross-env NODE_ENV=production webpack --config webpack.config.js","build:cdn":"rimraf dist && tsc -p tsconfig.json && cross-env NODE_ENV=production webpack --config webpack-cdn.config.js","tsc":"tsc -p tsconfig.json","test":"mocha --exit","test-report":"tsc -p tsconfig.json && nyc --reporter=html mocha --exit"},"devDependencies":{"@babel/cli":"^7.4.3","@babel/core":"^7.4.3","@babel/preset-env":"^7.4.3","@cloud/eslint-config-cbc":"^1.7.3","babel-eslint":"^10.1.0","babel-loader":"^8.0.5","babel-plugin-syntax-dynamic-import":"^6.18.0","cross-env":"^5.2.1","eslint":"^6.1.0","http-serve":"^1.0.1","jest":"^27.4.5","mocha":"^10.2.0","nyc":"^15.1.0","sinon":"^15.2.0","uglifyjs-webpack-plugin":"^2.1.2","webpack":"^4.29.6","webpack-cli":"^3.3.0"}}');},function(e,t,n){function o(e){return (o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,function(e){e=function(e,t){if("object"!==o(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0===n)return ("string"===t?String:Number)(e);n=n.call(e,t||"default");if("object"!==o(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return "symbol"===o(e)?e:String(e)}(r.key),r);}}Object.defineProperty(t,"__esModule",{value:!0});var c=n(1),a=n(3),l=n(0),n=function(){function e(){var t=this;if(!(this instanceof e))throw new TypeError("Cannot call a class as a function");this.checkConfig=function(e){return !!e&&t.checkReportPolices(e)&&t.checkLogConfig(e)&&t.checkUrl(e)&&t.checkRegion(e)&&t.checkProjectId(e)&&(0, c.checkConfigKey)(e)},this.checkProjectId=function(e){e=null==e?void 0:e.projectId;return !(!(0, c.isValidString)(e,"projectId")||!(0, c.checkLogParamString)("projectId",e,128))},this.checkRegion=function(e){return !(!(0, c.checkLogParamString)("region",null==e?void 0:e.region,128)||!a.REGIONS[null==e?void 0:e.region]&&(l.webPrint.warn("LTS.0009|Unsupported region."),1))},this.checkUrl=function(e){return !(null!=e&&e.url&&!(0, c.checkLogParamString)("url",null==e?void 0:e.url,128)||null!=e&&e.url&&("string"!=typeof(null==e?void 0:e.url)||!/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]+$/.test(null==e?void 0:e.url))&&(l.webPrint.warn("LTS.0006|Url doesn't match pattern."),1))},this.checkLogConfig=function(e){var t=null==e?void 0:e.groupId;return !!((0, c.isValidString)(t,"groupId")&&(0, c.checkLogParamString)("groupId",t,128)&&(t=null==e?void 0:e.streamId,(0, c.isValidString)(t,"streamId"))&&(0, c.checkLogParamString)("streamId",t,128))};}var t,n;return t=e,(n=[{key:"updateUrl",value:function(e){var t=null==e?void 0:e.url,t=(null!=(t=t||"https://lts-access.".concat(e.region,".myhuaweicloud.com"))?t:"").split(",")[0];return "".concat(t,"/v3/").concat(e.projectId,"/lts/groups/").concat(e.groupId,"/streams/").concat(e.streamId,"/logs")}},{key:"checkReportPolices",value:function(e){if(e)return this.checkThreshold(e,"timeThreshold",a.POLICY_CONSTANTS.TIME_MIN,a.POLICY_CONSTANTS.TIME_MAX,"timeInterval")&&this.checkThreshold(e,"cacheThreshold",a.POLICY_CONSTANTS.THRESHOLD_MIN,a.POLICY_CONSTANTS.THRESHOLD_MAX)}},{key:"checkThreshold",value:function(e,t,n,r,o){var i=e[t];if(void 0===i)e[t]=30;else{if("number"!=typeof i)return l.webPrint.warn("LTS.0002|".concat(o||t," is invalid.")),!1;if(i<n||r<i)return l.webPrint.warn("LTS.0004|The value of ".concat(o||t," must be between ").concat(n," and ").concat(r,".")),!1}return !0}}])&&i(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.default=new n;}],r={},o.m=n,o.c=r,o.d=function(e,t,n){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n});},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0});},o.t=function(t,e){if(1&e&&(t=o(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)o.d(n,r,function(e){return t[e]}.bind(null,r));return n},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p="",o(o.s=4);function o(e){var t;return (r[e]||(t=r[e]={i:e,l:!1,exports:{}},n[e].call(t.exports,t,t.exports,o),t.l=!0,t)).exports}var n,r;});
|
|
829
|
+
});
|
|
830
|
+
|
|
831
|
+
var LTS_WEB_SDK = unwrapExports(websdk_min);
|
|
832
|
+
var websdk_min_1 = websdk_min.lib;
|
|
833
|
+
|
|
834
|
+
var ltsInstance = null;
|
|
835
|
+
function getDeviceClient() {
|
|
836
|
+
var _a, _b, _c;
|
|
837
|
+
if (typeof navigator === 'undefined') {
|
|
838
|
+
return {};
|
|
839
|
+
}
|
|
840
|
+
return {
|
|
841
|
+
name: navigator.userAgent,
|
|
842
|
+
version: navigator.appVersion,
|
|
843
|
+
language: navigator.language,
|
|
844
|
+
platform: navigator.platform,
|
|
845
|
+
screen: {
|
|
846
|
+
width: ((_a = window.screen) === null || _a === void 0 ? void 0 : _a.width) || 0,
|
|
847
|
+
height: ((_b = window.screen) === null || _b === void 0 ? void 0 : _b.height) || 0,
|
|
848
|
+
colorDepth: ((_c = window.screen) === null || _c === void 0 ? void 0 : _c.colorDepth) || 0
|
|
849
|
+
},
|
|
850
|
+
viewport: {
|
|
851
|
+
width: window.innerWidth || 0,
|
|
852
|
+
height: window.innerHeight || 0
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
function convertTraceDataToLTS(traceData) {
|
|
857
|
+
var data = traceData.data;
|
|
858
|
+
var hasStack = data && 'stack' in data && data.stack;
|
|
859
|
+
var exception = hasStack
|
|
860
|
+
? {
|
|
861
|
+
values: [
|
|
862
|
+
{
|
|
863
|
+
value: data.message || data.name || 'Unknown error',
|
|
864
|
+
stacktrace: {
|
|
865
|
+
frames: data.stack.split('\n').map(function (line) {
|
|
866
|
+
var _a, _b, _c, _d;
|
|
867
|
+
return ({
|
|
868
|
+
filename: ((_a = line.match(/\((.+):\d+:\d+\)/)) === null || _a === void 0 ? void 0 : _a.pop()) || 'unknown',
|
|
869
|
+
lineno: parseInt(((_b = line.match(/:(\d+):/)) === null || _b === void 0 ? void 0 : _b.pop()) || '0'),
|
|
870
|
+
colno: parseInt(((_c = line.match(/:\d+:(\d+)\)/)) === null || _c === void 0 ? void 0 : _c.pop()) || '0'),
|
|
871
|
+
function: ((_d = line.match(/at\s+(.+)\s+\(/)) === null || _d === void 0 ? void 0 : _d.pop()) || 'unknown'
|
|
872
|
+
});
|
|
873
|
+
})
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
]
|
|
877
|
+
}
|
|
878
|
+
: undefined;
|
|
879
|
+
var tags = {};
|
|
880
|
+
if (traceData.fpId)
|
|
881
|
+
tags.fpId = traceData.fpId;
|
|
882
|
+
if (traceData.pid)
|
|
883
|
+
tags.pid = traceData.pid;
|
|
884
|
+
if (traceData.appId)
|
|
885
|
+
tags.appId = traceData.appId;
|
|
886
|
+
if (traceData.uid)
|
|
887
|
+
tags.uid = String(traceData.uid);
|
|
888
|
+
if (data && 'tag' in data && data.tag) {
|
|
889
|
+
tags.tag = data.tag;
|
|
890
|
+
}
|
|
891
|
+
var hasUrl = data && 'url' in data && data.url;
|
|
892
|
+
var request = hasUrl
|
|
893
|
+
? {
|
|
894
|
+
url: data.url || '',
|
|
895
|
+
method: 'method' in data && data.method ? data.method : 'GET',
|
|
896
|
+
headers: {},
|
|
897
|
+
data: 'body' in data && data.body ? data.body : undefined
|
|
898
|
+
}
|
|
899
|
+
: undefined;
|
|
900
|
+
return {
|
|
901
|
+
client: getDeviceClient(),
|
|
902
|
+
environment: traceData.bt || 'unknown',
|
|
903
|
+
tags: tags,
|
|
904
|
+
level: traceData.level || 'info',
|
|
905
|
+
exception: exception,
|
|
906
|
+
transaction: traceData.traceId,
|
|
907
|
+
extra: {
|
|
908
|
+
type: traceData.type,
|
|
909
|
+
url: traceData.url,
|
|
910
|
+
ua: traceData.ua,
|
|
911
|
+
createdAt: traceData.createdAt,
|
|
912
|
+
updatedAt: traceData.updatedAt,
|
|
913
|
+
breadcrumbs: traceData.breadcrumbs,
|
|
914
|
+
perf: traceData.perf
|
|
915
|
+
},
|
|
916
|
+
request: request
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
function sendByLTS(ltsConfig, data) {
|
|
920
|
+
try {
|
|
921
|
+
if (!ltsInstance) {
|
|
922
|
+
ltsInstance = new LTS_WEB_SDK({
|
|
923
|
+
region: ltsConfig.region,
|
|
924
|
+
projectId: ltsConfig.projectId,
|
|
925
|
+
groupId: ltsConfig.groupId,
|
|
926
|
+
streamId: ltsConfig.streamId,
|
|
927
|
+
debug: ltsConfig.debug || false
|
|
928
|
+
});
|
|
929
|
+
}
|
|
930
|
+
var ltsData = convertTraceDataToLTS(data);
|
|
931
|
+
ltsInstance.reportImmediately(ltsData);
|
|
932
|
+
}
|
|
933
|
+
catch (error) {
|
|
934
|
+
console.error('Failed to send data to LTS:', error);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
// 使用sendBeacon发送数据
|
|
938
|
+
function sendBeacon(url, data) {
|
|
939
|
+
if (typeof navigator === 'undefined')
|
|
940
|
+
return;
|
|
941
|
+
navigator.sendBeacon && navigator.sendBeacon(url, JSON.stringify(data));
|
|
942
|
+
}
|
|
943
|
+
// 使用img发送数据
|
|
944
|
+
function sendByImg(url, data) {
|
|
945
|
+
var spliceStr = url.indexOf('?') === -1 ? '?' : '&';
|
|
946
|
+
var imageUrl = "".concat(url).concat(spliceStr, "data=").concat(encodeURIComponent(safeStringify(data)));
|
|
947
|
+
var img = new Image();
|
|
948
|
+
img.src = imageUrl;
|
|
949
|
+
img.onload = function () {
|
|
950
|
+
console.log('Tracking data sent successfully!');
|
|
951
|
+
img = null;
|
|
952
|
+
};
|
|
953
|
+
img.onerror = function (err) {
|
|
954
|
+
console.error('Failed to send tracking data.', err);
|
|
955
|
+
img = null;
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
// 统一的发送接口
|
|
959
|
+
function send(method, url, ltsConfig, data) {
|
|
960
|
+
switch (method) {
|
|
961
|
+
case SendMethod.BEACON:
|
|
962
|
+
if (url) {
|
|
963
|
+
sendBeacon(url, data);
|
|
964
|
+
}
|
|
965
|
+
else {
|
|
966
|
+
console.warn('dsn is required for beacon method');
|
|
967
|
+
}
|
|
968
|
+
break;
|
|
969
|
+
case SendMethod.LTS:
|
|
970
|
+
if (ltsConfig) {
|
|
971
|
+
sendByLTS(ltsConfig, data);
|
|
972
|
+
}
|
|
973
|
+
else {
|
|
974
|
+
console.warn('ltsConfig is required for lts method');
|
|
975
|
+
}
|
|
976
|
+
break;
|
|
977
|
+
case SendMethod.IMG:
|
|
978
|
+
default:
|
|
979
|
+
if (url) {
|
|
980
|
+
sendByImg(url, data);
|
|
981
|
+
}
|
|
982
|
+
else {
|
|
983
|
+
console.warn('dsn is required for img method');
|
|
984
|
+
}
|
|
985
|
+
break;
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
var BaseTrace = /** @class */ (function () {
|
|
990
|
+
function BaseTrace(options) {
|
|
991
|
+
var _this = this;
|
|
992
|
+
// 日志上报后端API
|
|
993
|
+
this.dsn = '';
|
|
994
|
+
// 页面ID
|
|
995
|
+
this.pageId = '';
|
|
996
|
+
//
|
|
997
|
+
this.userAgent = navigator.userAgent;
|
|
998
|
+
//
|
|
999
|
+
this.browserType = BrowserType.MOBILE;
|
|
1000
|
+
// fingerprintId
|
|
1001
|
+
this.fpId = '';
|
|
1002
|
+
// user id
|
|
1003
|
+
this.uid = '';
|
|
1004
|
+
// appId
|
|
1005
|
+
this.appId = '';
|
|
1006
|
+
// 是否开启debug状态
|
|
1007
|
+
this.debug = true;
|
|
1008
|
+
// 发送方式
|
|
1009
|
+
this.sendMethod = SendMethod.IMG;
|
|
1010
|
+
// 性能日志数据
|
|
1011
|
+
this.perfData = {
|
|
1012
|
+
id: ''
|
|
1013
|
+
};
|
|
1014
|
+
// 存储错误资源数据
|
|
1015
|
+
this.resources = [];
|
|
1016
|
+
this.result = {};
|
|
1017
|
+
// 记录用户行为
|
|
1018
|
+
this.breadcrumb = [];
|
|
1019
|
+
// 最大存储用户行为
|
|
1020
|
+
this.maxBreadcrumb = 10;
|
|
1021
|
+
// 是否开启用户行为
|
|
1022
|
+
this.breadcrumbEnabled = true;
|
|
1023
|
+
this.observer = null;
|
|
1024
|
+
// 存储链路日志数据
|
|
1025
|
+
this.queue = [];
|
|
1026
|
+
// 发送请求时间间隔
|
|
1027
|
+
this.sendTimer = 1000;
|
|
1028
|
+
console.log('BaseTrace constructor.');
|
|
1029
|
+
this.pageId = uuid();
|
|
1030
|
+
this.dsn = options.dsn || '';
|
|
1031
|
+
this.appId = options.appId;
|
|
1032
|
+
this.debug = !!options.debug;
|
|
1033
|
+
this.sendMethod = options.sendMethod || SendMethod.IMG;
|
|
1034
|
+
this.ltsConfig = options.ltsConfig;
|
|
1035
|
+
this.perfData = {
|
|
1036
|
+
id: generateUniqueId$1()
|
|
1037
|
+
};
|
|
1038
|
+
this.fpId = getFingerprintId('TraceCourse');
|
|
1039
|
+
this.observer = new PerformanceObserver(function (list, observer) {
|
|
1040
|
+
list.getEntries().forEach(function (entry) {
|
|
1041
|
+
_this.debug && console.debug("name : ".concat(entry.name));
|
|
1042
|
+
_this.debug && console.debug("type : ".concat(entry.entryType));
|
|
1043
|
+
_this.debug && console.debug("duration: ".concat(entry.duration));
|
|
1044
|
+
if (entry.entryType === 'resource') {
|
|
1045
|
+
_this.handleObserverResource(entry);
|
|
1046
|
+
}
|
|
1047
|
+
});
|
|
1048
|
+
});
|
|
1049
|
+
}
|
|
1050
|
+
BaseTrace.prototype.log = function (log) {
|
|
1051
|
+
this.saveBreadcrumb({
|
|
1052
|
+
name: 'customer-log',
|
|
1053
|
+
level: log.level,
|
|
1054
|
+
type: dataTypes2BreadcrumbsType(log.type),
|
|
1055
|
+
category: dataCategory2BreadcrumbsCategory(log.type),
|
|
1056
|
+
message: log.message,
|
|
1057
|
+
time: getTimestamp()
|
|
1058
|
+
});
|
|
1059
|
+
this.debug && console.debug("log: ".concat(JSON.stringify(log)));
|
|
1060
|
+
this.send(log);
|
|
1061
|
+
};
|
|
1062
|
+
BaseTrace.prototype.info = function (message, tag) {
|
|
1063
|
+
this.log({
|
|
1064
|
+
name: 'customer-info',
|
|
1065
|
+
type: TraceDataTypes.LOG,
|
|
1066
|
+
level: TraceDataSeverity.Info,
|
|
1067
|
+
message: message,
|
|
1068
|
+
time: getTimestamp(),
|
|
1069
|
+
dataId: hashCode("".concat(message, "|").concat(tag || '')),
|
|
1070
|
+
tag: tag
|
|
1071
|
+
});
|
|
1072
|
+
};
|
|
1073
|
+
BaseTrace.prototype.warn = function (message, tag) {
|
|
1074
|
+
this.log({
|
|
1075
|
+
name: 'customer-warning',
|
|
1076
|
+
type: TraceDataTypes.LOG,
|
|
1077
|
+
level: TraceDataSeverity.Warning,
|
|
1078
|
+
message: message,
|
|
1079
|
+
time: getTimestamp(),
|
|
1080
|
+
dataId: hashCode("".concat(message, "|").concat(tag || '')),
|
|
1081
|
+
tag: tag
|
|
1082
|
+
});
|
|
1083
|
+
};
|
|
1084
|
+
BaseTrace.prototype.error = function (message, tag) {
|
|
1085
|
+
this.log({
|
|
1086
|
+
name: 'customer-error',
|
|
1087
|
+
type: TraceDataTypes.LOG,
|
|
1088
|
+
level: TraceDataSeverity.Error,
|
|
1089
|
+
message: message,
|
|
1090
|
+
time: getTimestamp(),
|
|
1091
|
+
dataId: hashCode("".concat(message, "|").concat(tag || '')),
|
|
1092
|
+
tag: tag
|
|
1093
|
+
});
|
|
1094
|
+
};
|
|
1095
|
+
BaseTrace.prototype.setTraceData = function (data) {
|
|
1096
|
+
var type = TraceTypes.CONSOLE;
|
|
1097
|
+
var level = TraceLevelType.Debug;
|
|
1098
|
+
var _data = null;
|
|
1099
|
+
var perf = null;
|
|
1100
|
+
if (!!data.dataId) {
|
|
1101
|
+
type = getTraceDataType(data.type);
|
|
1102
|
+
level = getTraceDataLevel(data.level);
|
|
1103
|
+
_data = data;
|
|
1104
|
+
}
|
|
1105
|
+
if (!!data.id) {
|
|
1106
|
+
type = TraceTypes.PERF;
|
|
1107
|
+
level = getPerfLevel(data);
|
|
1108
|
+
perf = data;
|
|
1109
|
+
}
|
|
1110
|
+
var traceData = {
|
|
1111
|
+
type: type,
|
|
1112
|
+
level: level,
|
|
1113
|
+
createdAt: getTimestamp(),
|
|
1114
|
+
updatedAt: getTimestamp(),
|
|
1115
|
+
data: _data,
|
|
1116
|
+
perf: perf,
|
|
1117
|
+
breadcrumbs: this.breadcrumb,
|
|
1118
|
+
traceId: uuid(),
|
|
1119
|
+
ua: this.userAgent,
|
|
1120
|
+
bt: this.browserType,
|
|
1121
|
+
fpId: this.fpId,
|
|
1122
|
+
appId: this.appId,
|
|
1123
|
+
clientType: TraceClientTypes.BROWSER_H5,
|
|
1124
|
+
url: document.URL,
|
|
1125
|
+
pid: this.pageId,
|
|
1126
|
+
uid: this.uid
|
|
1127
|
+
};
|
|
1128
|
+
this.debug && console.log('[setTraceData]traceData: ', traceData);
|
|
1129
|
+
return traceData;
|
|
1130
|
+
};
|
|
1131
|
+
BaseTrace.prototype.send = function (data) {
|
|
1132
|
+
var traceData = this.setTraceData(data);
|
|
1133
|
+
send(this.sendMethod, this.dsn, this.ltsConfig, traceData);
|
|
1134
|
+
};
|
|
1135
|
+
BaseTrace.prototype.createPerfReport = function () {
|
|
1136
|
+
var _this = this;
|
|
1137
|
+
var report = function (metric) {
|
|
1138
|
+
_this.perfData = __assign(__assign({}, _this.perfData), mapMetric(metric));
|
|
1139
|
+
};
|
|
1140
|
+
setTimeout(function () {
|
|
1141
|
+
var supportedEntryTypes = (PerformanceObserver && PerformanceObserver.supportedEntryTypes) || [];
|
|
1142
|
+
var isLatestVisibilityChangeSupported = supportedEntryTypes.indexOf('layout-shift') !== -1;
|
|
1143
|
+
if (isLatestVisibilityChangeSupported) {
|
|
1144
|
+
var onVisibilityChange = function () {
|
|
1145
|
+
if (document.visibilityState === 'hidden') {
|
|
1146
|
+
console.log('this.send', _this.perfData);
|
|
1147
|
+
_this.send(_this.perfData);
|
|
1148
|
+
// removeEventListener('visibilitychange', onVisibilityChange, true)
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
addEventListener('visibilitychange', onVisibilityChange, true);
|
|
1152
|
+
}
|
|
1153
|
+
else {
|
|
1154
|
+
addEventListener('pagehide', function () {
|
|
1155
|
+
console.log('pagehide', _this.perfData);
|
|
1156
|
+
_this.send(_this.perfData);
|
|
1157
|
+
}, { capture: true, once: true });
|
|
1158
|
+
}
|
|
1159
|
+
});
|
|
1160
|
+
return report;
|
|
1161
|
+
};
|
|
1162
|
+
BaseTrace.prototype.saveError = function (event) {
|
|
1163
|
+
console.log('[onResourceError] event: ', event);
|
|
1164
|
+
var target = event.target || event.srcElement;
|
|
1165
|
+
var isResTarget = isResourceTarget(target);
|
|
1166
|
+
if (!isResTarget) {
|
|
1167
|
+
var traceData = {
|
|
1168
|
+
dataId: hashCode("".concat(event.type, "-").concat(event.error.stack)),
|
|
1169
|
+
name: 'script-error',
|
|
1170
|
+
level: TraceDataSeverity.Error,
|
|
1171
|
+
message: event.message,
|
|
1172
|
+
time: getTimestamp(),
|
|
1173
|
+
type: TraceDataTypes.JAVASCRIPT,
|
|
1174
|
+
stack: event.error.stack
|
|
1175
|
+
};
|
|
1176
|
+
this.resources.push(traceData);
|
|
1177
|
+
this.breadcrumb.push({
|
|
1178
|
+
name: event.error.name,
|
|
1179
|
+
type: BreadcrumbTypes.CODE_ERROR,
|
|
1180
|
+
category: BreadcrumbsCategorys.Exception,
|
|
1181
|
+
level: TraceDataSeverity.Error,
|
|
1182
|
+
message: event.message,
|
|
1183
|
+
stack: event.error.stack,
|
|
1184
|
+
time: getTimestamp()
|
|
1185
|
+
});
|
|
1186
|
+
this.queue.push(this.setTraceData(traceData));
|
|
1187
|
+
}
|
|
1188
|
+
else {
|
|
1189
|
+
var url = target.getAttribute('src') || target.getAttribute('href');
|
|
1190
|
+
var traceData = {
|
|
1191
|
+
dataId: hashCode("".concat(target.nodeName.toLowerCase(), "-").concat(event.message).concat(url)),
|
|
1192
|
+
name: 'resource-load-error',
|
|
1193
|
+
level: TraceDataSeverity.Warning,
|
|
1194
|
+
message: event.message,
|
|
1195
|
+
time: getTimestamp(),
|
|
1196
|
+
type: TraceDataTypes.RESOURCE,
|
|
1197
|
+
stack: null
|
|
1198
|
+
};
|
|
1199
|
+
this.resources.push(traceData);
|
|
1200
|
+
this.breadcrumb.push({
|
|
1201
|
+
name: traceData.name,
|
|
1202
|
+
type: BreadcrumbTypes.RESOURCE,
|
|
1203
|
+
category: BreadcrumbsCategorys.Exception,
|
|
1204
|
+
level: TraceDataSeverity.Warning,
|
|
1205
|
+
message: event.message,
|
|
1206
|
+
time: getTimestamp()
|
|
1207
|
+
});
|
|
1208
|
+
this.queue.push(this.setTraceData(traceData));
|
|
1209
|
+
}
|
|
1210
|
+
};
|
|
1211
|
+
BaseTrace.prototype.handleObserverResource = function (entry) {
|
|
1212
|
+
if (entry.entryType === 'resource') {
|
|
1213
|
+
var level = TraceDataSeverity.Info;
|
|
1214
|
+
if (entry.duration > 1000 && entry.duration < 1500) {
|
|
1215
|
+
level = TraceDataSeverity.Warning;
|
|
1216
|
+
}
|
|
1217
|
+
else if (entry.duration > 1500) {
|
|
1218
|
+
level = TraceDataSeverity.Error;
|
|
1219
|
+
}
|
|
1220
|
+
entry.duration > 1000 &&
|
|
1221
|
+
this.resources.push({
|
|
1222
|
+
url: entry.name,
|
|
1223
|
+
name: "".concat(entry.entryType, "-duration-").concat(entry.initiatorType),
|
|
1224
|
+
type: TraceDataTypes.PERF,
|
|
1225
|
+
level: level,
|
|
1226
|
+
message: "duration:".concat(Math.round(entry.duration)),
|
|
1227
|
+
time: getTimestamp(),
|
|
1228
|
+
dataId: hashCode("".concat(entry.entryType, "-").concat(entry.name))
|
|
1229
|
+
});
|
|
1230
|
+
}
|
|
1231
|
+
};
|
|
1232
|
+
// 这里的构造数据有问题,后续需要更新
|
|
1233
|
+
BaseTrace.prototype.onFetchError = function (message) {
|
|
1234
|
+
console.log('[onFetchError] message: ', message);
|
|
1235
|
+
var traceBaseData = {
|
|
1236
|
+
dataId: hashCode("".concat(message.url, "-").concat(message.method, "-").concat(message.status, "-").concat(message.statusText)),
|
|
1237
|
+
name: 'fetch-error',
|
|
1238
|
+
level: TraceDataSeverity.Critical,
|
|
1239
|
+
message: '',
|
|
1240
|
+
time: getTimestamp(),
|
|
1241
|
+
type: TraceDataTypes.HTTP
|
|
1242
|
+
};
|
|
1243
|
+
var errorData = __assign(__assign({}, traceBaseData), { url: message.url, status: message.status, message: message.statusText, method: message.method, body: message.body, elapsedTime: message.elapsedTime, httpType: 'fetch' });
|
|
1244
|
+
console.log('error data: ', errorData);
|
|
1245
|
+
this.queue.push(this.setTraceData(errorData));
|
|
1246
|
+
};
|
|
1247
|
+
BaseTrace.prototype.onGlobalError = function () {
|
|
1248
|
+
var _t = this;
|
|
1249
|
+
console.log('onGlobalError');
|
|
1250
|
+
window.addEventListener('error', function (event) {
|
|
1251
|
+
_t.saveError(event);
|
|
1252
|
+
});
|
|
1253
|
+
window.addEventListener('unhandledrejection', function (event) {
|
|
1254
|
+
// _t.saveError(event)
|
|
1255
|
+
console.log(event);
|
|
1256
|
+
if (event instanceof PromiseRejectionEvent) {
|
|
1257
|
+
var errorEvent = new ErrorEvent('promiseRejection', {
|
|
1258
|
+
message: event.reason.toString(),
|
|
1259
|
+
// filename: event.filename,
|
|
1260
|
+
// lineno: event.lineno,
|
|
1261
|
+
// colno: event.colno,
|
|
1262
|
+
error: event.reason
|
|
1263
|
+
});
|
|
1264
|
+
_t.saveError(errorEvent);
|
|
1265
|
+
}
|
|
1266
|
+
else if (event instanceof ErrorEvent) {
|
|
1267
|
+
_t.saveError(event);
|
|
1268
|
+
}
|
|
1269
|
+
});
|
|
1270
|
+
};
|
|
1271
|
+
BaseTrace.prototype.onGlobalClick = function () {
|
|
1272
|
+
var _this = this;
|
|
1273
|
+
window.addEventListener('click', function (event) {
|
|
1274
|
+
var target = event.target;
|
|
1275
|
+
var innerHTML = target.innerHTML;
|
|
1276
|
+
var bc = {
|
|
1277
|
+
name: 'click',
|
|
1278
|
+
level: TraceDataSeverity.Normal,
|
|
1279
|
+
type: BreadcrumbTypes.CLICK,
|
|
1280
|
+
category: BreadcrumbsCategorys.User,
|
|
1281
|
+
message: innerHTML,
|
|
1282
|
+
time: getTimestamp()
|
|
1283
|
+
};
|
|
1284
|
+
_this.saveBreadcrumb(bc);
|
|
1285
|
+
});
|
|
1286
|
+
};
|
|
1287
|
+
BaseTrace.prototype.onObserverResource = function () {
|
|
1288
|
+
// const observer = new PerformanceObserver((list, observer) => {
|
|
1289
|
+
// list.getEntries().forEach((entry) => {
|
|
1290
|
+
// console.log(`name : ${entry.name}`);
|
|
1291
|
+
// console.log(`type : ${entry.entryType}`);
|
|
1292
|
+
// console.log(`duration: ${entry.duration}`);
|
|
1293
|
+
// _t.handleObserverResource(entry)
|
|
1294
|
+
// });
|
|
1295
|
+
// });
|
|
1296
|
+
// observer.observe({
|
|
1297
|
+
// entryTypes: ["resource"],
|
|
1298
|
+
// });
|
|
1299
|
+
};
|
|
1300
|
+
BaseTrace.prototype.saveBreadcrumb = function (data) {
|
|
1301
|
+
if (this.breadcrumbEnabled) {
|
|
1302
|
+
this.breadcrumb.push(data);
|
|
1303
|
+
if (this.breadcrumb.length > this.maxBreadcrumb) {
|
|
1304
|
+
this.breadcrumb.shift();
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
};
|
|
1308
|
+
BaseTrace.prototype.setUserId = function (userId) {
|
|
1309
|
+
this.uid = userId;
|
|
1310
|
+
};
|
|
1311
|
+
// 初始化实例
|
|
1312
|
+
BaseTrace.init = function (options) {
|
|
1313
|
+
var traceSdk = new BaseTrace(options);
|
|
1314
|
+
traceSdk.onGlobalError();
|
|
1315
|
+
// traceSdk.onObserverResource()
|
|
1316
|
+
traceSdk.observer.observe({
|
|
1317
|
+
entryTypes: ['resource']
|
|
1318
|
+
});
|
|
1319
|
+
window.fetch = interceptFetch({
|
|
1320
|
+
pagePath: '',
|
|
1321
|
+
onError: function (error) {
|
|
1322
|
+
traceSdk.onFetchError(error);
|
|
1323
|
+
},
|
|
1324
|
+
onBefore: function (props) {
|
|
1325
|
+
traceSdk.saveBreadcrumb({
|
|
1326
|
+
name: 'fetch',
|
|
1327
|
+
level: TraceDataSeverity.Normal,
|
|
1328
|
+
type: BreadcrumbTypes.FETCH,
|
|
1329
|
+
category: BreadcrumbsCategorys.Http,
|
|
1330
|
+
message: props.url,
|
|
1331
|
+
time: getTimestamp(),
|
|
1332
|
+
request: {
|
|
1333
|
+
method: props.method,
|
|
1334
|
+
url: props.url,
|
|
1335
|
+
options: props.options
|
|
1336
|
+
}
|
|
1337
|
+
});
|
|
1338
|
+
},
|
|
1339
|
+
onAfter: function (result) {
|
|
1340
|
+
traceSdk.saveBreadcrumb({
|
|
1341
|
+
name: 'fetch',
|
|
1342
|
+
level: TraceDataSeverity.Normal,
|
|
1343
|
+
type: BreadcrumbTypes.FETCH,
|
|
1344
|
+
category: BreadcrumbsCategorys.Http,
|
|
1345
|
+
message: result.status,
|
|
1346
|
+
time: getTimestamp(),
|
|
1347
|
+
response: {
|
|
1348
|
+
status: result.status,
|
|
1349
|
+
statusText: result.statusText
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
}
|
|
1353
|
+
});
|
|
1354
|
+
// 监听页面性能
|
|
1355
|
+
onVitals(traceSdk.createPerfReport());
|
|
1356
|
+
setInterval(function () {
|
|
1357
|
+
console.log('[queue] traceSdk.queue: ', traceSdk.queue);
|
|
1358
|
+
var data = traceSdk.queue.shift();
|
|
1359
|
+
console.log('[queue] data: ', data);
|
|
1360
|
+
if (data)
|
|
1361
|
+
send(traceSdk.sendMethod, traceSdk.dsn, traceSdk.ltsConfig, data);
|
|
1362
|
+
}, traceSdk.sendTimer);
|
|
1363
|
+
// @ts-ignore
|
|
1364
|
+
window.traceSdk = traceSdk;
|
|
1365
|
+
return traceSdk;
|
|
1366
|
+
};
|
|
1367
|
+
return BaseTrace;
|
|
1368
|
+
}());
|
|
1369
|
+
|
|
1370
|
+
var TraceSdk = /** @class */ (function (_super) {
|
|
1371
|
+
__extends(TraceSdk, _super);
|
|
1372
|
+
function TraceSdk() {
|
|
1373
|
+
return _super !== null && _super.apply(this, arguments) || this;
|
|
1374
|
+
}
|
|
1375
|
+
return TraceSdk;
|
|
1376
|
+
}(BaseTrace));
|
|
1377
|
+
|
|
1378
|
+
var instance;
|
|
1379
|
+
var init = function (options) {
|
|
1380
|
+
if (instance) {
|
|
1381
|
+
return instance;
|
|
1382
|
+
}
|
|
1383
|
+
instance = TraceSdk.init(options);
|
|
1384
|
+
console.log('instance: ', instance);
|
|
1385
|
+
return instance;
|
|
1386
|
+
};
|
|
1387
|
+
// @ts-ignore
|
|
1388
|
+
window.traceSdkInit = init;
|
|
1389
|
+
|
|
1390
|
+
export { init, SendMethod };
|
|
1391
|
+
//# sourceMappingURL=trace-log.esm.js.map
|