Files
magistr/frontend/telemetry.js
2026-08-20 00:55:27 +03:00

41 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
let telemetryPromise = null;
const pendingUxEvents = [];
export function initializeTelemetry() {
if (['localhost', '127.0.0.1', '::1'].includes(window.location.hostname)) {
return Promise.resolve();
}
if (!telemetryPromise) {
telemetryPromise = import('/vendor/otel.js').then(() => flushPendingUxEvents()).catch(error => {
console.warn('Не удалось инициализировать браузерную телеметрию');
});
}
return telemetryPromise;
}
export function trackUxEvent(name, attributes = {}) {
const event = {
name: String(name || 'неизвестное_событие'),
attributes: sanitizeAttributes(attributes),
timestamp: new Date().toISOString()
};
document.dispatchEvent(new CustomEvent('magistr:ux-event', { detail: event }));
if (typeof window.__magistrTrackUx === 'function') {
window.__magistrTrackUx(event.name, event.attributes);
} else {
pendingUxEvents.push(event);
if (pendingUxEvents.length > 100) pendingUxEvents.shift();
}
}
export function flushPendingUxEvents() {
if (typeof window.__magistrTrackUx !== 'function') return;
pendingUxEvents.splice(0).forEach(event => window.__magistrTrackUx(event.name, event.attributes));
}
function sanitizeAttributes(attributes) {
return Object.fromEntries(Object.entries(attributes || {})
.filter(([, value]) => ['string', 'number', 'boolean'].includes(typeof value))
.map(([key, value]) => [String(key), value]));
}