/** * Shared analytics event taxonomy and envelope validation (Phase 1). * * Pure module: no Payload, no DOM. Imported by the client SDK * (`src/lib/client-analytics/`), the collector route, the ingest service and * the rollup bins, so the event vocabulary has exactly one source of truth. * The Postgres `analytics_events.type` column mirrors this union; adding a * type here is a taxonomy change that belongs in the SDK README. */ export const ANALYTICS_EVENT_TYPES = [ "pageview", "click", "scroll", "focus", "visible", "custom", "heartbeat", ] as const; export type AnalyticsEventType = (typeof ANALYTICS_EVENT_TYPES)[number]; export function isAnalyticsEventType(value: unknown): value is AnalyticsEventType { return typeof value === "string" && (ANALYTICS_EVENT_TYPES as readonly string[]).includes(value); } /** Environment tag carried on every row ("dev" vs "production"). */ export const ANALYTICS_ENVS = ["dev", "production"] as const; export type AnalyticsEnv = (typeof ANALYTICS_ENVS)[number]; /** Resolve the env tag from the server process (clients never set it). */ export function resolveAnalyticsEnv(nodeEnv: string | undefined): AnalyticsEnv { return nodeEnv === "production" ? "production" : "dev"; } // --------------------------------------------------------------------------- // Ingest limits (strict validation at the collector boundary) // --------------------------------------------------------------------------- /** Maximum events accepted per batched envelope. */ export const MAX_EVENTS_PER_BATCH = 50; /** Maximum characters kept for a path. */ export const MAX_PATH_LENGTH = 2048; /** Maximum serialized JSON size for one `element` or `data` payload. */ export const MAX_JSON_BYTES = 4_096; /** Maximum characters for the session / anonymous identifiers. */ export const MAX_ID_LENGTH = 64; /** A batch may not carry timestamps further ahead than this. */ export const MAX_FUTURE_SKEW_MS = 5 * 60 * 1000; /** A batch may not carry timestamps older than this (stale beacon replays). */ export const MAX_PAST_AGE_MS = 24 * 60 * 60 * 1000; // --------------------------------------------------------------------------- // Envelope shape // --------------------------------------------------------------------------- /** One client event before validation. The SDK sends epoch-ms `ts`. */ export interface RawClientEvent { ts?: number; type: string; path?: string; element?: unknown; data?: unknown; } /** POST body of `/api/collect`: `{ sid, aid, events }`. */ export interface CollectEnvelope { sid: string | null; aid: string | null; events: RawClientEvent[]; } /** A validated event ready for insertion. */ export interface ValidatedEvent { ts: Date; type: AnalyticsEventType; path: string | null; element: Record | null; data: Record | null; } export interface ParsedEnvelope { sid: string | null; aid: string | null; events: ValidatedEvent[]; /** Events dropped by per-event validation (bad type, oversized json, ...). */ dropped: number; } function clampId(value: unknown): string | null { if (typeof value !== "string") return null; const trimmed = value.trim(); if (!trimmed) return null; return trimmed.slice(0, MAX_ID_LENGTH); } function clampPath(value: unknown): string | null { if (typeof value !== "string") return null; const trimmed = value.trim(); if (!trimmed || !trimmed.startsWith("/")) return null; return trimmed.slice(0, MAX_PATH_LENGTH); } function clampJsonObject(value: unknown): Record | null { if (value === null || value === undefined) return null; if (typeof value !== "object" || Array.isArray(value)) return null; let serialized: string; try { serialized = JSON.stringify(value); } catch { return null; } if (serialized.length > MAX_JSON_BYTES) return null; return value as Record; } /** * Validate a parsed JSON body into a `ParsedEnvelope`. Structural problems * (non-object body, missing/empty events array, oversized batch) reject the * whole request; individual bad events are dropped and counted so one broken * event never costs the rest of the batch. */ export function parseCollectEnvelope(body: unknown): | { ok: true; envelope: ParsedEnvelope } | { ok: false; error: string } { if (body === null || typeof body !== "object" || Array.isArray(body)) { return { ok: false, error: "Body must be a JSON object" }; } const raw = body as Record; if (!Array.isArray(raw.events) || raw.events.length === 0) { return { ok: false, error: "events must be a non-empty array" }; } if (raw.events.length > MAX_EVENTS_PER_BATCH) { return { ok: false, error: `events exceeds ${MAX_EVENTS_PER_BATCH}` }; } const now = Date.now(); const events: ValidatedEvent[] = []; let dropped = 0; for (const candidate of raw.events as unknown[]) { if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) { dropped += 1; continue; } const event = candidate as Record; if (!isAnalyticsEventType(event.type)) { dropped += 1; continue; } let tsMs = now; if (typeof event.ts === "number" && Number.isFinite(event.ts)) { if (event.ts > now + MAX_FUTURE_SKEW_MS || event.ts < now - MAX_PAST_AGE_MS) { dropped += 1; continue; } tsMs = event.ts; } events.push({ ts: new Date(tsMs), type: event.type, path: clampPath(event.path), element: clampJsonObject(event.element), data: clampJsonObject(event.data), }); } return { ok: true, envelope: { sid: clampId(raw.sid), aid: clampId(raw.aid), events, dropped, }, }; }