@grafana/faro-web-sdk
Version:
Faro instrumentations, metas, transports for web.
88 lines • 2.91 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.monitorHttpRequests = void 0;
var faro_core_1 = require("@grafana/faro-core");
var url_1 = require("../../utils/url");
var const_1 = require("./const");
/**
* Monitors if any http requests are in progress.
*/
function monitorHttpRequests() {
var observable = new faro_core_1.Observable();
var pendingXhrRequests = 0;
var pendingFetchRequests = 0;
function emitStartMessage() {
observable.notify({ type: const_1.MESSAGE_TYPE_HTTP_REQUEST_START, pending: pendingXhrRequests + pendingFetchRequests });
}
function emitEndMessage() {
observable.notify({ type: const_1.MESSAGE_TYPE_HTTP_REQUEST_END, pending: pendingXhrRequests + pendingFetchRequests });
}
monitorFetch(function () {
pendingFetchRequests++;
emitStartMessage();
}, function () {
pendingFetchRequests--;
emitEndMessage();
});
monitorXhr(function () {
pendingXhrRequests++;
emitStartMessage();
}, function () {
pendingXhrRequests--;
emitEndMessage();
});
return observable;
}
exports.monitorHttpRequests = monitorHttpRequests;
function monitorXhr(onRequestStart, onRequestEnd) {
var originalOpen = XMLHttpRequest.prototype.open;
var originalSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function () {
var url = arguments[1];
var isIgnoredUrl = (0, url_1.isUrlIgnored)(url);
this.addEventListener('loadstart', function () {
if (!isIgnoredUrl) {
onRequestStart();
}
});
this.addEventListener('loadend', function () {
if (!isIgnoredUrl) {
onRequestEnd();
}
});
originalOpen.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function () {
originalSend.apply(this, arguments);
};
}
function monitorFetch(onRequestsStart, onRequestEnd) {
var originalFetch = window.fetch;
window.fetch = function () {
var url = getUrlFromResource(arguments[0]);
var isIgnoredUrl = (0, url_1.isUrlIgnored)(url);
// fetch started
if (!isIgnoredUrl) {
onRequestsStart();
}
return originalFetch.apply(this, arguments).finally(function () {
// fetch ended
if (!isIgnoredUrl) {
onRequestEnd();
}
});
};
}
function getUrlFromResource(resource) {
if ((0, faro_core_1.isString)(resource)) {
return resource;
}
else if (resource instanceof URL) {
return resource.href;
}
else if ((0, faro_core_1.isFunction)(resource === null || resource === void 0 ? void 0 : resource.toString)) {
return resource.toString();
}
return undefined;
}
//# sourceMappingURL=httpRequestMonitor.js.map