fe-supervisor
Version:
The frontend monitor project
1,165 lines (1,158 loc) • 52.4 kB
JavaScript
/* fe-supervisor.js */
import {compatCheck,timeslice,getTs,isType,getUA,addListener,storage,uuid}from'peeler-js';/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
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;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}function notSupport() {
console.warn('Your browser not support the [Performance] API!');
return false;
}
function notSupportPromisify() {
console.warn('Your browser not support the [Performance] API!');
return Promise.resolve(false);
}var Observer = (function () {
function Observer(target, callback) {
this.cache = [];
this.observer = this.init(target, callback);
}
Observer.prototype.init = function (target, callback) {
if (!target) {
console.warn('Please pass a vaild HTMLElement');
return null;
}
var observer;
try {
observer = new MutationObserver(callback);
observer.observe(target, {
'childList': true,
'subtree': true,
'attributes': true,
'attributeFilter': ['src', 'href']
});
}
catch (error) {
return null;
}
return observer;
};
Observer.prototype.cancel = function () {
this.observer && this.observer.disconnect();
};
Observer.prototype.setCache = function (cache) {
this.cache.push(cache);
};
Observer.prototype.getCache = function () {
return this.cache;
};
Observer.prototype.clearCache = function () {
this.cache.splice(0);
};
return Observer;
}());var ExceptionTypes;
(function (ExceptionTypes) {
ExceptionTypes[ExceptionTypes["js"] = 0] = "js";
ExceptionTypes[ExceptionTypes["api"] = 1] = "api";
ExceptionTypes[ExceptionTypes["source"] = 2] = "source";
})(ExceptionTypes || (ExceptionTypes = {}));
var jsErrors = [];
var apiErrors = [];
var sourceErrors = [];
var errorTag = 'fe-supervisor-error';
function getErrors(type) {
var typeIndex = type ? ExceptionTypes[type] : undefined;
var errors;
switch (typeIndex) {
case ExceptionTypes['js']:
errors = jsErrors;
break;
case ExceptionTypes['api']:
errors = apiErrors;
break;
case ExceptionTypes['source']:
errors = sourceErrors;
break;
default:
errors = { jsErrors: jsErrors, apiErrors: apiErrors, sourceErrors: sourceErrors };
}
return errors;
}
var HandleException = {
getErrors: getErrors,
setErrors: function (error) {
var type = error.type;
var typeIndex = ExceptionTypes[type];
switch (typeIndex) {
case ExceptionTypes['js']:
var callstack = new Error().stack;
jsErrors.push(__assign(__assign({}, error), { code_site: callstack }));
break;
case ExceptionTypes['api']:
apiErrors.push(error);
break;
case ExceptionTypes['source']:
sourceErrors.push(error);
break;
}
},
clearError: function (type) {
var typeIndex = type ? ExceptionTypes[type] : undefined;
var res = true;
try {
switch (typeIndex) {
case ExceptionTypes['js']:
jsErrors.splice(0);
break;
case ExceptionTypes['api']:
apiErrors.splice(0);
break;
case ExceptionTypes['source']:
sourceErrors.splice(0);
break;
default:
jsErrors.splice(0);
apiErrors.splice(0);
sourceErrors.splice(0);
}
}
catch (err) {
res = false;
}
return res;
},
dupliError: function (type, msg) {
return __awaiter(this, void 0, Promise, function () {
function gen() {
var i, item;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
i = 0;
_a.label = 1;
case 1:
if (!(i < len)) return [3, 4];
item = errs[i];
if (item.msg && item.msg === msg) {
res = true;
return [2];
}
return [4];
case 2:
_a.sent();
_a.label = 3;
case 3:
i++;
return [3, 1];
case 4: return [2];
}
});
}
var res, errs, len, i, item;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
res = false;
errs = HandleException.getErrors(type);
len = (errs && errs.length) || 0;
if (!compatCheck('generator')) return [3, 2];
return [4, timeslice(gen)];
case 1:
_a.sent();
return [2, res];
case 2:
for (i = 0; i < len; i++) {
item = errs[i];
if (item.msg && item.msg === msg) {
res = true;
break;
}
}
return [2, res];
}
});
});
}
};function catchError(type, msg) {
return __awaiter(this, void 0, Promise, function () {
var isDuplication;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!type)
return [2];
return [4, HandleException.dupliError(type, msg)];
case 1:
isDuplication = _a.sent();
if (!isDuplication) {
HandleException.setErrors({
ts: getTs(),
type: type,
url: location.href,
msg: msg
});
}
return [2];
}
});
});
}var markCache = [];
var measureCache = [];
var marks = [];
var measures = [];
var getMemory = (function () {
if (typeof window === 'undefined' || !window.performance)
return notSupport;
return function () {
var limit, used, total, usedRatio;
try {
var p = window.performance;
var m = p.memory || {};
limit = m.jsHeapSizeLimit || 1;
used = m.usedJSHeapSize || 0;
total = m.totalJSHeapSize || 1;
usedRatio = +Number.prototype.toFixed.call(used / total, 3);
}
catch (error) {
var msg = "[SV - getMemory]: " + JSON.stringify(error, Object.getOwnPropertyNames(error));
catchError('js', msg);
}
finally {
return {
limit: limit,
memory: usedRatio || 'N/A',
used: usedRatio ? used : 'N/A',
total: usedRatio ? total : 'N/A'
};
}
};
})();
var getTiming = (function () {
if (typeof window === 'undefined' || !window.performance)
return notSupport;
return function () {
var wscreen, fscreen, network, network_prev, network_redirect, network_dns, network_tcp, network_request, network_response, network_interact, dom_loading, dom_interact, dom_ready, dom_load, dom_complete, js_ready, js_load, js_complete, render_ready, render_load, total;
wscreen = fscreen = network = network_prev = network_redirect = network_dns = network_tcp = network_request = network_response = network_interact = dom_loading = dom_interact = dom_ready = dom_load = dom_complete = js_ready = js_load = js_complete = render_ready = render_load = total = 'N/A';
try {
var p = window.performance;
var t = p.timing || {};
wscreen = timingFilter(t.domLoading - t.navigationStart);
fscreen = timingFilter(t.domContentLoadedEventStart - t.navigationStart);
network = timingFilter(t.responseEnd - t.navigationStart);
network_prev = timingFilter(t.fetchStart - t.navigationStart);
network_redirect = timingFilter(t.redirectEnd - t.redirectStart);
network_dns = timingFilter(t.domainLookupEnd - t.domainLookupStart);
network_tcp = timingFilter(t.connectEnd - t.connectStart);
network_request = timingFilter(t.responseStart - t.requestStart);
network_response = timingFilter(t.responseEnd - t.responseStart);
network_interact = timingFilter(t.responseEnd - t.requestStart);
dom_loading = timingFilter(t.domLoading - t.responseEnd);
dom_interact = timingFilter(t.domInteractive - t.domLoading);
dom_ready = timingFilter(t.domContentLoadedEventStart - t.domLoading);
dom_load = timingFilter(t.domComplete - t.domLoading);
dom_complete = timingFilter(t.domComplete - t.navigationStart);
js_ready = timingFilter(t.domContentLoadedEventStart - t.domInteractive);
js_load = timingFilter(t.domContentLoadedEventEnd - t.domInteractive);
js_complete = timingFilter(t.domContentLoadedEventEnd - t.navigationStart);
render_ready = timingFilter(t.domContentLoadedEventStart - t.domLoading);
render_load = timingFilter(t.loadEventEnd - t.domLoading);
total = timingFilter(t.loadEventEnd - t.navigationStart);
}
catch (error) {
var msg = "[SV - getTiming]: " + JSON.stringify(error, Object.getOwnPropertyNames(error));
catchError('js', msg);
}
finally {
return {
wscreen: wscreen,
fscreen: fscreen,
network: network,
network_prev: network_prev,
network_redirect: network_redirect,
network_dns: network_dns,
network_tcp: network_tcp,
network_request: network_request,
network_response: network_response,
network_interact: network_interact,
dom_loading: dom_loading,
dom_interact: dom_interact,
dom_ready: dom_ready,
dom_load: dom_load,
dom_complete: dom_complete,
js_ready: js_ready,
js_load: js_load,
js_complete: js_complete,
render_ready: render_ready,
render_load: render_load,
total: total
};
}
};
})();
var getSource = (function () {
if (typeof window === 'undefined' || !window.performance)
return notSupportPromisify;
return function (config) {
return __awaiter(this, void 0, Promise, function () {
function sortSource(item) {
var entryType = item.entryType || '';
var type = item.initiatorType || '';
var data = {
name: item.name,
duration: +Number.prototype.toFixed.call(item.duration, 2),
type: type
};
if (type === 'xmlhttprequest' || type === 'fetchrequest') {
if (w_a_1) {
if (isType('string')(w_a_1)) {
if (data.name === w_a_1)
return;
}
else if (isType('array')(w_a_1)) {
var w_a_len = (w_a_1 && w_a_1.length) || 0;
for (var j = 0; j < w_a_len; j++) {
if (data.name === w_a_1[j])
return;
}
}
}
randomRatio(apiRatio_1) && api_random.push(data);
data.duration >= threshold_1 && api_timeout.push(data);
if (isType('string')(apis_1)) {
data.name === apis_1 && api_appoint.push(data);
}
else if (isType('array')(apis_1)) {
apis_1.some(function (v) {
if (v === data.name) {
api_appoint.push(data);
return true;
}
return false;
});
}
}
else if (type === 'script' || type === 'css' || type === 'img' || type === 'link' || type === 'css') {
if (w_s_1) {
if (isType('string')(w_s_1)) {
if (data.name === w_s_1)
return;
}
else if (isType('array')(w_s_1)) {
var w_s_len = (w_s_1 && w_s_1.length) || 0;
for (var m = 0; m < w_s_len; m++) {
if (data.name === w_s_1[m])
return;
}
}
}
randomRatio(sourceRatio_1) && source_random.push(data);
data.duration >= threshold_1 && source_timeout.push(data);
if (isType('string')(sources_1)) {
type === sources_1 && source_appoint.push(data);
}
else if (isType('array')(sources_1)) {
sources_1.some(function (v) {
if (v === type) {
source_appoint.push(data);
return true;
}
return false;
});
}
else if (isType('object')(sources_1)) {
for (var k in sources_1) {
if (k === type) {
sources_1[k].some(function (v) {
if (v === data.name) {
source_appoint.push(data);
return true;
}
return false;
});
}
}
}
}
else {
if (paintTiming_1 && entryType === 'paint') {
var startTime = item.startTime;
var type_1 = '';
if (data.name === 'first-paint' || data.name === 'first-contentful-paint') {
switch (data.name) {
case 'first-paint':
type_1 = 'FP';
break;
case 'first-contentful-paint':
type_1 = 'FCP';
break;
}
others.push(__assign(__assign({}, data), { type: type_1,
startTime: startTime }));
}
}
}
}
function gen() {
var len, i;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
len = s_1.length;
i = 0;
_a.label = 1;
case 1:
if (!(i < len)) return [3, 4];
sortSource(s_1[i]);
return [4];
case 2:
_a.sent();
_a.label = 3;
case 3:
i++;
return [3, 1];
case 4: return [2];
}
});
}
var api_random, api_timeout, api_appoint, source_random, source_timeout, source_appoint, others, _a, _b, apiRatio_1, _c, sourceRatio_1, _d, apis_1, _e, sources_1, _f, timeout, _g, whitelist, _h, paintTiming_1, w_a_1, w_s_1, p, s_1, threshold_1, len, i, error_1, msg;
return __generator(this, function (_j) {
switch (_j.label) {
case 0:
api_random = [];
api_timeout = [];
api_appoint = [];
source_random = [];
source_timeout = [];
source_appoint = [];
others = [];
_j.label = 1;
case 1:
_j.trys.push([1, 5, 6, 7]);
_a = config || {}, _b = _a.apiRatio, apiRatio_1 = _b === void 0 ? 0.1 : _b, _c = _a.sourceRatio, sourceRatio_1 = _c === void 0 ? 0.1 : _c, _d = _a.apis, apis_1 = _d === void 0 ? '' : _d, _e = _a.sources, sources_1 = _e === void 0 ? '' : _e, _f = _a.timeout, timeout = _f === void 0 ? 2000 : _f, _g = _a.whitelist, whitelist = _g === void 0 ? {} : _g, _h = _a.paintTiming, paintTiming_1 = _h === void 0 ? false : _h;
w_a_1 = whitelist.api || '';
w_s_1 = whitelist.source || '';
p = window.performance;
s_1 = (p.getEntries && p.getEntries()) || [];
threshold_1 = timeout;
if (!compatCheck('generator')) return [3, 3];
return [4, timeslice(gen)];
case 2:
_j.sent();
return [3, 4];
case 3:
len = s_1.length;
for (i = 0; i < len; i++) {
sortSource(s_1[i]);
}
_j.label = 4;
case 4: return [3, 7];
case 5:
error_1 = _j.sent();
msg = "[SV - getSource]: " + JSON.stringify(error_1, Object.getOwnPropertyNames(error_1));
catchError('js', msg);
return [3, 7];
case 6: return [2, {
api_random: api_random,
api_timeout: api_timeout,
api_appoint: api_appoint,
source_random: source_random,
source_timeout: source_timeout,
source_appoint: source_appoint,
others: others
}];
case 7: return [2];
}
});
});
};
})();
var getExecTiming = (function () {
if (typeof window === 'undefined' || !window.performance)
return notSupportPromisify;
return function () {
return __awaiter(this, void 0, Promise, function () {
function sortExec(item) {
if (item.entryType === 'measure') {
exec.push({
name: item.name,
duration: +Number.prototype.toFixed.call(item.duration, 3)
});
}
}
function gen() {
var len, i;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
len = (measures_1 && measures_1.length) || 0;
for (i = 0; i < len; i++) {
sortExec(measures_1[i]);
}
return [4];
case 1:
_a.sent();
return [2];
}
});
}
var exec, p, measures_1, len, i, error_2, msg;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
exec = [];
_a.label = 1;
case 1:
_a.trys.push([1, 5, 6, 7]);
p = window.performance;
measures_1 = [];
if (p.mark && p.measure) {
measures_1 = (p.getEntriesByType && p.getEntriesByType('measure')) || (p.getEntries && p.getEntries()) || [];
}
else {
measures_1 = measureCache;
}
if (!compatCheck('generator')) return [3, 3];
return [4, timeslice(gen)];
case 2:
_a.sent();
return [3, 4];
case 3:
len = (measures_1 && measures_1.length) || 0;
for (i = 0; i < len; i++) {
sortExec(measures_1[i]);
}
_a.label = 4;
case 4: return [3, 7];
case 5:
error_2 = _a.sent();
msg = "[SV - getExecTiming]: " + JSON.stringify(error_2, Object.getOwnPropertyNames(error_2));
catchError('js', msg);
return [3, 7];
case 6: return [2, {
exec: exec
}];
case 7: return [2];
}
});
});
};
})();
var getPerformanceData = (function () {
if (typeof window === 'undefined' || !window.performance)
return notSupportPromisify;
return function (config) {
return __awaiter(this, void 0, Promise, function () {
var memory, timings, sources, execTiming, memo, error_3, msg;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 3, 4, 5]);
memo = getMemory();
memory = memo && memo.memory;
timings = getTiming() || {};
return [4, getSource(config).then(function (data) { return data; })];
case 1:
sources = _a.sent();
return [4, getExecTiming().then(function (data) { return data; })];
case 2:
execTiming = _a.sent();
return [3, 5];
case 3:
error_3 = _a.sent();
msg = "[SV - getPerformanceData]: " + JSON.stringify(error_3, Object.getOwnPropertyNames(error_3));
catchError('js', msg);
return [3, 5];
case 4: return [2, __assign(__assign(__assign({ memory: memory || 'N/A' }, timings), sources), execTiming)];
case 5: return [2];
}
});
});
};
})();
var mark = (function () {
if (typeof window === 'undefined' || !window.performance)
return notSupport;
return function (tag) {
var res = true;
try {
var p = window.performance;
var tagS = tag + "_start";
var tagE = tag + "_end";
if (!~marks.indexOf(tag)) {
if (p.mark) {
p.mark(tagS);
}
else {
compatibleMark(tagS);
}
marks.push(tag);
}
else if (!~measures.indexOf(tag)) {
if (p.mark && p.measure) {
p.mark(tagE);
p.measure("" + tag, tagS, tagE);
}
else {
compatibleMark(tagE);
compatibleMeasure("" + tag, tagS, tagE);
}
measures.push(tag);
}
else {
res = false;
console.warn("Cannot repeat tag the mark: " + tag);
}
}
catch (error) {
res = false;
var msg = "[SV - mark]: " + JSON.stringify(error, Object.getOwnPropertyNames(error));
catchError('js', msg);
}
finally {
return res;
}
};
})();
var clearPerformance = (function () {
if (typeof window === 'undefined' || !window.performance)
return notSupport;
return function (clearType) {
try {
var isClearSource = !clearType || clearType === 'source' || clearType === 'all';
var isClearMark = !clearType || clearType === 'mark' || clearType === 'all';
var isClearMeasure = !clearType || clearType === 'measure' || clearType === 'all';
var p = window.performance;
if (isClearMark) {
p.clearMarks && p.clearMarks();
marks.splice(0);
markCache.splice(0);
}
if (isClearMeasure) {
p.clearMeasures && p.clearMeasures();
measures.splice(0);
measureCache.splice(0);
}
isClearSource && p.clearResourceTimings && p.clearResourceTimings();
return true;
}
catch (error) {
var msg = "[SV - clearPerformance]: " + JSON.stringify(error, Object.getOwnPropertyNames(error));
catchError('js', msg);
return false;
}
};
})();
var observeSource = (function () {
if (typeof window === 'undefined' || !window.performance)
return notSupport;
return function (target, callback, option) {
var _a = option || {}, _b = _a.sourceType, sourceType = _b === void 0 ? 'img' : _b, _c = _a.timeout, timeout = _c === void 0 ? 2000 : _c, _d = _a.whitelist, whitelist = _d === void 0 ? {} : _d;
sourceType = isType('string')(sourceType) ? [sourceType.toLowerCase()] : __spreadArrays(sourceType.map(function (type) { return type.toLowerCase(); }));
getSourceByDom(target);
var observer = new Observer(target, function (mutationRecords) {
return __awaiter(this, void 0, void 0, function () {
function timerQuery() {
setTimeout(function () {
return __awaiter(this, void 0, void 0, function () {
var sourceData, addrLen, k;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, getSource({
apiRatio: 0,
sourceRatio: 0,
sources: sourceAddr,
whitelist: whitelist
}).then(function (data) { return data.source_appoint; })];
case 1:
sourceData = _a.sent();
addrLen = 0;
for (k in sourceAddr) {
addrLen += sourceAddr[k].length;
}
if ((sourceData && sourceData.length === addrLen) || spendTime >= timeout) {
return [2, callback && callback(sourceData)];
}
else {
spendTime += frequence;
timerQuery();
}
return [2];
}
});
});
}, frequence);
}
var spendTime, frequence, len, sourceAddr, i, item, recordType, _a, addNodes, attrName, target_1, type;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
spendTime = 0;
frequence = 200;
len = (mutationRecords && mutationRecords.length) || 0;
sourceAddr = {};
i = 0;
_b.label = 1;
case 1:
if (!(i < len)) return [3, 6];
item = mutationRecords[i];
recordType = item.type;
_a = recordType;
switch (_a) {
case 'childList': return [3, 2];
case 'attributes': return [3, 4];
}
return [3, 5];
case 2:
addNodes = item.addedNodes;
return [4, timeslice(iterationDOM(addNodes, sourceAddr))];
case 3:
_b.sent();
return [3, 5];
case 4:
attrName = item.attributeName;
target_1 = item.target;
type = target_1.tagName && target_1.tagName.toLowerCase() || 'img';
if (attrName) {
!sourceAddr[type] && (sourceAddr[type] = []);
sourceAddr[type].push(target_1[attrName]);
}
return [3, 5];
case 5:
i++;
return [3, 1];
case 6:
timerQuery();
return [2];
}
});
});
});
function getSourceByDom(dom, isAsync) {
return __awaiter(this, void 0, void 0, function () {
var data, type, sourceAddr, sourceSrc, doms, error_4, msg;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
data = [];
_a.label = 1;
case 1:
_a.trys.push([1, 5, 6, 7]);
type = dom.nodeName.toLowerCase();
sourceAddr = {};
if (~sourceType.indexOf(type)) {
sourceSrc = dom.src || dom.href || '';
!sourceAddr[type] && (sourceAddr[type] = []);
sourceSrc && sourceAddr[type].push(sourceSrc);
}
doms = dom.children;
if (!(doms && doms.length > 0)) return [3, 3];
return [4, timeslice(iterationDOM(doms, sourceAddr))];
case 2:
_a.sent();
_a.label = 3;
case 3: return [4, getSource({
apiRatio: 0,
sourceRatio: 0,
sources: sourceAddr,
whitelist: whitelist
}).then(function (data) { return data.source_appoint; })];
case 4:
data = _a.sent();
!isAsync && callback && callback(data);
return [3, 7];
case 5:
error_4 = _a.sent();
msg = "[SV - observeSource_getSourceByDom]: " + JSON.stringify(error_4, Object.getOwnPropertyNames(error_4));
catchError('js', msg);
return [3, 7];
case 6: return [2, data];
case 7: return [2];
}
});
});
}
function iterationDOM(doms, sourceAddr) {
function sortDOM(doms, sourceStore) {
var len = (doms && doms.length) || 0;
for (var i = 0; i < len; i++) {
var dom = doms[i];
var type = dom.nodeName.toLowerCase();
if (~sourceType.indexOf(type)) {
var sourceSrc = dom.src || dom.href || '';
!sourceStore[type] && (sourceStore[type] = []);
sourceSrc && sourceStore[type].push(sourceSrc);
}
var children = dom.children;
var childLen = (children && children.length) || 0;
if (childLen > 0) {
sortDOM(children, sourceStore);
}
}
}
if (compatCheck('generator')) {
return function () {
var len, i, dom, type, sourceSrc, children, childLen, error_5, msg;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 7, , 8]);
len = (doms && doms.length) || 0;
i = 0;
_a.label = 1;
case 1:
if (!(i < len)) return [3, 6];
dom = doms[i];
type = dom.nodeName.toLowerCase();
if (~sourceType.indexOf(type)) {
sourceSrc = dom.src || dom.href || '';
!sourceAddr[type] && (sourceAddr[type] = []);
sourceSrc && sourceAddr[type].push(sourceSrc);
}
children = dom.children;
childLen = (children && children.length) || 0;
if (!(childLen > 0)) return [3, 3];
return [4, timeslice(iterationDOM(children, sourceAddr))];
case 2:
_a.sent();
_a.label = 3;
case 3: return [4];
case 4:
_a.sent();
_a.label = 5;
case 5:
i++;
return [3, 1];
case 6: return [3, 8];
case 7:
error_5 = _a.sent();
msg = "[SV - observeSource_iterationDOM]: " + JSON.stringify(error_5, Object.getOwnPropertyNames(error_5));
catchError('js', msg);
return [3, 8];
case 8: return [2];
}
});
};
}
else {
sortDOM(doms, sourceAddr);
}
}
return observer;
};
})();
function compatibleMark(tag) {
var ts = +((window.performance.now && ('' + window.performance.now())) || getTs());
markCache.push({ tag: tag, ts: ts });
}
function compatibleMeasure(tag, tagStart, tagEnd) {
var len = (markCache && markCache.length) || 0;
var startTime = 0;
var endTime = 0;
for (var i = 0; i < len; i++) {
var item = markCache[i];
if (item.tag === tagStart)
startTime = item.ts;
if (item.tag === tagEnd)
endTime = item.ts;
}
measureCache.push({ entryType: 'measure', name: tag, duration: Math.abs(endTime - startTime) });
}
function timingFilter(timing) {
if (timing === null || timing === undefined || isNaN(timing))
return 'N/A';
return timing > 0 ? timing : 0;
}
function randomRatio(ratio) {
if (ratio === 0)
return false;
if (Math.random() <= ratio)
return true;
return false;
}
var SV = (function () {
function SV(config) {
this.config = config;
}
SV.prototype.updateConfig = function (newConfig) {
this.config = __assign(__assign({}, this.config), newConfig);
};
SV.prototype.getMemory = function () {
return getMemory();
};
SV.prototype.getTiming = function () {
return getTiming();
};
SV.prototype.getSource = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, getSource(this.config)];
case 1: return [2, _a.sent()];
}
});
});
};
SV.prototype.getExecTiming = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, getExecTiming()];
case 1: return [2, _a.sent()];
}
});
});
};
SV.prototype.getPerformanceData = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2, getPerformanceData(this.config)];
});
});
};
SV.prototype.clearPerformance = function (clearType) {
return clearPerformance(clearType);
};
SV.prototype.observeSource = function (target, callback, option) {
if (this.config && this.config.timeout) {
option = __assign({ timeout: this.config.timeout }, option);
}
return observeSource(target, callback, option);
};
return SV;
}());var getEnvInfo = (function () {
if (typeof window === 'undefined')
return function () {
console.warn('Please call in browser environment');
return false;
};
return function () {
var ua = navigator.userAgent;
var scr = window.screen;
var page_url = location.href;
var referer = document.referrer;
var info = {
ts: getTs(),
os: '',
browser: '',
screen_size: (scr.width || 0) + 'x' + (scr.height || 0),
page_url: page_url,
referer: referer,
device: ('ontouchstart' in window ? 'mobile' : 'pc'),
ua: ua
};
var _a = getUA(ua), isMobile = _a.isMobile, isAndroid = _a.isAndroid, isIOS = _a.isIOS, isWindows = _a.isWindows, isMac = _a.isMac, isWeixin = _a.isWeixin, isSinaWeibo = _a.isSinaWeibo, isQQWeibo = _a.isQQWeibo, isFacebook = _a.isFacebook, isTwitter = _a.isTwitter, isInstagram = _a.isInstagram, isChrome = _a.isChrome, isFirefox = _a.isFirefox, isGecko = _a.isGecko, isIE = _a.isIE, isEdge = _a.isEdge, isOpera = _a.isOpera, isSafari = _a.isSafari, is360se = _a.is360se, isQQ = _a.isQQ, isUCBrowser = _a.isUCBrowser, isBaiduBrowser = _a.isBaiduBrowser, isSougouBrowser = _a.isSougouBrowser, isLiebaoBrowser = _a.isLiebaoBrowser, isWebKit = _a.isWebKit;
if (isMobile) {
if (isAndroid) {
info.os = 'android';
}
else if (isIOS) {
info.os = 'ios';
}
}
else {
if (isWindows) {
info.os = 'windows';
}
else if (isMac) {
info.os = 'mac';
}
}
if (isWeixin) {
info.browser = 'weixin';
}
else if (isSinaWeibo) {
info.browser = 'weibo_sina';
}
else if (isQQWeibo) {
info.browser = 'weibo_qq';
}
else if (isFacebook) {
info.browser = 'facebook';
}
else if (isTwitter) {
info.browser = 'twitter';
}
else if (isInstagram) {
info.browser = 'instagram';
}
else if (isChrome) {
info.browser = 'chrome';
}
else if (isFirefox || isGecko) {
info.browser = 'firefox';
}
else if (isIE) {
info.browser = 'ie';
}
else if (isEdge) {
info.browser = 'edge';
}
else if (isOpera) {
info.browser = 'opera';
}
else if (isSafari) {
info.browser = 'safari';
}
else if (is360se) {
info.browser = '360';
}
else if (isQQ) {
info.browser = 'qq';
}
else if (isUCBrowser) {
info.browser = 'uc';
}
else if (isBaiduBrowser) {
info.browser = 'baidu';
}
else if (isSougouBrowser) {
info.browser = 'sougou';
}
else if (isLiebaoBrowser) {
info.browser = 'liebao';
}
else if (isWebKit) {
info.browser = 'webkit';
}
return info;
};
})();(function () {
if (typeof window === 'undefined')
return;
addListener('error', function (e) {
var filename = e.filename, message = e.message, error = e.error;
HandleException.setErrors({
ts: getTs(),
type: 'js',
url: filename || '',
msg: message,
error: error
});
}, window, { passive: true });
addListener('DOMContentLoaded', function () {
var imgs = transArray(document.getElementsByTagName('img'));
var links = transArray(document.getElementsByTagName('link'));
var scripts = transArray(document.getElementsByTagName('script'));
var len_img = (imgs && imgs.length) || 0;
var len_link = (links && links.length) || 0;
var len_script = (scripts && scripts.length) || 0;
var max_len = Math.max(len_img, len_link, len_script);
for (var i = 0; i < max_len; i++) {
imgs[i] && handleError(imgs[i], 'img');
links[i] && handleError(links[i], 'link');
scripts[i] && handleError(scripts[i], 'script');
}
}, window);
})();
function getError(type) {
return type ? HandleException.getErrors(type) : HandleException.getErrors();
}
function setError(err) {
HandleException.setErrors(err);
}
function clearError(type) {
return HandleException.clearError(type);
}
function observeError(target, callback, observeDom) {
var observer = new Observer(target, function (doms) {
var observeList = (observeDom && typeof observeDom === 'string' ? [observeDom] : observeDom) || ['img'];
handleError(doms);
function handleError(doms) {
try {
var len_doms = (doms && doms.length) || 0;
for (var i = 0; i < len_doms; i++) {
var addedNodes = doms[i].addedNodes;
if (addedNodes) {
var len_added = addedNodes.length || 0;
for (var k = 0; k < len_added; k++) {
bindError(addedNodes[k]);
}
}
else {
bindError(doms[i]);
}
}
}
catch (error) {
var msg = "[SV - observeError_handleError]: " + JSON.stringify(error, Object.getOwnPropertyNames(error));
catchError('js', msg);
}
function bindError(dom) {
try {
var nodeName = dom.nodeName;
var sourceType_1 = nodeName.toLowerCase();
bind: if (~observeList.indexOf(sourceType_1)) {
if (dom.getAttribute) {
if (dom.getAttribute(errorTag))
break bind;
dom.setAttribute(errorTag, 'true');
}
addListener('error', function (e) {
var target = e.target;
var url = target && (target.href || target.src) || location.href;
var errObj = {
ts: getTs(),
type: 'source',
sourceType: sourceType_1,
url: url,
msg: JSON.stringify(e, Object.getOwnPropertyNames(e))
};
HandleException.setErrors(errObj);
callback && callback(dom, e);