UNPKG

@dotcms/analytics

Version:

Official JavaScript library for Content Analytics with DotCMS.

81 lines (80 loc) 2.83 kB
import m from "@analytics/queue-utils"; import v from "@analytics/router-utils"; import { DEFAULT_QUEUE_CONFIG as y } from "../constants/dot-analytics.constants.js"; import { sendAnalyticsEvent as b } from "../http/dot-analytics.http.js"; import { createPluginLogger as w } from "../utils/dot-analytics.utils.js"; const L = (o) => { const i = w("Queue", o); let e = null, n = null, u = !1, d = !1, f = typeof window < "u" ? window.location.pathname : ""; const a = { ...y, ...typeof o.queue == "object" ? o.queue : {} }, g = (t, s) => { if (!n) return; i.debug(`Sending batch of ${t.length} event(s)`, { events: t, keepalive: u }), b({ context: n, events: t }, o, u); }, l = () => { !e || e.size() === 0 || !n || (i.info(`Flushing ${e.size()} events (page hidden/unload)`), u = !0, e.flush(!0)); }, c = () => { if (i.debug("handleVisibilityChange", document.visibilityState), document.visibilityState === "hidden") { if (d) { i.debug("Skipping flush (SPA navigation detected)"); return; } l(); } else document.visibilityState === "visible" && (d = !1); }; return { /** * Initialize the queue with smart batching */ initialize: () => { e = m( (t, s) => { g(t); }, { max: a.eventBatchSize, interval: a.flushInterval, throttle: !1 // Always false - enables both batch size and interval triggers } ), typeof window < "u" && typeof document < "u" && (document.addEventListener("visibilitychange", c), window.addEventListener("pagehide", l), v((t) => { d = !0, f = t, i.debug(`SPA navigation detected (${f})`), setTimeout(() => { d = !1; }, 100); })); }, /** * Add event to queue * smartQueue handles all batching logic automatically: * - Sends immediately when eventBatchSize reached (with throttle: false) * - Sends pending events every flushInterval */ enqueue: (t, s) => { if (n = s, !e) return; const r = e.size() + 1, p = a.eventBatchSize, h = r >= p; i.debug( `Event added. Queue size: ${r}/${p}${h ? " (full, sending...)" : ""}`, { eventType: t.event_type, event: t } ), e.push(t); }, /** * Get queue size for debugging * Returns the number of events in smartQueue */ size: () => (e == null ? void 0 : e.size()) ?? 0, /** * Clean up queue resources * Flushes remaining events and cleans up listeners */ cleanup: () => { l(), typeof window < "u" && typeof document < "u" && (document.removeEventListener("visibilitychange", c), window.removeEventListener("pagehide", l)), e = null, n = null, u = !1; } }; }; export { L as createAnalyticsQueue };