/** * The analytics query model (RFC-0006 §7.2). Every Studio screen and MCP tool asks one of these * five queries; each store compiles them (SQLite, Workers Analytics Engine, rollups), so no screen * ever writes SQL. Everything a query may carry is an id, an enum, a bounded integer or an instant, * checked by `assertAnalyticsQuery` before any compiler sees it. */ import type { AnalyticsChannel, AnalyticsDevice, AnalyticsEvent } from "@cloudhal/core-contracts"; export type Id = string; /** ISO instants (or `YYYY-MM-DD` dates), UTC, half-open: `[from, to)`. */ export interface Range { readonly from: string; readonly to: string; } export interface Filter { readonly node?: Id; readonly channel?: AnalyticsChannel; readonly country?: string; readonly device?: AnalyticsDevice; } export declare const DIMENSIONS: readonly ["node", "refHost", "channel", "utmSource", "utmMedium", "utmCampaign", "country", "device", "browser", "os"]; export type Dimension = (typeof DIMENSIONS)[number]; export declare const RENDER_REPORTS: readonly ["errors", "redirects", "crawlers"]; export type RenderReport = (typeof RENDER_REPORTS)[number]; export interface SummaryQuery { readonly kind: "summary"; readonly siteId: Id; readonly range: Range; readonly filter?: Filter; } export interface SeriesQuery { readonly kind: "series"; readonly siteId: Id; readonly range: Range; readonly interval: "hour" | "day"; readonly filter?: Filter; } export interface TopQuery { readonly kind: "top"; readonly siteId: Id; readonly range: Range; readonly dimension: Dimension; readonly limit: number; readonly filter?: Filter; } export interface VitalsQuery { readonly kind: "vitals"; readonly siteId: Id; readonly range: Range; /** `channel` is refused: vitals events carry no channel. */ readonly filter?: Filter; } export interface RendersQuery { readonly kind: "renders"; readonly siteId: Id; readonly range: Range; readonly statuses: RenderReport; readonly limit: number; } export type AnalyticsQuery = SummaryQuery | SeriesQuery | TopQuery | VitalsQuery | RendersQuery; export interface SummaryData { readonly pageviews: number; readonly visits: number; /** Daily unique visitors, summed over the range's days; `null` when no view carried a hash. */ readonly visitors: number | null; /** * Pages the site Worker rendered for people: render events with status `200` (published HTML, * which is a cache miss by definition), no known crawler and not a bot, weighted by * `sampleOneIn`; the node, country and device filters apply. `null` when unknown: under a * `channel` filter (render events carry no channel), and from rollups that do not keep it * (filtered summaries, and days rolled up before it was kept). Feeds `estimatedCacheHitRatio`. */ readonly renders: number | null; /** * Page views whose beacon carried GPC or DNT (`privacySignal`), under the same filter: counted, * never hashed, so `visitors` is a lower bound. `null` from rollups that do not keep it (filtered * summaries, and days rolled up before it was kept). Views recorded before the field existed * count as without a signal. */ readonly signals: number | null; } /** Share of page views that carried a privacy signal (0–1, three decimals); `null` when unknown. */ export declare function privacySignalShare(summary: Pick): number | null; /** * The estimated cache-hit ratio (RFC-0006 §5.4): `1 − renders ÷ page views`, clamped to [0, 1] and * rounded to three decimals. An **estimate**: page views come from the script (visitors without * JavaScript, or with it blocked, are not counted) while renders are counted by the Worker, and * only a zone sees real edge cache statistics. `null` without page views or without a render count. * Meaningful only where an edge cache sits in front of the Worker (Cloudflare, `store: "wae"`). */ export declare function estimatedCacheHitRatio(summary: Pick): number | null; export interface SeriesPoint { /** Bucket start, `YYYY-MM-DDTHH:MM:SSZ` (UTC). Every bucket of the range is present. */ readonly t: string; readonly pageviews: number; readonly visits: number; } export interface SeriesData { readonly interval: "hour" | "day"; readonly points: readonly SeriesPoint[]; } export interface TopRow { readonly key: string; readonly pageviews: number; readonly visits: number; } export interface TopData { readonly dimension: Dimension; /** Ordered by page views (descending), then key; rows without a value are left out. */ readonly rows: readonly TopRow[]; } export declare const VITALS_METRICS: readonly ["lcp", "inp", "cls", "ttfb", "fcp"]; export type VitalsMetricName = (typeof VITALS_METRICS)[number]; /** web.dev thresholds: good ≤ `good`, poor > `poor` (ms; CLS unitless). */ export declare const VITALS_THRESHOLDS: Readonly>; export interface VitalsMetric { readonly metric: VitalsMetricName; /** Weighted 75th percentile (nearest rank); `null` without samples. */ readonly p75: number | null; /** Page views represented (each sample weighs its `sampleOneIn`). */ readonly samples: number; /** Weighted counts per rating; `null` when the source does not keep them. */ readonly good: number | null; readonly needsImprovement: number | null; readonly poor: number | null; } export interface VitalsData { readonly metrics: readonly VitalsMetric[]; } export interface RenderErrorRow { /** Requested path as received: percent-encoded ASCII, visitor-controlled, shown as plain text. */ readonly path: string; readonly status: number; /** Same-site page that linked here, when known. */ readonly refPath: string | null; readonly hits: number; /** Latest hit; `null` from rollups. */ readonly lastSeen: string | null; } export interface RenderRedirectRow { readonly path: string; readonly status: number; readonly redirectTo: string; readonly nodeId: string | null; readonly hits: number; } export type CrawlerClass = "search" | "ai" | "social" | "monitor" | "other"; export interface RenderCrawlerRow { readonly crawler: string; readonly class: CrawlerClass; readonly hits: number; } export type RendersData = { readonly report: "errors"; readonly rows: readonly RenderErrorRow[]; } | { readonly report: "redirects"; readonly rows: readonly RenderRedirectRow[]; } | { readonly report: "crawlers"; readonly rows: readonly RenderCrawlerRow[]; }; type RendersDataFor = Extract; export type AnalyticsData = Q extends SummaryQuery ? SummaryData : Q extends SeriesQuery ? SeriesData : Q extends TopQuery ? TopData : Q extends VitalsQuery ? VitalsData : Q extends RendersQuery ? RendersDataFor : never; export type AnalyticsSource = "live" | "rollups" | "mixed"; export interface AnalyticsResult { readonly data: AnalyticsData; readonly source: AnalyticsSource; /** Approximate: sampled or distinct counts, approximate quantiles, or merged daily percentiles. */ readonly estimated: boolean; /** Part of the range could not be read (budget spent, or older than live data and not rolled up). */ readonly partial?: boolean; } export interface AnalyticsWriter { /** Never throws into the caller; returns at once (WAE) or after queueing one insert (SQL). */ write(event: AnalyticsEvent): void; } export interface AnalyticsReader { readonly kind: "wae" | "sql" | "memory" | "rollups" | "composite"; /** Runs one query of the model; `source` says where the answer came from. */ query(q: Q): Promise>; } /** A store that both records and answers (SQLite/D1 and the in-memory fake). */ export interface AnalyticsStore extends AnalyticsWriter, AnalyticsReader { readonly kind: "wae" | "sql" | "memory"; } /** The daily budget of uncached live queries (RFC-0006 §7.7). */ export interface QueryBudget { /** Spends one query; `false` once the day's budget is spent. */ take(now: Date): Promise; } export declare const ID_RE: RegExp; export declare const COUNTRY_RE: RegExp; export declare const CHANNELS: readonly AnalyticsChannel[]; export declare const DEVICES: readonly AnalyticsDevice[]; /** Live data reaches back this far (WAE keeps 3 months); a raw-store query spans at most this. */ export declare const MAX_LIVE_DAYS = 92; /** Hourly series cover at most a week (168 buckets). */ export declare const MAX_HOURLY_DAYS = 7; /** Rows per top list or render report. */ export declare const MAX_LIMIT = 1000; /** Parses a range bound: an ISO instant with zone, or a `YYYY-MM-DD` date (UTC midnight). */ export declare function parseInstant(value: unknown, label?: string): Date; export interface ParsedRange { readonly from: Date; readonly to: Date; } export declare function parseRange(range: unknown, maxDays?: number): ParsedRange; export declare function assertFilter(filter: unknown, kind: AnalyticsQuery["kind"]): void; /** * Checks a query against the model: ids by the `Id` pattern, enums by the contract, ranges parse and * stay within `maxDays`, limits are bounded. Returns the parsed range. Throws `AnalyticsQueryError`. */ export declare function assertAnalyticsQuery(q: unknown, options?: { maxDays?: number; }): ParsedRange; /** Stable key for a query (cache keys): sorted fields, range normalised to instants. */ export declare function queryKey(q: AnalyticsQuery, range: ParsedRange): string; /** `YYYY-MM-DD` of a UTC day. */ export declare function utcDay(d: Date): string; export declare function startOfUtcDay(d: Date): Date; export declare function addDays(d: Date, days: number): Date; /** `YYYY-MM-DDTHH:MM:SSZ`, with milliseconds only when they are not zero. */ export declare function isoInstant(d: Date): string; /** Bucket starts covering `[from, to)`: the first is `from` floored to the interval. */ export declare function bucketStarts(range: ParsedRange, interval: "hour" | "day"): Date[]; /** Parses a bucket value returned by a store (`YYYY-MM-DD HH:MM:SS`, ISO, or a date) to an instant. */ export declare function parseBucket(value: unknown): string | undefined; /** Every bucket of the range, zero where the store had no row. */ export declare function fillSeries(range: ParsedRange, interval: "hour" | "day", rows: readonly { t: string; pageviews: number; visits: number; }[]): SeriesPoint[]; /** Coerces a numeric column (some stores answer 64-bit integers as strings). */ export declare function num(value: unknown): number; /** Orders top rows: page views descending, then key ascending (code-unit order, as SQLite). */ export declare function compareTopRows(a: TopRow, b: TopRow): number; /** Ratings and p75 from weighted samples, nearest rank: the smallest value whose cumulative weight * reaches three quarters of the total. Shared by the in-memory store and the rollup merge. */ export declare function weightedP75(samples: readonly { x: number; w: number; }[]): number | null; export declare function vitalsMetric(metric: VitalsMetricName, p75: number | null, samples: number, good: number | null, poor: number | null): VitalsMetric; export {};