UNPKG

@grafana/faro-core

Version:
82 lines 3.32 kB
"use strict"; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BatchExecutor = void 0; var DEFAULT_SEND_TIMEOUT_MS = 250; var DEFAULT_BATCH_ITEM_LIMIT = 50; var BatchExecutor = /** @class */ (function () { function BatchExecutor(sendFn, options) { var _this = this; var _a, _b; this.signalBuffer = []; this.itemLimit = (_a = options === null || options === void 0 ? void 0 : options.itemLimit) !== null && _a !== void 0 ? _a : DEFAULT_BATCH_ITEM_LIMIT; this.sendTimeout = (_b = options === null || options === void 0 ? void 0 : options.sendTimeout) !== null && _b !== void 0 ? _b : DEFAULT_SEND_TIMEOUT_MS; this.paused = (options === null || options === void 0 ? void 0 : options.paused) || false; this.sendFn = sendFn; this.flushInterval = -1; if (!this.paused) { this.start(); } // Send batched/buffered data when user navigates to new page, switches or closes the tab, minimizes or closes the browser. // If on mobile, it also sends data if user switches from the browser to a different app. document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'hidden') { _this.flush(); } }); } BatchExecutor.prototype.addItem = function (item) { if (this.paused) { return; } this.signalBuffer.push(item); if (this.signalBuffer.length >= this.itemLimit) { this.flush(); } }; BatchExecutor.prototype.start = function () { var _this = this; this.paused = false; if (this.sendTimeout > 0) { this.flushInterval = window.setInterval(function () { return _this.flush(); }, this.sendTimeout); } }; BatchExecutor.prototype.pause = function () { this.paused = true; clearInterval(this.flushInterval); }; BatchExecutor.prototype.groupItems = function (items) { var itemMap = new Map(); items.forEach(function (item) { var metaKey = JSON.stringify(item.meta); var currentItems = itemMap.get(metaKey); if (currentItems === undefined) { currentItems = [item]; } else { currentItems = __spreadArray(__spreadArray([], currentItems, true), [item], false); } itemMap.set(metaKey, currentItems); }); return Array.from(itemMap.values()); }; BatchExecutor.prototype.flush = function () { if (this.paused || this.signalBuffer.length === 0) { return; } var itemGroups = this.groupItems(this.signalBuffer); itemGroups.forEach(this.sendFn); this.signalBuffer = []; }; return BatchExecutor; }()); exports.BatchExecutor = BatchExecutor; //# sourceMappingURL=batchExecutor.js.map