UNPKG

@dotcms/analytics

Version:

Official JavaScript library for Content Analytics with DotCMS.

262 lines (261 loc) 11.2 kB
import { AnalyticsPlugin, PageData } from 'analytics'; import { DotCMSPredefinedEventType } from '../constants'; import { DotLogger, LogLevel } from '../dot-analytics.logger'; import { AnalyticsBasePayloadWithContext, ContentletData, DotCMSAnalyticsConfig, DotCMSAnalyticsEventContext, DotCMSBrowserData, DotCMSEventDeviceData, DotCMSEventUtmData, EnrichedAnalyticsPayload } from '../models'; export { cleanupActivityTracking, initializeActivityTracking, updateSessionActivity } from '../../plugin/identity/dot-analytics.identity.activity-tracker'; /** * Type guard to check if an event is a predefined event type. * Enables TypeScript type narrowing for better type safety. * * @param event - Event name to check * @returns True if event is a predefined type, false for custom events * * @example * ```typescript * if (isPredefinedEventType(eventName)) { * // TypeScript knows eventName is DotCMSPredefinedEventType here * console.log('Predefined event:', eventName); * } else { * // TypeScript knows eventName is string (custom) here * console.log('Custom event:', eventName); * } * ``` */ export declare function isPredefinedEventType(event: string): event is DotCMSPredefinedEventType; /** * Validates required configuration fields for Analytics initialization. * * @param config - The analytics configuration to validate * @returns Array of missing field names, or null if all required fields are present * * @example * ```ts * const missing = validateAnalyticsConfig(config); * if (missing) { * console.error(`Missing: ${missing.join(' and ')}`); * } * ``` */ export declare function validateAnalyticsConfig(config: DotCMSAnalyticsConfig): string[] | null; /** * Generates a cryptographically secure random ID. * @internal This function is for internal use only and should not be used outside of the SDK. * @param prefix - The prefix for the generated ID * @returns A unique ID string with the given prefix */ export declare const generateSecureId: (prefix: string) => string; /** * Safe sessionStorage wrapper with error handling */ export declare const safeSessionStorage: { getItem: (key: string) => string | null; setItem: (key: string, value: string) => void; removeItem: (key: string) => void; }; /** * Gets or generates a user ID from localStorage. * @internal This function is for internal use only. * @returns The user ID string */ export declare const getUserId: () => string; /** * Gets session ID with comprehensive lifecycle management. * Returns existing valid session ID or creates a new one if needed. * @internal This function is for internal use only. * * Session validation criteria: * 1. User is still active (< 30 min inactivity) * 2. Session hasn't passed midnight (UTC) * * @returns The session ID string */ export declare const getSessionId: () => string; /** * Gets analytics context with user and session identification. * Used by the identity plugin to inject context into analytics events. * * @param config - The analytics configuration object * @returns The analytics context with site_key, session_id, and user_id */ export declare const getAnalyticsContext: (config: DotCMSAnalyticsConfig) => DotCMSAnalyticsEventContext; /** * Configuration result with warnings for analytics setup */ export interface AnalyticsConfigResult { config: DotCMSAnalyticsConfig; warnings?: string[]; missingAttributes?: string[]; hasIssues: boolean; } /** * Gets analytics configuration from script tag attributes. * Always returns a config (with defaults if needed). * * - If no data-analytics-server attribute is found, uses the current domain as the server endpoint * - Both debug and autoPageView default to false (must be explicitly set to "true") * * @returns The analytics configuration object */ export declare const getAnalyticsConfig: () => DotCMSAnalyticsConfig; /** * Gets current device data for analytics. * Combines static browser data with dynamic viewport information. * Used by the identity plugin to inject device data into context. * * @returns Device data with screen resolution, language, and viewport dimensions */ export declare const getDeviceDataForContext: () => DotCMSEventDeviceData; /** * Retrieves the browser event data - optimized but accurate. * @internal This function is for internal use only. * @param location - The Location object to extract data from * @returns Browser event data with all relevant information */ export declare const getBrowserEventData: (location: Location) => DotCMSBrowserData; /** * Extracts and transforms UTM parameters from the URL - cached for performance. * Returns UTM data in DotCMS format (without 'utm_' prefix). * @internal This function is for internal use only. * @param location - The Location object to extract UTM parameters from * @returns DotCMSEventUtmData object with transformed UTM parameters (source, medium, campaign, etc.) */ export declare const extractUTMParameters: (location: Location) => DotCMSEventUtmData; /** * Default redirect function. * @internal This function is for internal use only. * @param href - The URL to redirect to */ export declare const defaultRedirectFn: (href: string) => string; /** * Gets local time in ISO format without milliseconds. * Used by enricher plugins to add local_time to events. * * @returns Local time string in ISO 8601 format with timezone offset (e.g., "2024-01-01T12:00:00-05:00") */ export declare const getLocalTime: () => string; /** * Gets page data from browser event data and payload. * @internal This function is for internal use only. * @param browserData - Browser event data * @param payload - Payload with properties * @returns PageData object for Analytics.js */ export declare const getPageData: (browserData: DotCMSBrowserData, payload: { properties: Record<string, unknown>; }) => PageData; /** * Gets device data from browser event data. * @internal This function is for internal use only. * @param browserData - Browser event data * @returns Device data with screen resolution, language, and viewport dimensions */ export declare const getDeviceData: (browserData: DotCMSBrowserData) => DotCMSEventDeviceData; /** * Gets UTM data from browser event data. * @internal This function is for internal use only. * @param browserData - Browser event data * @returns UTM data with source, medium, campaign, etc. */ export declare const getUtmData: (browserData: DotCMSBrowserData) => DotCMSEventUtmData; /** * Enriches payload with UTM data. * @internal This function is for internal use only. * @param payload - The payload to enrich * @returns The payload with UTM data added */ export declare const enrichWithUtmData: <T extends Record<string, unknown>>(payload: T) => T; /** * Optimized payload enrichment using existing analytics.js data. * Filters out Analytics.js default properties and only keeps user-provided properties in custom. * Used by the enricher plugin to transform Analytics.js payload into DotCMS event format. * * @param payload - The Analytics.js payload with context already injected by identity plugin * @param location - The Location object to extract page data from (defaults to window.location) * @returns Enriched payload with page, UTM, custom data, and local_time (device is in context) */ export declare const enrichPagePayloadOptimized: (payload: AnalyticsBasePayloadWithContext, location?: Location) => EnrichedAnalyticsPayload; /** * Legacy function that enriches page payload with all data in one call. * @internal This function is for internal use only. * @param payload - The payload to enrich * @param location - The Location object to extract data from * @returns Object with enriched payload */ export declare const enrichPagePayload: (payload: { properties: Record<string, unknown>; } & Record<string, unknown>, location?: Location) => { payload: { local_time: string; utm?: DotCMSEventUtmData | undefined; page: PageData; device: DotCMSEventDeviceData; properties: Record<string, unknown>; }; }; /** * Creates a throttled version of a callback function * Ensures the callback is executed at most once every `limitMs` milliseconds * @param callback - The function to throttle * @param limitMs - The time limit in milliseconds * @returns A throttled function */ export declare function createThrottle<T extends (...args: unknown[]) => void>(callback: T, limitMs: number): (...args: Parameters<T>) => void; /** * Extracts the contentlet identifier from a DOM element * @param element - The HTML element containing data attributes * @returns The contentlet identifier or null if not found */ export declare function extractContentletIdentifier(element: HTMLElement): string | null; /** * Extracts all contentlet data from a DOM element's data attributes * @param element - The HTML element containing data attributes * @returns Complete contentlet data object */ export declare function extractContentletData(element: HTMLElement): ContentletData; /** * Initial scan delay for DOM readiness * Allows React/Next.js to finish rendering before scanning for contentlets */ export declare const INITIAL_SCAN_DELAY_MS = 100; /** * Checks if code is running in a browser environment * @returns true if window and document are available */ export declare const isBrowser: () => boolean; /** * Finds all contentlet elements in the DOM * @returns Array of contentlet HTMLElements */ export declare const findContentlets: () => HTMLElement[]; /** * Creates a MutationObserver that watches for contentlet changes in the DOM * @param callback - Function to call when mutations are detected * @param debounceMs - Debounce time in milliseconds (default: 250ms) * @returns Configured and active MutationObserver */ export declare const createContentletObserver: (callback: () => void, debounceMs?: number) => MutationObserver; /** * Sets up cleanup handlers for page unload events * Registers cleanup function to both 'beforeunload' and 'pagehide' for maximum compatibility * @param cleanup - Function to call on page unload */ export declare const setupPluginCleanup: (cleanup: () => void) => void; /** * Creates a logger with plugin-specific prefix and configurable log level * @param pluginName - Name of the plugin (e.g., 'Click', 'Impression') * @param config - Analytics configuration with debug flag and optional logLevel * @returns DotLogger instance with configured log level */ export declare const createPluginLogger: (pluginName: string, config: { debug: boolean; logLevel?: LogLevel; }) => DotLogger; /** * Gets enhanced tracking plugins based on configuration * Returns content impression and click tracking plugins if enabled * @param config - Analytics configuration * @param impressionPlugin - Impression tracking plugin factory * @param clickPlugin - Click tracking plugin factory * @returns Array of enabled tracking plugins */ export declare const getEnhancedTrackingPlugins: (config: DotCMSAnalyticsConfig, impressionPlugin: (config: DotCMSAnalyticsConfig) => AnalyticsPlugin, clickPlugin: (config: DotCMSAnalyticsConfig) => AnalyticsPlugin) => AnalyticsPlugin[];