@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.
- package/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/index.cjs +2218 -0
- package/package.json +56 -0
- package/src/index.d.ts +21 -0
- package/src/lib/adapters/memory-adapter.d.ts +15 -0
- package/src/lib/adapters/postgres-adapter.d.ts +31 -0
- package/src/lib/analytics-auth.d.ts +17 -0
- package/src/lib/analytics-config.types.d.ts +75 -0
- package/src/lib/analytics-event.types.d.ts +89 -0
- package/src/lib/analytics-middleware.d.ts +40 -0
- package/src/lib/analytics-plugin.d.ts +39 -0
- package/src/lib/analytics-query-handler.d.ts +46 -0
- package/src/lib/client/block-tracker.d.ts +29 -0
- package/src/lib/client/rule-engine.d.ts +72 -0
- package/src/lib/client/tracker.d.ts +74 -0
- package/src/lib/collectors/api-collector.d.ts +18 -0
- package/src/lib/collectors/block-field-injector.d.ts +17 -0
- package/src/lib/collectors/collection-collector.d.ts +27 -0
- package/src/lib/content-performance/content-performance-handler.d.ts +15 -0
- package/src/lib/content-performance/content-performance.types.d.ts +38 -0
- package/src/lib/event-store.d.ts +57 -0
- package/src/lib/ingest-handler.d.ts +24 -0
- package/src/lib/tracking-rules/tracking-rule.types.d.ts +49 -0
- package/src/lib/tracking-rules/tracking-rules-collection.d.ts +11 -0
- package/src/lib/tracking-rules/tracking-rules-endpoint.d.ts +27 -0
- package/src/lib/utils/parse-user-agent.d.ts +21 -0
- package/src/lib/utils/selector-security.d.ts +16 -0
- package/src/lib/utils/type-guards.d.ts +9 -0
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@momentumcms/plugins-analytics",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Analytics and content tracking plugin for Momentum CMS",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Momentum CMS Contributors",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/momentum-cms/momentum-cms.git",
|
|
10
|
+
"directory": "libs/plugins/analytics"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/momentum-cms/momentum-cms#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/momentum-cms/momentum-cms/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"cms",
|
|
18
|
+
"momentum-cms",
|
|
19
|
+
"analytics",
|
|
20
|
+
"tracking",
|
|
21
|
+
"content-performance"
|
|
22
|
+
],
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=18"
|
|
25
|
+
},
|
|
26
|
+
"type": "commonjs",
|
|
27
|
+
"main": "./index.cjs",
|
|
28
|
+
"types": "./src/index.d.ts",
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@angular/aria": "^21.1.2",
|
|
31
|
+
"@angular/cdk": "^21.1.2",
|
|
32
|
+
"@angular/common": "~21.1.0",
|
|
33
|
+
"@angular/core": "~21.1.0",
|
|
34
|
+
"@angular/forms": "~21.1.0",
|
|
35
|
+
"@angular/router": "~21.1.0",
|
|
36
|
+
"@aws-sdk/client-s3": "^3.983.0",
|
|
37
|
+
"@aws-sdk/s3-request-presigner": "^3.983.0",
|
|
38
|
+
"@momentumcms/core": "0.1.0",
|
|
39
|
+
"@momentumcms/logger": "0.1.0",
|
|
40
|
+
"@momentumcms/plugins-core": "0.1.0",
|
|
41
|
+
"@momentumcms/server-core": "0.1.0",
|
|
42
|
+
"@ng-icons/core": "^33.0.0",
|
|
43
|
+
"@ng-icons/heroicons": "^33.0.0",
|
|
44
|
+
"express": "^4.21.0",
|
|
45
|
+
"graphql": "^16.12.0",
|
|
46
|
+
"rxjs": "~7.8.0"
|
|
47
|
+
},
|
|
48
|
+
"peerDependencies": {
|
|
49
|
+
"pg": "^8.0.0"
|
|
50
|
+
},
|
|
51
|
+
"peerDependenciesMeta": {
|
|
52
|
+
"pg": {
|
|
53
|
+
"optional": true
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export type { AnalyticsEvent, AnalyticsCategory, AnalyticsContext, AnalyticsQueryOptions, AnalyticsQueryResult, } from './lib/analytics-event.types';
|
|
2
|
+
export type { AnalyticsAdapter, AnalyticsConfig } from './lib/analytics-config.types';
|
|
3
|
+
export { EventStore, type EventStoreOptions } from './lib/event-store';
|
|
4
|
+
export { injectCollectionCollector, type AnalyticsEmitter, type CollectionCollectorOptions, } from './lib/collectors/collection-collector';
|
|
5
|
+
export { createApiCollectorMiddleware } from './lib/collectors/api-collector';
|
|
6
|
+
export { createIngestRouter, type IngestHandlerOptions } from './lib/ingest-handler';
|
|
7
|
+
export { MemoryAnalyticsAdapter } from './lib/adapters/memory-adapter';
|
|
8
|
+
export { postgresAnalyticsAdapter, type PostgresAnalyticsAdapterOptions, } from './lib/adapters/postgres-adapter';
|
|
9
|
+
export { parseUserAgent, type ParsedUserAgent } from './lib/utils/parse-user-agent';
|
|
10
|
+
export { createTracker, type TrackerConfig, type MomentumTracker, type ClientEvent, } from './lib/client/tracker';
|
|
11
|
+
export { analyticsPlugin, type AnalyticsPluginInstance } from './lib/analytics-plugin';
|
|
12
|
+
export { createAnalyticsQueryRouter, type AnalyticsSummary } from './lib/analytics-query-handler';
|
|
13
|
+
export { createAnalyticsMiddleware, type AnalyticsMiddleware } from './lib/analytics-middleware';
|
|
14
|
+
export { injectBlockAnalyticsFields } from './lib/collectors/block-field-injector';
|
|
15
|
+
export { attachBlockTracking } from './lib/client/block-tracker';
|
|
16
|
+
export { createRuleEngine, type RuleEngine, type RuleEngineConfig } from './lib/client/rule-engine';
|
|
17
|
+
export { TrackingRules } from './lib/tracking-rules/tracking-rules-collection';
|
|
18
|
+
export { createTrackingRulesRouter, type TrackingRulesEndpointOptions, type TrackingRulesRouterResult, } from './lib/tracking-rules/tracking-rules-endpoint';
|
|
19
|
+
export type { TrackingRule, ClientTrackingRule, TrackingEventType, PropertyExtraction, } from './lib/tracking-rules/tracking-rule.types';
|
|
20
|
+
export { createContentPerformanceRouter } from './lib/content-performance/content-performance-handler';
|
|
21
|
+
export type { ContentPerformanceData, ContentPerformanceQuery, } from './lib/content-performance/content-performance.types';
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-Memory Analytics Adapter
|
|
3
|
+
*
|
|
4
|
+
* Stores analytics events in memory. Useful for testing and development.
|
|
5
|
+
*/
|
|
6
|
+
import type { AnalyticsAdapter } from '../analytics-config.types';
|
|
7
|
+
import type { AnalyticsEvent, AnalyticsQueryOptions, AnalyticsQueryResult } from '../analytics-event.types';
|
|
8
|
+
/**
|
|
9
|
+
* In-memory analytics adapter for development and testing.
|
|
10
|
+
*/
|
|
11
|
+
export declare class MemoryAnalyticsAdapter implements AnalyticsAdapter {
|
|
12
|
+
readonly events: AnalyticsEvent[];
|
|
13
|
+
store(events: AnalyticsEvent[]): Promise<void>;
|
|
14
|
+
query(options?: AnalyticsQueryOptions): Promise<AnalyticsQueryResult>;
|
|
15
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PostgreSQL Analytics Adapter
|
|
3
|
+
*
|
|
4
|
+
* Stores analytics events in a PostgreSQL table with JSONB columns.
|
|
5
|
+
* Uses the `pg` package (same as @momentumcms/db-drizzle).
|
|
6
|
+
*/
|
|
7
|
+
import type { AnalyticsAdapter } from '../analytics-config.types';
|
|
8
|
+
/**
|
|
9
|
+
* PostgreSQL analytics adapter options.
|
|
10
|
+
*/
|
|
11
|
+
export interface PostgresAnalyticsAdapterOptions {
|
|
12
|
+
/** PostgreSQL connection string */
|
|
13
|
+
connectionString: string;
|
|
14
|
+
/** Maximum pool size. @default 5 */
|
|
15
|
+
poolSize?: number;
|
|
16
|
+
/** Table name. @default '_momentum_analytics' */
|
|
17
|
+
tableName?: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* PostgreSQL analytics adapter.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* import { postgresAnalyticsAdapter } from '@momentumcms/plugins/analytics';
|
|
25
|
+
*
|
|
26
|
+
* const adapter = postgresAnalyticsAdapter({
|
|
27
|
+
* connectionString: process.env.DATABASE_URL,
|
|
28
|
+
* });
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export declare function postgresAnalyticsAdapter(options: PostgresAnalyticsAdapterOptions): AnalyticsAdapter;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Analytics Auth Utilities
|
|
3
|
+
*
|
|
4
|
+
* Shared authentication helpers for analytics endpoints.
|
|
5
|
+
* Uses type guards (no `as` assertions) to check req.user set by auth middleware.
|
|
6
|
+
*/
|
|
7
|
+
import type { Request, Response, NextFunction } from 'express';
|
|
8
|
+
/**
|
|
9
|
+
* Express middleware that requires authentication.
|
|
10
|
+
* Returns 401 if no valid user session is present.
|
|
11
|
+
*/
|
|
12
|
+
export declare function requireAuth(req: Request, res: Response, next: NextFunction): void;
|
|
13
|
+
/**
|
|
14
|
+
* Express middleware that requires admin role.
|
|
15
|
+
* Returns 401 if no session, 403 if not admin.
|
|
16
|
+
*/
|
|
17
|
+
export declare function requireAdmin(req: Request, res: Response, next: NextFunction): void;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Analytics Configuration Types
|
|
3
|
+
*/
|
|
4
|
+
import type { AnalyticsEvent, AnalyticsQueryOptions, AnalyticsQueryResult } from './analytics-event.types';
|
|
5
|
+
/**
|
|
6
|
+
* Analytics storage adapter interface.
|
|
7
|
+
* Implement this to store analytics events in your preferred backend.
|
|
8
|
+
*/
|
|
9
|
+
export interface AnalyticsAdapter {
|
|
10
|
+
/** Store a batch of events */
|
|
11
|
+
store(events: AnalyticsEvent[]): Promise<void>;
|
|
12
|
+
/** Query events (for admin dashboard) */
|
|
13
|
+
query?(options: AnalyticsQueryOptions): Promise<AnalyticsQueryResult>;
|
|
14
|
+
/** Initialize adapter (create tables, etc.) */
|
|
15
|
+
initialize?(): Promise<void>;
|
|
16
|
+
/** Flush pending events and close connections */
|
|
17
|
+
shutdown?(): Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Analytics configuration.
|
|
21
|
+
*/
|
|
22
|
+
export interface AnalyticsConfig {
|
|
23
|
+
/** Enable/disable analytics. @default true */
|
|
24
|
+
enabled?: boolean;
|
|
25
|
+
/** Analytics storage adapter */
|
|
26
|
+
adapter: AnalyticsAdapter;
|
|
27
|
+
/** Server-side collection tracking. @default true */
|
|
28
|
+
trackCollections?: boolean;
|
|
29
|
+
/** API request tracking. @default true */
|
|
30
|
+
trackApi?: boolean;
|
|
31
|
+
/** Admin action tracking. @default true */
|
|
32
|
+
trackAdmin?: boolean;
|
|
33
|
+
/** Client-side ingest endpoint path. @default '/api/analytics/collect' */
|
|
34
|
+
ingestPath?: string;
|
|
35
|
+
/** Rate limit for ingest endpoint (requests per minute per IP). @default 100 */
|
|
36
|
+
ingestRateLimit?: number;
|
|
37
|
+
/** Batch flush interval in ms. @default 5000 */
|
|
38
|
+
flushInterval?: number;
|
|
39
|
+
/** Batch size before forced flush. @default 100 */
|
|
40
|
+
flushBatchSize?: number;
|
|
41
|
+
/** Collections to exclude from tracking */
|
|
42
|
+
excludeCollections?: string[];
|
|
43
|
+
/**
|
|
44
|
+
* Inject analytics toggle fields into block definitions.
|
|
45
|
+
* When enabled, admins can toggle impression/click tracking per block instance.
|
|
46
|
+
* @default true
|
|
47
|
+
*/
|
|
48
|
+
blockTracking?: boolean;
|
|
49
|
+
/**
|
|
50
|
+
* Content performance endpoint and admin page.
|
|
51
|
+
* @default true
|
|
52
|
+
*/
|
|
53
|
+
contentPerformance?: boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Element tracking rules (admin-managed CSS selector listeners).
|
|
56
|
+
* - `true` (default): enable with default settings
|
|
57
|
+
* - `false`: disable
|
|
58
|
+
* - object: override cache TTL
|
|
59
|
+
*/
|
|
60
|
+
trackingRules?: boolean | {
|
|
61
|
+
cacheTtl?: number;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Admin dashboard configuration.
|
|
65
|
+
* - `true` (default): use built-in dashboard
|
|
66
|
+
* - `false`: disable dashboard
|
|
67
|
+
* - object: override loadComponent and/or group
|
|
68
|
+
*/
|
|
69
|
+
adminDashboard?: boolean | {
|
|
70
|
+
/** Override lazy component loader */
|
|
71
|
+
loadComponent?: unknown;
|
|
72
|
+
/** Sidebar section name. @default 'Tools' */
|
|
73
|
+
group?: string;
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Analytics Event Types
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* Analytics event categories.
|
|
6
|
+
*/
|
|
7
|
+
export type AnalyticsCategory = 'admin' | 'api' | 'content' | 'page' | 'action' | 'custom';
|
|
8
|
+
/**
|
|
9
|
+
* A single analytics event.
|
|
10
|
+
*/
|
|
11
|
+
export interface AnalyticsEvent {
|
|
12
|
+
/** Unique event ID */
|
|
13
|
+
id: string;
|
|
14
|
+
/** Event category */
|
|
15
|
+
category: AnalyticsCategory;
|
|
16
|
+
/** Event name (e.g., 'page_view', 'content_created', 'button_click') */
|
|
17
|
+
name: string;
|
|
18
|
+
/** ISO timestamp */
|
|
19
|
+
timestamp: string;
|
|
20
|
+
/** Session ID (for client events) */
|
|
21
|
+
sessionId?: string;
|
|
22
|
+
/** User/visitor identifier */
|
|
23
|
+
userId?: string;
|
|
24
|
+
/** Anonymous visitor ID (for non-authenticated frontend users) */
|
|
25
|
+
visitorId?: string;
|
|
26
|
+
/** Event-specific properties */
|
|
27
|
+
properties: Record<string, unknown>;
|
|
28
|
+
/** Context metadata */
|
|
29
|
+
context: AnalyticsContext;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Context metadata for analytics events.
|
|
33
|
+
*/
|
|
34
|
+
export interface AnalyticsContext {
|
|
35
|
+
/** Source: 'server' or 'client' */
|
|
36
|
+
source: 'server' | 'client';
|
|
37
|
+
/** Page URL */
|
|
38
|
+
url?: string;
|
|
39
|
+
/** Referrer URL */
|
|
40
|
+
referrer?: string;
|
|
41
|
+
/** Raw user agent string */
|
|
42
|
+
userAgent?: string;
|
|
43
|
+
/** Client IP address */
|
|
44
|
+
ip?: string;
|
|
45
|
+
/** Device type (mobile, tablet, desktop) */
|
|
46
|
+
device?: string;
|
|
47
|
+
/** Browser name (Chrome, Firefox, Safari, etc.) */
|
|
48
|
+
browser?: string;
|
|
49
|
+
/** Operating system (Windows, macOS, Linux, iOS, Android) */
|
|
50
|
+
os?: string;
|
|
51
|
+
/** For server events: collection slug */
|
|
52
|
+
collection?: string;
|
|
53
|
+
/** For server events: operation type */
|
|
54
|
+
operation?: string;
|
|
55
|
+
/** For API events: response time in ms */
|
|
56
|
+
duration?: number;
|
|
57
|
+
/** For API events: HTTP status code */
|
|
58
|
+
statusCode?: number;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Query options for retrieving analytics events.
|
|
62
|
+
*/
|
|
63
|
+
export interface AnalyticsQueryOptions {
|
|
64
|
+
/** Filter by category */
|
|
65
|
+
category?: AnalyticsCategory;
|
|
66
|
+
/** Filter by event name */
|
|
67
|
+
name?: string;
|
|
68
|
+
/** Filter by collection */
|
|
69
|
+
collection?: string;
|
|
70
|
+
/** Full-text search across event name, URL, collection */
|
|
71
|
+
search?: string;
|
|
72
|
+
/** Start date (ISO string) */
|
|
73
|
+
from?: string;
|
|
74
|
+
/** End date (ISO string) */
|
|
75
|
+
to?: string;
|
|
76
|
+
/** Maximum number of results */
|
|
77
|
+
limit?: number;
|
|
78
|
+
/** Page number (1-based) */
|
|
79
|
+
page?: number;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Result of an analytics query.
|
|
83
|
+
*/
|
|
84
|
+
export interface AnalyticsQueryResult {
|
|
85
|
+
events: AnalyticsEvent[];
|
|
86
|
+
total: number;
|
|
87
|
+
page: number;
|
|
88
|
+
limit: number;
|
|
89
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Analytics Express Middleware
|
|
3
|
+
*
|
|
4
|
+
* Convenience function to create all Express middleware from an analytics plugin instance.
|
|
5
|
+
* Returns the ingest router (for client-side events) and API collector middleware.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { analyticsPlugin, createAnalyticsMiddleware, MemoryAnalyticsAdapter } from '@momentumcms/plugins/analytics';
|
|
10
|
+
*
|
|
11
|
+
* const analytics = analyticsPlugin({ adapter: new MemoryAnalyticsAdapter() });
|
|
12
|
+
*
|
|
13
|
+
* // In Express setup:
|
|
14
|
+
* const { ingestRouter, apiCollector } = createAnalyticsMiddleware(analytics);
|
|
15
|
+
* app.use('/api/analytics/collect', ingestRouter);
|
|
16
|
+
* app.use('/api', apiCollector);
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
import type { Router, Request, Response, NextFunction } from 'express';
|
|
20
|
+
import type { AnalyticsPluginInstance } from './analytics-plugin';
|
|
21
|
+
/**
|
|
22
|
+
* Result of createAnalyticsMiddleware.
|
|
23
|
+
*/
|
|
24
|
+
export interface AnalyticsMiddleware {
|
|
25
|
+
/** Express router for the ingest endpoint (mount at your ingest path) */
|
|
26
|
+
ingestRouter: Router;
|
|
27
|
+
/** Express middleware that tracks API request timing/status (mount before API routes) */
|
|
28
|
+
apiCollector: (req: Request, res: Response, next: NextFunction) => void;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Creates all Express middleware from an analytics plugin instance.
|
|
32
|
+
*
|
|
33
|
+
* @deprecated The analytics plugin now auto-registers its middleware via the plugin system.
|
|
34
|
+
* Simply add `analyticsPlugin(config)` to your `plugins` array in momentum.config.ts
|
|
35
|
+
* and the framework will mount the ingest router and API collector automatically.
|
|
36
|
+
*
|
|
37
|
+
* @param plugin - The analytics plugin instance (returned by `analyticsPlugin()`)
|
|
38
|
+
* @returns Object with ingest router and API collector middleware
|
|
39
|
+
*/
|
|
40
|
+
export declare function createAnalyticsMiddleware(plugin: AnalyticsPluginInstance): AnalyticsMiddleware;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Analytics Plugin
|
|
3
|
+
*
|
|
4
|
+
* A Momentum CMS plugin that wires all analytics collectors together.
|
|
5
|
+
* Tracks collection CRUD, API requests, and accepts client-side events.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { analyticsPlugin, MemoryAnalyticsAdapter } from '@momentumcms/plugins/analytics';
|
|
10
|
+
*
|
|
11
|
+
* export default defineMomentumConfig({
|
|
12
|
+
* plugins: [
|
|
13
|
+
* analyticsPlugin({
|
|
14
|
+
* adapter: new MemoryAnalyticsAdapter(),
|
|
15
|
+
* // Dashboard is included by default. Set false to disable.
|
|
16
|
+
* }),
|
|
17
|
+
* ],
|
|
18
|
+
* });
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
import type { MomentumPlugin } from '@momentumcms/plugins/core';
|
|
22
|
+
import type { AnalyticsConfig } from './analytics-config.types';
|
|
23
|
+
import { EventStore } from './event-store';
|
|
24
|
+
/**
|
|
25
|
+
* Analytics plugin with access to the event store.
|
|
26
|
+
*/
|
|
27
|
+
export interface AnalyticsPluginInstance extends MomentumPlugin {
|
|
28
|
+
/** The event store — use for manual event emission */
|
|
29
|
+
eventStore: EventStore;
|
|
30
|
+
/** The analytics configuration */
|
|
31
|
+
analyticsConfig: AnalyticsConfig;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Creates an analytics plugin.
|
|
35
|
+
*
|
|
36
|
+
* @param config - Analytics configuration
|
|
37
|
+
* @returns Plugin instance
|
|
38
|
+
*/
|
|
39
|
+
export declare function analyticsPlugin(config: AnalyticsConfig): AnalyticsPluginInstance;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Analytics Query Handler
|
|
3
|
+
*
|
|
4
|
+
* Express router with endpoints for querying analytics data.
|
|
5
|
+
* Provides paginated event queries and pre-aggregated summary metrics.
|
|
6
|
+
*/
|
|
7
|
+
import { Router } from 'express';
|
|
8
|
+
import type { EventStore } from './event-store';
|
|
9
|
+
import type { AnalyticsAdapter } from './analytics-config.types';
|
|
10
|
+
/**
|
|
11
|
+
* Pre-aggregated analytics summary.
|
|
12
|
+
*/
|
|
13
|
+
export interface AnalyticsSummary {
|
|
14
|
+
totalEvents: number;
|
|
15
|
+
byCategory: Record<string, number>;
|
|
16
|
+
byCollection: Record<string, number>;
|
|
17
|
+
contentOperations: {
|
|
18
|
+
created: number;
|
|
19
|
+
updated: number;
|
|
20
|
+
deleted: number;
|
|
21
|
+
};
|
|
22
|
+
apiMetrics: {
|
|
23
|
+
totalRequests: number;
|
|
24
|
+
avgDuration: number;
|
|
25
|
+
};
|
|
26
|
+
activeSessions: number;
|
|
27
|
+
activeVisitors: number;
|
|
28
|
+
/** Top pages by visit count */
|
|
29
|
+
topPages: Array<{
|
|
30
|
+
url: string;
|
|
31
|
+
count: number;
|
|
32
|
+
}>;
|
|
33
|
+
/** Top referrers by count */
|
|
34
|
+
topReferrers: Array<{
|
|
35
|
+
referrer: string;
|
|
36
|
+
count: number;
|
|
37
|
+
}>;
|
|
38
|
+
/** Device type breakdown */
|
|
39
|
+
deviceBreakdown: Record<string, number>;
|
|
40
|
+
/** Browser breakdown */
|
|
41
|
+
browserBreakdown: Record<string, number>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Creates an Express router with analytics query endpoints.
|
|
45
|
+
*/
|
|
46
|
+
export declare function createAnalyticsQueryRouter(eventStore: EventStore, adapter: AnalyticsAdapter): Router;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Block-Level Analytics Tracker
|
|
3
|
+
*
|
|
4
|
+
* Attaches IntersectionObserver for impression tracking and mouseenter delegation
|
|
5
|
+
* for hover tracking on blocks that have `data-block-track` attributes.
|
|
6
|
+
*
|
|
7
|
+
* Only tracks blocks where the admin has enabled tracking via the
|
|
8
|
+
* `_analytics` group fields injected by the analytics plugin.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* const tracker = createTracker({ endpoint: '/api/analytics/collect' });
|
|
13
|
+
* const cleanup = attachBlockTracking(tracker);
|
|
14
|
+
* // Later: cleanup() to disconnect observers and remove listeners
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
import type { MomentumTracker } from './tracker';
|
|
18
|
+
/**
|
|
19
|
+
* Attach block-level analytics tracking to the page.
|
|
20
|
+
*
|
|
21
|
+
* Finds all elements with `data-block-track` and:
|
|
22
|
+
* - Observes visibility via IntersectionObserver (for `impressions`)
|
|
23
|
+
* - Listens for mouseenter via event delegation (for `hover`)
|
|
24
|
+
*
|
|
25
|
+
* @param tracker - Momentum tracker instance for event emission
|
|
26
|
+
* @param container - DOM container to scope tracking (defaults to document.body)
|
|
27
|
+
* @returns Cleanup function to disconnect observers and remove listeners
|
|
28
|
+
*/
|
|
29
|
+
export declare function attachBlockTracking(tracker: MomentumTracker, container?: HTMLElement): () => void;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rule Engine
|
|
3
|
+
*
|
|
4
|
+
* Client-side engine for admin-managed element tracking rules.
|
|
5
|
+
* Fetches active rules from the server, filters by current URL,
|
|
6
|
+
* and attaches event listeners/observers for matching elements.
|
|
7
|
+
*
|
|
8
|
+
* Supports SPA navigation by wrapping pushState/replaceState and
|
|
9
|
+
* listening for popstate to re-filter rules on route changes.
|
|
10
|
+
*/
|
|
11
|
+
import type { MomentumTracker } from './tracker';
|
|
12
|
+
/**
|
|
13
|
+
* Rule engine configuration.
|
|
14
|
+
*/
|
|
15
|
+
export interface RuleEngineConfig {
|
|
16
|
+
/** Rules endpoint URL. @default '/api/analytics/tracking-rules' */
|
|
17
|
+
endpoint?: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Rule engine instance.
|
|
21
|
+
*/
|
|
22
|
+
export interface RuleEngine {
|
|
23
|
+
/** Fetch rules and start tracking for the current URL */
|
|
24
|
+
start(): Promise<void>;
|
|
25
|
+
/** Stop all tracking and clean up listeners */
|
|
26
|
+
stop(): void;
|
|
27
|
+
/** Re-filter rules and re-attach listeners for a new URL (SPA navigation) */
|
|
28
|
+
onNavigate(url: string): void;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* A tracking rule as received from the server.
|
|
32
|
+
*/
|
|
33
|
+
interface ClientRule {
|
|
34
|
+
name: string;
|
|
35
|
+
selector: string;
|
|
36
|
+
eventType: string;
|
|
37
|
+
eventName: string;
|
|
38
|
+
urlPattern: string;
|
|
39
|
+
properties: Record<string, unknown>;
|
|
40
|
+
extractProperties?: unknown[];
|
|
41
|
+
active: boolean;
|
|
42
|
+
rateLimit?: number;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Match a URL pathname against a glob pattern.
|
|
46
|
+
* Supports `*` (any single path segment) and `**` (any path depth).
|
|
47
|
+
*/
|
|
48
|
+
export declare function matchUrlPattern(pattern: string, pathname: string): boolean;
|
|
49
|
+
/**
|
|
50
|
+
* Validate and narrow a server response to a rules array.
|
|
51
|
+
* Rejects rules with selectors targeting sensitive form inputs.
|
|
52
|
+
*/
|
|
53
|
+
export declare function parseRulesResponse(data: unknown): ClientRule[];
|
|
54
|
+
/**
|
|
55
|
+
* Create a client-side rule engine.
|
|
56
|
+
*
|
|
57
|
+
* @param tracker - Momentum tracker instance for event emission
|
|
58
|
+
* @param config - Rule engine configuration
|
|
59
|
+
* @returns Rule engine instance
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```typescript
|
|
63
|
+
* const engine = createRuleEngine(tracker, { endpoint: '/api/analytics/tracking-rules' });
|
|
64
|
+
* await engine.start();
|
|
65
|
+
* // On SPA navigation:
|
|
66
|
+
* engine.onNavigate('/new-path');
|
|
67
|
+
* // Cleanup:
|
|
68
|
+
* engine.stop();
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export declare function createRuleEngine(tracker: MomentumTracker, config?: RuleEngineConfig): RuleEngine;
|
|
72
|
+
export {};
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client-Side Analytics Tracker
|
|
3
|
+
*
|
|
4
|
+
* Lightweight JS snippet (~2KB) for tracking page views and custom actions.
|
|
5
|
+
* Designed to be served as a standalone script or imported in frontend apps.
|
|
6
|
+
*
|
|
7
|
+
* Features:
|
|
8
|
+
* - Auto-generates visitorId (localStorage) and sessionId (sessionStorage)
|
|
9
|
+
* - Batches events and flushes every 5s or on beforeunload
|
|
10
|
+
* - Uses navigator.sendBeacon() for reliable delivery on page exit
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Tracker configuration.
|
|
14
|
+
*/
|
|
15
|
+
export interface TrackerConfig {
|
|
16
|
+
/** Ingest endpoint URL. @default '/api/analytics/collect' */
|
|
17
|
+
endpoint?: string;
|
|
18
|
+
/** Flush interval in ms. @default 5000 */
|
|
19
|
+
flushInterval?: number;
|
|
20
|
+
/** Enable block-level analytics (impressions + clicks on blocks with `data-block-track`). @default false */
|
|
21
|
+
blockTracking?: boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Enable element tracking rules (admin-managed CSS selector listeners).
|
|
24
|
+
* - `true`: enable with default endpoint
|
|
25
|
+
* - object: override rules endpoint URL
|
|
26
|
+
* @default false
|
|
27
|
+
*/
|
|
28
|
+
trackingRules?: boolean | {
|
|
29
|
+
endpoint?: string;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Client event structure (before server enrichment).
|
|
34
|
+
*/
|
|
35
|
+
export interface ClientEvent {
|
|
36
|
+
name: string;
|
|
37
|
+
category?: string;
|
|
38
|
+
properties?: Record<string, unknown>;
|
|
39
|
+
context?: {
|
|
40
|
+
url?: string;
|
|
41
|
+
referrer?: string;
|
|
42
|
+
};
|
|
43
|
+
sessionId?: string;
|
|
44
|
+
visitorId?: string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Momentum Analytics Tracker interface.
|
|
48
|
+
*/
|
|
49
|
+
export interface MomentumTracker {
|
|
50
|
+
/** Track a page view (auto-captures URL, referrer) */
|
|
51
|
+
pageView(properties?: Record<string, unknown>): void;
|
|
52
|
+
/** Track a custom action */
|
|
53
|
+
track(name: string, properties?: Record<string, unknown>): void;
|
|
54
|
+
/** Identify the current user */
|
|
55
|
+
identify(userId: string, traits?: Record<string, unknown>): void;
|
|
56
|
+
/** Flush pending events */
|
|
57
|
+
flush(): void;
|
|
58
|
+
/** Flush pending events and clean up all listeners, timers, and observers */
|
|
59
|
+
destroy(): void;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Create a Momentum Analytics tracker.
|
|
63
|
+
*
|
|
64
|
+
* @param config - Tracker configuration
|
|
65
|
+
* @returns Tracker instance
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```typescript
|
|
69
|
+
* const tracker = createTracker({ endpoint: '/api/analytics/collect' });
|
|
70
|
+
* tracker.pageView();
|
|
71
|
+
* tracker.track('button_click', { buttonId: 'cta-signup' });
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export declare function createTracker(config?: TrackerConfig): MomentumTracker;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* API Collector
|
|
3
|
+
*
|
|
4
|
+
* Express middleware that tracks API request timing and status codes.
|
|
5
|
+
*/
|
|
6
|
+
import type { Request, Response, NextFunction } from 'express';
|
|
7
|
+
import type { AnalyticsEvent } from '../analytics-event.types';
|
|
8
|
+
/**
|
|
9
|
+
* Callback type for analytics event emission.
|
|
10
|
+
*/
|
|
11
|
+
export type AnalyticsEmitter = (event: AnalyticsEvent) => void;
|
|
12
|
+
/**
|
|
13
|
+
* Creates Express middleware that tracks API request metrics.
|
|
14
|
+
*
|
|
15
|
+
* @param emitter - Callback to emit analytics events
|
|
16
|
+
* @returns Express middleware function
|
|
17
|
+
*/
|
|
18
|
+
export declare function createApiCollectorMiddleware(emitter: AnalyticsEmitter): (req: Request, res: Response, next: NextFunction) => void;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Block Field Injector
|
|
3
|
+
*
|
|
4
|
+
* Walks all collections and injects `_analytics` group fields into every
|
|
5
|
+
* BlockConfig, giving admins per-block-instance control over impression
|
|
6
|
+
* and hover tracking.
|
|
7
|
+
*
|
|
8
|
+
* Same mutation pattern as `injectCollectionCollector` — modifies the
|
|
9
|
+
* mutable collections array during plugin `onInit`.
|
|
10
|
+
*/
|
|
11
|
+
import type { CollectionConfig } from '@momentumcms/core';
|
|
12
|
+
/**
|
|
13
|
+
* Inject analytics group fields into all block definitions across all collections.
|
|
14
|
+
*
|
|
15
|
+
* @param collections - Mutable collections array from PluginContext
|
|
16
|
+
*/
|
|
17
|
+
export declare function injectBlockAnalyticsFields(collections: CollectionConfig[]): void;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Collection Collector
|
|
3
|
+
*
|
|
4
|
+
* Injects afterChange and afterDelete hooks that emit analytics events
|
|
5
|
+
* for collection CRUD operations.
|
|
6
|
+
*/
|
|
7
|
+
import type { CollectionConfig } from '@momentumcms/core';
|
|
8
|
+
import type { AnalyticsEvent } from '../analytics-event.types';
|
|
9
|
+
/**
|
|
10
|
+
* Callback type for analytics event emission.
|
|
11
|
+
*/
|
|
12
|
+
export type AnalyticsEmitter = (event: AnalyticsEvent) => void;
|
|
13
|
+
/**
|
|
14
|
+
* Options for the collection collector.
|
|
15
|
+
*/
|
|
16
|
+
export interface CollectionCollectorOptions {
|
|
17
|
+
/** Collections to exclude from tracking */
|
|
18
|
+
excludeCollections?: string[];
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Inject collection tracking hooks into all collections.
|
|
22
|
+
*
|
|
23
|
+
* @param collections - Mutable collections array
|
|
24
|
+
* @param emitter - Callback to emit analytics events
|
|
25
|
+
* @param options - Collector options
|
|
26
|
+
*/
|
|
27
|
+
export declare function injectCollectionCollector(collections: CollectionConfig[], emitter: AnalyticsEmitter, options?: CollectionCollectorOptions): void;
|