avi-analytics-sdk
Version:
An analytics SDK for capturing user interactions
84 lines (83 loc) • 3.2 kB
JavaScript
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 { v4 as uuidv4 } from "uuid";
import { EVENTS_ENDPOINT } from "../config/constants";
import { capturePageLoad, handleClick, handleMouseMove, handlePageUnload, handleScroll, } from "../handlers/eventHandlers";
import { initializeObservability } from "./observability";
import { initializeRecording } from "./recording";
let sessionId;
let eventQueue = [];
let apiKey;
export function initializeAnalytics(options) {
if (!options.apiKey) {
console.error("API Key is required to initialize analytics.");
return;
}
apiKey = options.apiKey;
// Initialize session
sessionId = uuidv4();
initializeRecording({ apiKey, sessionId });
initializeObservability({ apiKey, sessionId });
// Attach event listeners
setupEventListeners();
// Periodically send events
setInterval(() => __awaiter(this, void 0, void 0, function* () {
yield sendEvents();
}), 5000);
// Capture initial page load
const pageLoadEvent = capturePageLoad();
eventQueue.push(pageLoadEvent);
sendEvents();
}
function setupEventListeners() {
document.addEventListener("click", (e) => {
eventQueue.push(handleClick(e));
});
document.addEventListener("scroll", () => {
eventQueue.push(handleScroll());
});
document.addEventListener("mousemove", (e) => {
handleMouseMove(e, (data) => eventQueue.push(data));
});
window.addEventListener("beforeunload", () => {
eventQueue.push(handlePageUnload());
});
}
function sendEvents() {
return __awaiter(this, void 0, void 0, function* () {
if (eventQueue.length === 0)
return;
const payload = {
api_key: apiKey,
session_id: sessionId,
events: [...eventQueue],
timestamp: new Date().toISOString(),
page_url: window.location.href,
viewport_width: window.innerWidth,
viewport_height: window.innerHeight,
};
const compressedPayload = pako.deflate(JSON.stringify(payload));
yield axios
.post(EVENTS_ENDPOINT, compressedPayload, {
headers: {
"Content-Encoding": "deflate",
"Content-Type": "application/octet-stream",
},
})
.then(() => {
eventQueue = [];
})
.catch((error) => {
console.error("Failed to send events:", error);
});
});
}