@dotcms/analytics
Version:
Official JavaScript library for Content Analytics with DotCMS.
80 lines (79 loc) • 2.37 kB
JavaScript
import { EVENT_TYPES as y } from "../shared/dot-content-analytics.constants.js";
import { sendAnalyticsEventToServer as c } from "../shared/dot-content-analytics.http.js";
const p = (v) => {
let r = !1;
return {
name: "dot-analytics",
config: v,
/**
* Initialize the plugin
*/
initialize: () => (r = !0, Promise.resolve()),
/**
* Track a page view event
* Takes enriched data from properties and creates final structured event
*/
page: (a) => {
const { config: t, payload: e } = a, { context: n, page: o, device: i, utm: s, local_time: l } = e;
if (!r)
throw new Error("DotAnalytics: Plugin not initialized");
if (!n || !o || !i || !l)
throw new Error("DotAnalytics: Missing required payload data for pageview event");
const d = {
context: n,
events: [
{
event_type: y.PAGEVIEW,
local_time: l,
data: {
page: o,
device: i,
...s && { utm: s }
}
}
]
};
return t.debug && console.warn("DotAnalytics: Pageview event to send:", d), c(d, t);
},
// TODO: Fix this when we haver the final design for the track event
/**
* Track a custom event
* Takes enriched data and sends it to the analytics server
*/
track: (a) => {
const { config: t, payload: e } = a;
if (!r)
throw new Error("DotAnalytics: Plugin not initialized");
if ("events" in e && Array.isArray(e.events)) {
const o = e, i = {
context: o.context,
events: o.events
};
return t.debug && console.warn("DotAnalytics: Track event to send:", i), c(i, t);
}
if (!e.context || !e.local_time)
throw new Error("DotAnalytics: Missing required payload data for track event");
const n = {
context: e.context,
events: [
{
event_type: y.TRACK,
local_time: e.local_time,
data: {
event: e.event,
...e.properties
}
}
]
};
return t.debug && console.warn("DotAnalytics: Track event to send (fallback):", n), c(n, t);
},
/**
* Check if the plugin is loaded
*/
loaded: () => r
};
};
export {
p as dotAnalytics
};