@momentumcms/plugins-analytics 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Content Performance Handler
3
+ *
4
+ * Express router that serves per-document analytics data.
5
+ * Aggregates page_view events by URL pattern and document properties.
6
+ */
7
+ import { Router } from 'express';
8
+ import type { AnalyticsAdapter } from '../analytics-config.types';
9
+ /**
10
+ * Create an Express router for the content performance endpoint.
11
+ *
12
+ * @param adapter - Analytics storage adapter (must support query)
13
+ * @returns Express Router
14
+ */
15
+ export declare function createContentPerformanceRouter(adapter: AnalyticsAdapter): Router;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Content Performance Types
3
+ *
4
+ * Types for the per-document analytics feature.
5
+ */
6
+ /**
7
+ * Performance data for a specific document.
8
+ */
9
+ export interface ContentPerformanceData {
10
+ /** Total page views for this document */
11
+ pageViews: number;
12
+ /** Unique visitor count */
13
+ uniqueVisitors: number;
14
+ /** Top referrer URLs */
15
+ topReferrers: Array<{
16
+ referrer: string;
17
+ count: number;
18
+ }>;
19
+ /** Block-level engagement (if block tracking is enabled) */
20
+ blockEngagement?: Array<{
21
+ blockType: string;
22
+ impressions: number;
23
+ hovers: number;
24
+ }>;
25
+ }
26
+ /**
27
+ * Query parameters for the content performance endpoint.
28
+ */
29
+ export interface ContentPerformanceQuery {
30
+ /** Collection slug */
31
+ collection: string;
32
+ /** Document ID */
33
+ documentId: string;
34
+ /** Start date (ISO string) */
35
+ from?: string;
36
+ /** End date (ISO string) */
37
+ to?: string;
38
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Event Store
3
+ *
4
+ * In-memory buffer with periodic flush to the analytics adapter.
5
+ * Events are batched for performance and flushed on interval or batch size.
6
+ */
7
+ import type { AnalyticsEvent } from './analytics-event.types';
8
+ import type { AnalyticsAdapter } from './analytics-config.types';
9
+ /**
10
+ * Options for the event store.
11
+ */
12
+ export interface EventStoreOptions {
13
+ /** Storage adapter */
14
+ adapter: AnalyticsAdapter;
15
+ /** Flush interval in ms. @default 5000 */
16
+ flushInterval?: number;
17
+ /** Batch size before forced flush. @default 100 */
18
+ flushBatchSize?: number;
19
+ }
20
+ /**
21
+ * In-memory event buffer with periodic flush.
22
+ */
23
+ export declare class EventStore {
24
+ private buffer;
25
+ private readonly adapter;
26
+ private readonly flushInterval;
27
+ private readonly flushBatchSize;
28
+ private readonly logger;
29
+ private timer;
30
+ private flushing;
31
+ constructor(options: EventStoreOptions);
32
+ /**
33
+ * Start the periodic flush timer.
34
+ */
35
+ start(): void;
36
+ /**
37
+ * Add an event to the buffer.
38
+ * Triggers an immediate flush if batch size is reached.
39
+ */
40
+ add(event: AnalyticsEvent): void;
41
+ /**
42
+ * Add multiple events to the buffer.
43
+ */
44
+ addBatch(events: AnalyticsEvent[]): void;
45
+ /**
46
+ * Flush all buffered events to the adapter.
47
+ */
48
+ flush(): Promise<void>;
49
+ /**
50
+ * Stop the periodic flush timer and flush remaining events.
51
+ */
52
+ shutdown(): Promise<void>;
53
+ /**
54
+ * Get the current buffer size.
55
+ */
56
+ get size(): number;
57
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Ingest Handler
3
+ *
4
+ * Express route handler for the client-side analytics ingest endpoint.
5
+ * Validates incoming events, assigns server-side timestamps, and rate limits.
6
+ */
7
+ import type { Router } from 'express';
8
+ import type { EventStore } from './event-store';
9
+ /**
10
+ * Options for the ingest handler.
11
+ */
12
+ export interface IngestHandlerOptions {
13
+ /** Event store to buffer events */
14
+ eventStore: EventStore;
15
+ /** Rate limit per IP per minute. @default 100 */
16
+ rateLimit?: number;
17
+ }
18
+ /**
19
+ * Creates an Express router for the analytics ingest endpoint.
20
+ *
21
+ * @param options - Ingest handler options
22
+ * @returns Express router
23
+ */
24
+ export declare function createIngestRouter(options: IngestHandlerOptions): Router;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Tracking Rule Types
3
+ *
4
+ * Types for admin-managed element tracking rules.
5
+ * Admins define CSS selector + DOM event → analytics event mappings.
6
+ */
7
+ /**
8
+ * DOM event types supported by tracking rules.
9
+ */
10
+ export type TrackingEventType = 'click' | 'submit' | 'scroll-into-view' | 'hover' | 'focus';
11
+ /**
12
+ * Describes how to extract a property value from a matched DOM element.
13
+ */
14
+ export interface PropertyExtraction {
15
+ /** Property key in the analytics event */
16
+ key: string;
17
+ /** Where to read the value from */
18
+ source: 'text' | 'attribute' | 'dataset';
19
+ /** Attribute or dataset key name (required for 'attribute' and 'dataset' sources) */
20
+ attribute?: string;
21
+ }
22
+ /**
23
+ * A tracking rule as stored in the database.
24
+ */
25
+ export interface TrackingRule {
26
+ id: string;
27
+ /** Human-readable name */
28
+ name: string;
29
+ /** CSS selector to match elements */
30
+ selector: string;
31
+ /** DOM event type to listen for */
32
+ eventType: TrackingEventType;
33
+ /** Analytics event name to fire */
34
+ eventName: string;
35
+ /** URL pattern to match pages (glob: * = any segment, ** = any path) */
36
+ urlPattern: string;
37
+ /** Static properties attached to every event */
38
+ properties: Record<string, string>;
39
+ /** Dynamic property extraction from matched DOM elements */
40
+ extractProperties?: PropertyExtraction[];
41
+ /** Whether this rule is active */
42
+ active: boolean;
43
+ /** Max events per minute per visitor for this rule */
44
+ rateLimit?: number;
45
+ }
46
+ /**
47
+ * Client-facing tracking rule (stripped of internal fields).
48
+ */
49
+ export type ClientTrackingRule = Omit<TrackingRule, 'id'>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Tracking Rules Collection
3
+ *
4
+ * Collection definition for admin-managed element tracking rules.
5
+ * Injected into the collections array by the analytics plugin during onInit.
6
+ */
7
+ /**
8
+ * Tracking Rules collection config.
9
+ * Defines the schema for admin-managed CSS selector tracking rules.
10
+ */
11
+ export declare const TrackingRules: import("@momentumcms/core").CollectionConfig;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Tracking Rules Endpoint
3
+ *
4
+ * Serves active tracking rules to the client-side rule engine.
5
+ * Includes an in-memory cache to avoid DB hits on every page load.
6
+ */
7
+ import { Router } from 'express';
8
+ import type { MomentumAPI } from '@momentumcms/core';
9
+ /**
10
+ * Options for the tracking rules endpoint.
11
+ */
12
+ export interface TrackingRulesEndpointOptions {
13
+ /** Cache time-to-live in ms. @default 60000 */
14
+ cacheTtl?: number;
15
+ }
16
+ /**
17
+ * Create an Express router for serving tracking rules to the client.
18
+ *
19
+ * @param getApi - Function that returns the MomentumAPI instance (available after onReady)
20
+ * @param options - Endpoint options
21
+ * @returns Express Router
22
+ */
23
+ export interface TrackingRulesRouterResult {
24
+ router: Router;
25
+ invalidateCache: () => void;
26
+ }
27
+ export declare function createTrackingRulesRouter(getApi: () => MomentumAPI | null, options?: TrackingRulesEndpointOptions): TrackingRulesRouterResult;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Lightweight User-Agent Parser
3
+ *
4
+ * Extracts device type, browser name, and OS from a user-agent string.
5
+ * Uses simple regex patterns — no external dependencies.
6
+ */
7
+ export interface ParsedUserAgent {
8
+ /** Device type: 'mobile', 'tablet', or 'desktop' */
9
+ device: string;
10
+ /** Browser name (e.g., 'Chrome', 'Firefox', 'Safari') */
11
+ browser: string;
12
+ /** Operating system (e.g., 'Windows', 'macOS', 'Linux', 'iOS', 'Android') */
13
+ os: string;
14
+ }
15
+ /**
16
+ * Parse a user-agent string into device, browser, and OS components.
17
+ *
18
+ * @param ua - The user-agent string to parse
19
+ * @returns Parsed components with sensible defaults for unknown values
20
+ */
21
+ export declare function parseUserAgent(ua: string | undefined): ParsedUserAgent;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * CSS Selector Security Utilities
3
+ *
4
+ * Shared blocklist and validation for tracking rule CSS selectors.
5
+ * Used by both the server-side endpoint (tracking-rules-endpoint.ts)
6
+ * and the client-side rule engine (rule-engine.ts).
7
+ *
8
+ * Selectors targeting sensitive form inputs are rejected to prevent
9
+ * data exfiltration via the tracking rules system.
10
+ */
11
+ /**
12
+ * Check if a CSS selector targets sensitive elements.
13
+ * Normalizes CSS escape sequences and strips pseudo-class wrappers
14
+ * before checking against the blocklist to prevent bypass.
15
+ */
16
+ export declare function isSelectorBlocked(selector: string): boolean;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Shared Type Guards
3
+ *
4
+ * Common type guard functions used across the analytics plugin.
5
+ */
6
+ /**
7
+ * Check if a value is a non-null, non-array object.
8
+ */
9
+ export declare function isRecord(val: unknown): val is Record<string, unknown>;