@bugster/bugster-js
Version:
An SDK to capture user interactions on web applications
531 lines (530 loc) • 24.1 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(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);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (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 (g && (g = 0, op[0] && (_ = 0)), _) 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 };
}
};
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 });
var uuid_1 = require("uuid");
var BugsterTracker = /** @class */ (function () {
function BugsterTracker(config) {
this.isCapturingEnabled = false;
this.config = __assign({ endpoint: 'https://i.bugster.app', batchSize: 10, flushInterval: 5 * 60 * 1000, sessionTimeout: 30 * 60 * 1000, persistence: 'localStorage', capturePageview: true, capturePageleave: true, captureUtm: true, captureReferrer: true, inputDebounceTime: 500 }, config);
this.persistence = new Persistence(this.config);
this.distinctId = this.persistence.getDistinctId() || this.generateId();
this.sessionId = this.persistence.getSessionId() || this.generateId();
this.queue = [];
this.lastActivityTimestamp = Date.now();
this.inputDebounceTimers = new Map();
this.lastSessionUpdate = Date.now();
this.initialize();
}
BugsterTracker.prototype.initialize = function () {
return __awaiter(this, void 0, void 0, function () {
var error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.checkRemoteConfig()];
case 1:
_a.sent();
if (this.isCapturingEnabled) {
this.setupEventListeners();
this.startBatchingLoop();
if (this.config.capturePageview) {
this.capturePageview();
}
}
return [3 /*break*/, 3];
case 2:
error_1 = _a.sent();
console.error('Failed to initialize BugsterTracker:', error_1);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
});
};
BugsterTracker.prototype.checkRemoteConfig = function () {
return __awaiter(this, void 0, void 0, function () {
var response, responseBody, config, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
console.log('[Bugster-js] Checking remote config...');
_a.label = 1;
case 1:
_a.trys.push([1, 6, , 7]);
return [4 /*yield*/, fetch("".concat(this.config.endpoint, "/remote-config"), {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': this.config.apiKey
}
})];
case 2:
response = _a.sent();
if (!response.ok) return [3 /*break*/, 4];
return [4 /*yield*/, response.json()];
case 3:
responseBody = _a.sent();
config = JSON.parse(responseBody.body);
this.isCapturingEnabled = config.isCapturingEnabled;
console.log("[Bugster-js] Event capturing is ".concat(this.isCapturingEnabled ? 'enabled' : 'disabled'));
return [3 /*break*/, 5];
case 4:
if (response.status === 403) {
this.isCapturingEnabled = false;
console.log('[Bugster-js] Event capturing is disabled. Activate event capture in your Settings');
}
else {
throw new Error("Failed to fetch remote config: ".concat(response.statusText));
}
_a.label = 5;
case 5: return [3 /*break*/, 7];
case 6:
error_2 = _a.sent();
console.error('[Bugster-js] Error fetching remote config:', error_2);
// Defaulting to disabled state if there's an error
this.isCapturingEnabled = false;
return [3 /*break*/, 7];
case 7: return [2 /*return*/];
}
});
});
};
BugsterTracker.prototype.generateId = function () {
return (0, uuid_1.v4)();
};
BugsterTracker.prototype.identify = function (distinctId, properties) {
if (properties === void 0) { properties = {}; }
var previousDistinctId = this.distinctId;
this.distinctId = distinctId;
this.persistence.setDistinctId(distinctId);
this.capture('$identify', __assign({ distinct_id: distinctId, $anon_distinct_id: previousDistinctId }, properties));
};
BugsterTracker.prototype.capture = function (eventName, properties, skipSessionCheck) {
if (properties === void 0) { properties = {}; }
if (skipSessionCheck === void 0) { skipSessionCheck = false; }
if (!this.isCapturingEnabled)
return;
if (!skipSessionCheck) {
this.checkAndUpdateSession();
}
var event = {
event: eventName,
properties: __assign(__assign({ distinct_id: this.distinctId, session_id: this.sessionId }, this.getDefaultProperties()), properties),
timestamp: new Date().toISOString()
};
this.queue.push(event);
if (this.config.batchSize && this.queue.length >= this.config.batchSize) {
this.flush();
}
this.lastActivityTimestamp = Date.now();
};
BugsterTracker.prototype.getDefaultProperties = function () {
return __assign({ $current_url: window.location.href, $host: window.location.host, $pathname: window.location.pathname, $browser: this.getBrowserInfo(), $device: this.getDeviceInfo(), $referrer: document.referrer, $referring_domain: document.referrer ? new URL(document.referrer).hostname : '', $screen_height: window.screen.height, $screen_width: window.screen.width }, this.getUtmParams());
};
BugsterTracker.prototype.getBrowserInfo = function () {
var ua = navigator.userAgent;
var browserName = "Unknown";
if (ua.indexOf("Firefox") > -1) {
browserName = "Firefox";
}
else if (ua.indexOf("Opera") > -1 || ua.indexOf("OPR") > -1) {
browserName = "Opera";
}
else if (ua.indexOf("Trident") > -1) {
browserName = "Internet Explorer";
}
else if (ua.indexOf("Edge") > -1) {
browserName = "Microsoft Edge";
}
else if (ua.indexOf("Chrome") > -1) {
browserName = "Chrome";
}
else if (ua.indexOf("Safari") > -1) {
browserName = "Safari";
}
return browserName;
};
BugsterTracker.prototype.getDeviceInfo = function () {
var ua = navigator.userAgent;
if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
return "Tablet";
}
if (/Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
return "Mobile";
}
return "Desktop";
};
BugsterTracker.prototype.getUtmParams = function () {
if (!this.config.captureUtm)
return {};
var utmParams = {};
var params = new URLSearchParams(window.location.search);
['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'].forEach(function (param) {
var value = params.get(param);
if (value)
utmParams[param] = value;
});
return utmParams;
};
BugsterTracker.prototype.setupEventListeners = function () {
var _this = this;
if (!this.isCapturingEnabled)
return;
var processedElements = new Map();
var handleOnce = function (event, handler, eventType, priority) {
var target = event.target;
var lastEvent = processedElements.get(target);
if (lastEvent && lastEvent === eventType)
return;
if (!lastEvent || getEventPriority(lastEvent) < priority) {
processedElements.set(target, eventType);
handler(event);
}
setTimeout(function () {
processedElements.delete(target);
}, 500);
};
var getEventPriority = function (eventType) {
switch (eventType) {
case 'submit': return 3;
case 'click': return 2;
case 'blur': return 1;
case 'change': return 1;
default: return 0;
}
};
document.addEventListener('click', function (e) { return handleOnce(e, _this.handleEvent.bind(_this), 'click', getEventPriority('click')); }, true);
document.addEventListener('change', function (e) { return handleOnce(e, _this.handleEvent.bind(_this), 'change', getEventPriority('change')); }, true);
document.addEventListener('blur', function (e) { return handleOnce(e, _this.handleBlurEvent.bind(_this), 'blur', getEventPriority('blur')); }, true);
document.addEventListener('submit', function (e) { return handleOnce(e, _this.handleEvent.bind(_this), 'submit', getEventPriority('submit')); }, true);
if (this.config.capturePageleave) {
window.addEventListener('beforeunload', this.handlePageLeave.bind(this));
}
};
BugsterTracker.prototype.handleBlurEvent = function (event) {
if (!this.isCapturingEnabled)
return;
var target = event.target;
if (target.tagName.toLowerCase() === 'input' || target.tagName.toLowerCase() === 'textarea') {
var value = this.sanitizeInputValue(target);
this.capture('$input_blur', {
value: value,
isChecked: target.type === 'checkbox' || target.type === 'radio' ? target.checked : undefined,
});
}
};
BugsterTracker.prototype.handleEvent = function (event) {
if (!this.isCapturingEnabled)
return;
var target = event.target;
if (target.tagName.toLowerCase() === 'body' || target.tagName.toLowerCase() === 'html') {
return;
}
var elementData = this.getElementData(target);
var eventData = __assign(__assign({ eventType: event.type }, this.truncateElementData(elementData)), { timestamp: new Date().toISOString() });
if (event instanceof MouseEvent) {
Object.assign(eventData, {
x: event.clientX,
y: event.clientY,
mouseButton: event.button,
ctrlKey: event.ctrlKey,
shiftKey: event.shiftKey,
altKey: event.altKey,
metaKey: event.metaKey,
});
}
if (event.type === 'input' || event.type === 'change') {
var inputElement = event.target;
Object.assign(eventData, {
value: this.sanitizeInputValue(inputElement),
isChecked: inputElement.type === 'checkbox' || inputElement.type === 'radio' ? inputElement.checked : undefined,
});
}
if (event.type === 'submit' && event.target instanceof HTMLFormElement) {
Object.assign(eventData, {
formAction: event.target.action,
formMethod: event.target.method,
});
}
this.capture("$".concat(event.type), eventData);
};
BugsterTracker.prototype.truncateElementData = function (data) {
return {
elementType: data.elementType,
elementText: this.truncateString(data.elementText, 100),
elementAttributes: this.truncateAttributes(data.elementAttributes),
};
};
BugsterTracker.prototype.truncateAttributes = function (attributes) {
var truncated = {};
for (var _i = 0, _a = Object.entries(attributes); _i < _a.length; _i++) {
var _b = _a[_i], key = _b[0], value = _b[1];
truncated[key] = this.truncateString(value, 200);
}
return truncated;
};
BugsterTracker.prototype.truncateString = function (str, maxLength) {
if (str.length <= maxLength)
return str;
return str.slice(0, maxLength) + '...';
};
BugsterTracker.prototype.sanitizeInputValue = function (input) {
if (input.type === 'password')
return '*****';
return this.truncateString(input.value, 100);
};
BugsterTracker.prototype.getElementData = function (element) {
return {
elementType: element.tagName.toLowerCase(),
elementText: element.textContent || '',
elementAttributes: this.getElementAttributes(element),
};
};
BugsterTracker.prototype.getElementAttributes = function (element) {
var attrs = {};
for (var _i = 0, _a = Array.from(element.attributes); _i < _a.length; _i++) {
var attr = _a[_i];
attrs[attr.name] = attr.value;
}
return attrs;
};
BugsterTracker.prototype.handlePageLeave = function () {
if (!this.isCapturingEnabled)
return;
this.capture('$pageleave', {
$time_on_page: Date.now() - this.lastActivityTimestamp
});
this.flush();
};
BugsterTracker.prototype.capturePageview = function () {
if (!this.isCapturingEnabled)
return;
this.capture('$pageview');
};
BugsterTracker.prototype.checkAndUpdateSession = function () {
var currentTime = Date.now();
if (currentTime - this.lastSessionUpdate > this.config.sessionTimeout) {
this.sessionId = this.generateId();
this.lastSessionUpdate = currentTime;
this.capture('$session_start', {
sessionId: this.sessionId
}, true);
}
};
BugsterTracker.prototype.startBatchingLoop = function () {
var _this = this;
if (!this.isCapturingEnabled)
return;
setInterval(function () { return _this.flush(); }, this.config.flushInterval);
};
BugsterTracker.prototype.flush = function () {
return __awaiter(this, void 0, void 0, function () {
var eventsToSend, response, error_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.isCapturingEnabled || this.queue.length === 0)
return [2 /*return*/];
eventsToSend = __spreadArray([], this.queue, true);
this.queue = [];
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, fetch("".concat(this.config.endpoint, "/event"), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': this.config.apiKey
},
body: JSON.stringify({ events: eventsToSend })
})];
case 2:
response = _a.sent();
console.log('[Bugster-js] Events send successfully');
if (!response.ok) {
throw new Error("HTTP error! status: ".concat(response.status));
}
return [3 /*break*/, 4];
case 3:
error_3 = _a.sent();
console.error('Failed to send events:', error_3);
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
});
};
return BugsterTracker;
}());
var Persistence = /** @class */ (function () {
function Persistence(config) {
this.config = config;
this.storage = this.getStorageMechanism();
}
Persistence.prototype.getStorageMechanism = function () {
switch (this.config.persistence) {
case 'localStorage':
return window.localStorage;
case 'cookie':
return new CookieStorage(this.config);
case 'memory':
default:
return new MemoryStorage();
}
};
Persistence.prototype.getDistinctId = function () {
var _a, _b;
return (_b = (_a = this.storage) === null || _a === void 0 ? void 0 : _a.getItem('bugster_distinct_id')) !== null && _b !== void 0 ? _b : null;
};
Persistence.prototype.setDistinctId = function (id) {
var _a;
(_a = this.storage) === null || _a === void 0 ? void 0 : _a.setItem('bugster_distinct_id', id);
};
Persistence.prototype.getSessionId = function () {
var _a, _b;
return (_b = (_a = this.storage) === null || _a === void 0 ? void 0 : _a.getItem('bugster_session_id')) !== null && _b !== void 0 ? _b : null;
};
Persistence.prototype.setSessionId = function (id) {
var _a;
(_a = this.storage) === null || _a === void 0 ? void 0 : _a.setItem('bugster_session_id', id);
};
return Persistence;
}());
var MemoryStorage = /** @class */ (function () {
function MemoryStorage() {
this.data = {};
}
MemoryStorage.prototype.getItem = function (key) {
return this.data[key] || null;
};
MemoryStorage.prototype.setItem = function (key, value) {
this.data[key] = value;
};
Object.defineProperty(MemoryStorage.prototype, "length", {
get: function () {
return Object.keys(this.data).length;
},
enumerable: false,
configurable: true
});
MemoryStorage.prototype.clear = function () {
this.data = {};
};
MemoryStorage.prototype.key = function (index) {
return Object.keys(this.data)[index] || null;
};
MemoryStorage.prototype.removeItem = function (key) {
delete this.data[key];
};
return MemoryStorage;
}());
var CookieStorage = /** @class */ (function () {
function CookieStorage(config) {
this.config = config;
}
CookieStorage.prototype.getItem = function (key) {
var name = key + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return null;
};
CookieStorage.prototype.setItem = function (key, value) {
var cookieString = "".concat(key, "=").concat(value);
if (this.config.cookieDomain) {
cookieString += "; domain=".concat(this.config.cookieDomain);
}
if (this.config.crossSubdomainCookie) {
cookieString += "; SameSite=None";
}
if (this.config.secureCookie) {
cookieString += "; Secure";
}
document.cookie = cookieString;
};
Object.defineProperty(CookieStorage.prototype, "length", {
get: function () {
return document.cookie.split(';').filter(function (c) { return c.trim(); }).length;
},
enumerable: false,
configurable: true
});
CookieStorage.prototype.clear = function () {
document.cookie.split(';').forEach(function (c) {
document.cookie = c.replace(/^ +/, '').replace(/=.*/, "=;expires=".concat(new Date().toUTCString(), ";path=/"));
});
};
CookieStorage.prototype.key = function (index) {
var _a, _b;
return (_b = (_a = document.cookie.split(';').filter(function (c) { return c.trim(); })[index]) === null || _a === void 0 ? void 0 : _a.split('=')[0]) !== null && _b !== void 0 ? _b : null;
};
CookieStorage.prototype.removeItem = function (key) {
document.cookie = "".concat(key, "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;");
};
return CookieStorage;
}());
exports.default = BugsterTracker;