UNPKG

avi-analytics-sdk

Version:

An analytics SDK for capturing user interactions

90 lines (89 loc) 3.38 kB
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()); }); }; import axios from "axios"; import * as pako from "pako"; import { record } from "rrweb"; import { RECORDING_ENDPOINT } from "../config/constants"; let rrwebEventQueue = []; let recordingApiKey; let stopRecording = null; export function initializeRecording({ apiKey, sessionId, }) { if (!apiKey) { console.error("API Key is required to initialize recording."); return; } recordingApiKey = apiKey; // Start rrweb recording stopRecording = record({ emit(event) { rrwebEventQueue.push(event); }, }); // Periodically send rrweb events setInterval(() => __awaiter(this, void 0, void 0, function* () { yield sendRrwebEvents(sessionId); }), 5000); } function sendRrwebEvents(sessionId) { return __awaiter(this, void 0, void 0, function* () { if (rrwebEventQueue.length === 0) return; // Convert rrweb events to payload format const processedEvents = rrwebEventQueue.map((ev) => { // Map rrweb event.type to your defined event_type enum // For simplicity: // 1 = DomSnapshot (full snapshot) // 2 = Mutation (changes in DOM) // 3 = Interaction (mouse, input, etc.) let eventType = "mutation"; if (ev.type === 2) { eventType = "dom_snapshot"; } else if (ev.type === 3 || ev.type === 4) { eventType = "mutation"; } else if (ev.type === 5) { eventType = "interaction"; } return { event_type: eventType, rrweb_data: JSON.stringify(ev), timestamp: new Date(ev.timestamp).toISOString(), }; }); const payload = { api_key: recordingApiKey, session_id: sessionId, rrwebEvents: processedEvents, timestamp: new Date().toISOString(), page_url: window.location.href, viewport_width: window.innerWidth, viewport_height: window.innerHeight, }; const compressedPayload = pako.deflate(JSON.stringify(payload)); try { yield axios.post(RECORDING_ENDPOINT, compressedPayload, { headers: { "Content-Encoding": "deflate", "Content-Type": "application/octet-stream", }, }); rrwebEventQueue = []; } catch (error) { console.error("Failed to send rrweb events:", error); } }); } export function stopRrwebRecording() { if (stopRecording) { stopRecording(); } }