/** * DAnalytics - Simple Analytics/Event Tracking Utility * * Usage: * const analytics = new DAnalytics({ appName: "myApp", debug: true }); * analytics.trackEvent("user_login", { userId: 123 }); * analytics.trackPageView("/home"); */ import { dlog } from "./dlog"; import { dnetwork } from "./dnetwork"; export interface TConfig { server: string; app_id: string; app_version?: string; device_os?: string; device_id?: string; device_api?: string; debug?: boolean; } export class DAnalytics { private config: TConfig; private sessionKey: string | null = null; private eventQueue: Array<{ type: string; data: any; ts: number }> = []; constructor(config: TConfig) { this.config = config; this.initSession(); } /** * Initialize analytics session by calling the launch API. */ private async initSession() { const url = `http://${this.config.server}/api/analytics/launch`; const payload = { app_id: this.config.app_id, app_version: this.config.app_version || "0.0", device_os: this.config.device_os || "unknown", device_id: this.config.device_id || "unknown", device_api: this.config.device_api || "unknown", }; try { const resp = await dnetwork.postSimpleStore(url, payload); this.sessionKey = resp.out.session; if (this.config.debug) { dlog.d("[DAnalytics] Session initialized:", this.sessionKey); } } catch (err) { if (this.config.debug) { // eslint-disable-next-line no-console dlog.d("[DAnalytics] Failed to initialize session", err); } } } /** * Track a specific user action by calling the /api/analytics/action endpoint. * @param type The type of action (e.g., "click") * @param target_id The target element's ID (e.g., "btn1") * @param tag A tag describing the action (e.g., "btn_click") * @returns The response from the server */ async trackAction( type: string, target_id: string, tag: string ): Promise { if (!this.sessionKey) { if (this.config.debug) { // eslint-disable-next-line no-console console.warn( "[DAnalytics] Session not initialized, cannot track action." ); } return; } const url = `http://${this.config.server}/api/analytics/action`; const payload = { app_id: this.config.app_id, session: this.sessionKey, type, action_id: target_id, action_tag: tag, }; try { const data = await dnetwork.postSimpleStore(url, payload); if (this.config.debug) { // eslint-disable-next-line no-console console.log("[DAnalytics] Tracked action:", data); } return data; } catch (err) { if (this.config.debug) { // eslint-disable-next-line no-console console.error("[DAnalytics] Failed to track action", err); } throw err; } } // This will log anything in the console. // This will flash all log history async trackConsoleLog() { const url = `http://${this.config.server}/api/analytics/adhoc`; return await dnetwork.postSimpleStore(url, { app_id: this.config.app_id, session: this.sessionKey, console_log: dlog.getLogHistoryAndFlash(), }); } }