import { MetricCollector } from './collectors/collector.js'; import { DebugPane } from './debug/types.js'; /** * Primitive value types that collectors can return. * * Every field in a {@link ServerStats} snapshot is one of these types. * Custom collectors must also return records of these values. */ export type MetricValue = string | number | boolean; /** * A point-in-time snapshot of all server metrics. * * Produced by {@link StatsEngine.collect} each tick and broadcast to clients * via Transmit (SSE) or polled via the HTTP endpoint. * * Each collector contributes a subset of these fields. Fields will be `0`, * `false`, or `''` when the responsible collector is not configured or when * the underlying service is unavailable. */ export interface ServerStats { /** Node.js version string (e.g. `"v20.11.0"`). */ nodeVersion: string; /** Process uptime in **seconds**. */ uptime: number; /** V8 heap memory currently in use, in **bytes**. */ memHeapUsed: number; /** V8 heap memory allocated (committed), in **bytes**. */ memHeapTotal: number; /** * Resident Set Size in **bytes**. * * Total OS memory footprint of the process, including heap, stack, * and native allocations. */ memRss: number; /** * CPU usage as a percentage of **one** CPU core (0 -- 100). * * Measured as the ratio of user + system CPU time to wall-clock time * since the last collection tick. */ cpuPercent: number; /** * Event loop latency in **milliseconds**. * * Mean delay between a timer's scheduled execution time and its actual * execution time, sampled via `monitorEventLoopDelay`. * * | Range | Meaning | * |----------|------------------------------| * | < 20 ms | Healthy | * | 20-50 ms | Under load (amber threshold) | * | > 50 ms | Blocked (red threshold) | */ eventLoopLag: number; /** Unix timestamp in **milliseconds** when this snapshot was taken. */ timestamp: number; /** * HTTP requests per second over the rolling window. * * Defaults to a 60-second window; configurable via * `httpCollector({ windowMs })`. */ requestsPerSecond: number; /** * Average HTTP response time in **milliseconds** over the rolling window. * * | Range | Meaning | * |-----------|------------------------------| * | < 200 ms | Healthy | * | 200-500ms | Slow (amber threshold) | * | > 500 ms | Critical (red threshold) | */ avgResponseTimeMs: number; /** * Server error rate as a **percentage** (0 -- 100). * * Ratio of 5xx responses to total responses in the rolling window. * * | Range | Meaning | * |-------|------------------------------| * | < 1% | Healthy | * | 1-5% | Elevated (amber threshold) | * | > 5% | Critical (red threshold) | */ errorRate: number; /** Number of currently open HTTP connections. */ activeHttpConnections: number; /** Database pool connections currently checked out. */ dbPoolUsed: number; /** Database pool connections sitting idle and available. */ dbPoolFree: number; /** Queries waiting for a pool connection to become available. */ dbPoolPending: number; /** Maximum pool size configured for the connection. */ dbPoolMax: number; /** `true` if Redis responded to PING successfully. */ redisOk: boolean; /** Redis server memory usage in **megabytes**. */ redisMemoryUsedMb: number; /** Number of clients currently connected to Redis. */ redisConnectedClients: number; /** Total number of keys across all Redis databases. */ redisKeysCount: number; /** * Redis cache hit rate as a **percentage** (0 -- 100). * * Calculated as `keyspace_hits / (keyspace_hits + keyspace_misses)`. * * | Range | Meaning | * |-------|------------------------------| * | > 90% | Healthy | * | 70-90%| Suboptimal (amber threshold) | * | < 70% | Poor (red threshold) | */ redisHitRate: number; /** Number of jobs currently being processed. */ queueActive: number; /** Number of jobs waiting to be picked up by a worker. */ queueWaiting: number; /** Number of jobs scheduled for future execution. */ queueDelayed: number; /** Number of jobs that have permanently failed. */ queueFailed: number; /** Number of BullMQ worker processes connected to the queue. */ queueWorkerCount: number; /** OS load average over the last 1 minute. */ systemLoadAvg1m: number; /** OS load average over the last 5 minutes. */ systemLoadAvg5m: number; /** OS load average over the last 15 minutes. */ systemLoadAvg15m: number; /** Total system (OS) memory in **megabytes**. */ systemMemoryTotalMb: number; /** Free system (OS) memory in **megabytes**. */ systemMemoryFreeMb: number; /** System (OS) uptime in **seconds**. */ systemUptime: number; /** Number of active user sessions (from `sessions` table). */ onlineUsers: number; /** Number of webhook events with `"pending"` status. */ pendingWebhooks: number; /** Number of scheduled emails with `"pending"` status. */ pendingEmails: number; /** Number of `error` and `fatal` log entries in the last 5 minutes. */ logErrorsLast5m: number; /** Number of `warn` log entries in the last 5 minutes. */ logWarningsLast5m: number; /** Total log entries (all levels) in the last 5 minutes. */ logEntriesLast5m: number; /** Log entries per minute, averaged over the last 5 minutes. */ logEntriesPerMinute: number; } /** * Rolling log statistics computed by {@link LogStreamService}. * * Covers a 5-minute sliding window. Used internally by * `logCollector()` and exposed via `LogStreamService.getLogStats()`. */ export interface LogStats { /** Number of `error` (50) and `fatal` (60) entries in the window. */ errorsLast5m: number; /** Number of `warn` (40) entries in the window. */ warningsLast5m: number; /** Total entries (all levels) in the window. */ entriesLast5m: number; /** Entries per minute, averaged over the window. */ entriesPerMinute: number; } /** * Configuration for the dev toolbar overlay. * * The dev toolbar adds a debug panel with SQL query inspection, * emitted event tracking, route table, and live logs. Only active * in non-production environments. * * @example * ```ts * export default defineConfig({ * devToolbar: { * enabled: true, * maxQueries: 500, * slowQueryThresholdMs: 100, * panes: [myCustomPane], * }, * }) * ``` */ export interface DevToolbarOptions { /** Enable the dev toolbar. Has no effect in production. */ enabled: boolean; /** * Maximum number of SQL queries to keep in the ring buffer. * @default 500 */ maxQueries?: number; /** * Maximum number of emitted events to keep in the ring buffer. * @default 200 */ maxEvents?: number; /** * Maximum number of captured emails to keep in the ring buffer. * @default 100 */ maxEmails?: number; /** * Queries slower than this threshold (in **milliseconds**) are * highlighted in the toolbar. * @default 100 */ slowQueryThresholdMs?: number; /** * Additional custom panes to display in the debug panel. * * Each pane fetches JSON from an endpoint you define and renders * a table based on column definitions. * * @see {@link DebugPane} */ panes?: DebugPane[]; /** * Persist debug data (queries, events, emails) to disk so it * survives server restarts. * * - `false` — no persistence * - `true` — persist to `.adonisjs/server-stats/debug-data.json` * - `string` — persist to the given path (relative to app root) * * @default false */ persistDebugData?: boolean | string; /** * Enable per-request tracing with timeline visualization. * * When enabled, each HTTP request is traced with a waterfall * of all operations (DB queries, events, mail) that occurred * during the request. * * @default true */ tracing?: boolean; /** * Maximum number of request traces to keep in the ring buffer. * @default 200 */ maxTraces?: number; /** * Enable the full-page dashboard. * Serves a standalone HTML page at `dashboardPath`. * @default false */ dashboard?: boolean; /** * URL path for the full-page dashboard. * Must start with `/`. * @default '/__stats' */ dashboardPath?: string; /** * Data retention period in days for historical persistence. * Records older than this are auto-pruned on startup and periodically. * @default 7 */ retentionDays?: number; /** * Size cap in MB for the SQLite database's live data. When exceeded, * the hourly cleanup deletes the oldest records — regardless of age — * until usage drops below the cap, effectively shortening the retention * window when write volume outruns `retentionDays`. Set to `0` to * disable the cap. * @default 500 */ maxDbSizeMb?: number; /** * Path to the SQLite database file for historical persistence. * Relative to app root. * @default '.adonisjs/server-stats/dashboard.sqlite3' */ dbPath?: string; /** * URL prefixes to exclude from tracing and dashboard persistence. * * Requests matching these prefixes will still count toward HTTP * metrics (req/s, latency) but won't appear in the timeline or * be persisted to the dashboard. * * The stats endpoint (`config.endpoint`) is always excluded * automatically when tracing is enabled. * * @example * ```ts * excludeFromTracing: ['/admin/api/debug', '/admin/api/server-stats'] * ``` * * @default ['/admin/api/debug', '/admin/api/server-stats'] */ excludeFromTracing?: string[]; /** * Base path for the debug toolbar API endpoints. * * The debug panel fetches data from endpoints under this path * (e.g. `{debugEndpoint}/queries`, `{debugEndpoint}/events`). * * Must start with `/`. * * @default '/admin/api/debug' */ debugEndpoint?: string; /** * Client-side rendering library for the Edge integration. * * - `'preact'` — lightweight Preact + React-compat components (default) * - `'vue'` — Vue 3 components (ideal if your app already uses Vue / Inertia) * * Both renderers share the same CSS and JSON config; only the JS bundle differs. * * @default 'preact' */ renderer?: 'preact' | 'vue'; } /** * Debug toolbar configuration. * * Controls the debug panel overlay that shows SQL queries, events, * emails, routes, logs, and per-request tracing. Pass `true` to * `toolbar` to enable with all defaults, or an object to customize. * * @example * ```ts * export default defineConfig({ * toolbar: { * slowQueryThreshold: 200, * tracing: true, * persist: true, * }, * }) * ``` */ export interface ToolbarConfig { /** * Queries slower than this threshold (in **milliseconds**) are * highlighted in red in the debug panel. * * @default 100 */ slowQueryThreshold?: number; /** * Enable per-request tracing with timeline visualization. * * When enabled, each HTTP request is traced with a waterfall of all * operations (DB queries, events, custom spans) that occurred during * the request. Adds a "Timeline" tab to the debug panel. * * Uses `AsyncLocalStorage` to automatically correlate DB queries and * `console.warn` calls to the request that triggered them. * * @default true */ tracing?: boolean; /** * Persist debug data (queries, events, emails) to disk so it * survives server restarts. * * Data is saved to `.adonisjs/server-stats/debug-data.json` * (customizable via `advanced.persistPath`). Flushed every 30 * seconds and on graceful shutdown. * * @default false */ persist?: boolean; /** * Custom tabs to add to the debug panel. * * Each pane fetches JSON from an endpoint you define and renders * it as a table with configurable columns, search, and formatting. * * @see {@link DebugPane} * * @example * ```ts * panes: [{ * id: 'webhooks', * label: 'Webhooks', * endpoint: '/admin/api/debug/webhooks', * columns: [ * { key: 'event', label: 'Event', searchable: true }, * { key: 'status', label: 'Status', format: 'badge', * badgeColorMap: { delivered: 'green', failed: 'red' } }, * ], * }] * ``` */ panes?: DebugPane[]; /** * URL prefixes to exclude from tracing and dashboard persistence. * * Requests matching these prefixes still count toward HTTP metrics * (req/s, latency) but won't appear in the timeline or be stored * in the dashboard. The stats endpoint is always excluded automatically. * * @default ['/admin/api/debug', '/admin/api/server-stats'] */ excludeFromTracing?: string[]; } /** * Full-page dashboard configuration. * * The dashboard provides historical data, charts, query analysis, and * integration inspectors — all persisted to a local SQLite database. * Pass `true` to `dashboard` to enable at `/__stats` with defaults, * or an object to customize. * * Requires `better-sqlite3` as a peer dependency. If not installed, * the dashboard disables itself gracefully. * * @example * ```ts * export default defineConfig({ * dashboard: { * path: '/admin/dashboard', * retentionDays: 14, * }, * }) * ``` */ export interface DashboardConfig { /** * URL path where the dashboard page is served. * * Must start with `/`. All dashboard API routes are registered * under `{path}/api/*`. * * @default '/__stats' */ path?: string; /** * How many days of historical data to keep in SQLite. * * Records older than this are automatically pruned on startup * and periodically during runtime. * * @default 7 */ retentionDays?: number; /** * Size cap in MB for the SQLite database's live data. * * When exceeded, the cleanup deletes the oldest records — regardless * of age — until usage drops below the cap. This bounds disk usage * when write volume (tracing, verbose query logging) outruns what * `retentionDays` alone would keep small. Set to `0` to disable. * * @default 500 */ maxDbSizeMb?: number; } /** * Access-control callback signature. * * May be sync or async — the route guard awaits it. An async guard is the usual * shape once the check has to consult `ctx.auth` or the database. * * One caveat: the `@serverStats()` Edge tag evaluates the guard synchronously * while rendering the template, so with an **async** guard the toolbar hides * itself rather than risk showing when it shouldn't. The HTTP routes await it * properly either way — only the cosmetic bar is affected. */ export type AccessGuard = (ctx: import('@adonisjs/core/http').HttpContext) => boolean | Promise; /** * Which capture subsystems are active. * * Each one hooks a global: queries and events subscribe to the Lucid/app * emitter, emails subscribe to the mail events, traces wrap every request in * `AsyncLocalStorage`. Turning one off means its collector is never subscribed, * so it costs nothing — its dashboard pane simply stays empty. * * Outside production every field defaults to `true`. In production every field * defaults to **`false`** and must be opted into individually. */ export interface CaptureConfig { /** SQL text, bindings, and timings for every query. */ queries?: boolean; /** Application events, linked to the request that follows them and persisted with it. */ events?: boolean; /** Sent mail, including subject and body. */ emails?: boolean; /** Per-request spans and the request timeline. */ traces?: boolean; /** Log lines written into the dashboard's SQLite store. */ logs?: boolean; } /** * Opt in to running the dashboard in production. * * By default this package registers **no routes** when `NODE_ENV=production` * and never builds the debug or dashboard stores. Setting `enabled: true` lifts * that, but only with an {@link ServerStatsConfig.authorize} guard in place — * `unsafeAllowNoAuth` is ignored in production. * * Data capture stays **off** unless you ask for it. Without any `capture` * flags you still get the request list, the overview, and the charts (those * come from request rows and 1-minute metric buckets), at a small fraction of * the write volume of a full dev-mode capture. * * @example * ```ts * export default defineConfig({ * authorize: async (ctx) => (await ctx.auth.check()) && ctx.auth.user?.isAdmin === true, * dashboard: true, * production: { * enabled: true, * capture: { queries: true }, * retentionDays: 3, * }, * }) * ``` */ export interface ProductionConfig { /** * Register routes and build the dashboard when `NODE_ENV=production`. * * Requires an `authorize` guard — without one the routes are still not * registered, and a warning explains why. * * @default false */ enabled?: boolean; /** * Which capture subsystems to switch on. Every field defaults to `false` in * production, so capture is opt-in one subsystem at a time. * * @see {@link CaptureConfig} */ capture?: CaptureConfig; /** * How many days of history to keep in SQLite, overriding the usual default * of 7. Retention deletes rows hourly and returns freed pages to the OS * incrementally — watch actual size via the dashboard's storage panel. * * @default 3 */ retentionDays?: number; /** * Size cap in MB for the SQLite database's live data in production, * overriding the usual default. When exceeded, the hourly cleanup deletes * the oldest records — regardless of age — until usage drops below the * cap. Set to `0` to disable. * * @default 500 */ maxDbSizeMb?: number; } /** * Advanced options that most users never need to touch. * * These control internal behavior like buffer sizes, file paths, * channel names, and the client-side rendering library for Edge. * * @example * ```ts * export default defineConfig({ * advanced: { * maxQueries: 1000, * renderer: 'vue', * dbPath: 'tmp/stats.sqlite3', * }, * }) * ``` */ export interface AdvancedConfig { /** * Skip all metric collection during test runs. * * Prevents collectors from running database queries, connecting * to Redis, or spawning timers during tests. * * @default true */ skipInTest?: boolean; /** * Transmit channel name for SSE broadcasting. * * Clients subscribe to this channel to receive real-time stats * updates. Only relevant when `realtime: true`. * * @default 'admin/server-stats' */ channelName?: string; /** * Base URL path for the debug panel API endpoints. * * The debug panel fetches data from endpoints under this path * (e.g. `{debugEndpoint}/queries`, `{debugEndpoint}/events`). * * @default '/admin/api/debug' */ debugEndpoint?: string; /** * Client-side rendering library for the Edge tag integration. * * - `'preact'` — lightweight Preact + React-compat (smaller bundle) * - `'vue'` — Vue 3 components (ideal if your app already uses Vue) * * Only affects the `@serverStats()` Edge tag. The standalone React * and Vue npm imports are unaffected by this setting. * * @default 'preact' */ renderer?: 'preact' | 'vue'; /** * Path to the SQLite database file for dashboard persistence. * * Relative to app root. The directory is created automatically * if it doesn't exist. Add it to `.gitignore`. * * @default '.adonisjs/server-stats/dashboard.sqlite3' */ dbPath?: string; /** * Path for persisted debug data (queries, events, emails). * * Relative to app root. Only used when `toolbar.persist` is enabled. * Overrides the default path. * * @default '.adonisjs/server-stats/debug-data.json' */ persistPath?: string; /** * Maximum SQL queries to keep in the debug panel ring buffer. * * @default 500 */ maxQueries?: number; /** * Maximum application events to keep in the debug panel ring buffer. * * @default 200 */ maxEvents?: number; /** * Maximum captured emails to keep in the debug panel ring buffer. * * @default 100 */ maxEmails?: number; /** * Maximum request traces to keep in the debug panel ring buffer. * * @default 200 */ maxTraces?: number; /** * Allow-list prefix for the dashboard's cache inspector. * * Scopes which Redis keys the Cache tab may list, read, and delete * (e.g. `'myapp:cache:'`). Unset keeps full access in development for * back-compat, but in production single-key reads and deletes are * refused until a prefix is configured — a production dashboard must * not be able to read session keys or delete rate-limit counters. * * The `SERVER_STATS_CACHE_KEY_PREFIX` env var is used as a fallback. */ cacheKeyPrefix?: string; /** * Redis pub/sub channel for the cross-process email bridge. * * Queue workers publish captured mail on this channel and the web * process persists it. On a Redis instance shared between apps or * tenants, namespace this (e.g. `myapp:server-stats:emails`) so * other subscribers cannot read your outbound mail. * * @default 'adonisjs-server-stats:emails' */ emailBridgeChannel?: string; } /** * Top-level configuration for `adonisjs-server-stats`. * * Pass this to {@link defineConfig} in `config/server_stats.ts`. * All fields are optional — `defineConfig({})` works out of the box. * * **Recommended fields** (use these): * - `pollInterval`, `realtime`, `statsEndpoint`, `authorize` * - `collectors`, `toolbar`, `dashboard`, `advanced`, `verbose` * * **Deprecated fields** (still work, but will be removed in v2): * - `intervalMs` → `pollInterval` * - `transport` → `realtime` * - `endpoint` → `statsEndpoint` * - `shouldShow` → `authorize` * - `devToolbar` → `toolbar` + `dashboard` + `advanced` * - `channelName` → `advanced.channelName` * - `skipInTest` → `advanced.skipInTest` * * @example * ```ts * // Zero config — auto-detects everything * import { defineConfig } from 'adonisjs-server-stats' * export default defineConfig({}) * ``` * * @example * ```ts * // Common production setup * import { defineConfig } from 'adonisjs-server-stats' * export default defineConfig({ * authorize: (ctx) => ctx.auth?.user?.role === 'admin', * toolbar: true, * dashboard: true, * }) * ``` */ export interface ServerStatsConfig { /** * How often (in **milliseconds**) to run all collectors and * broadcast updated stats. * * Lower values give more responsive dashboards but increase * CPU and network overhead. * * @default 3000 * @deprecated Use {@link pollInterval} instead. Will be removed in the next major version. */ intervalMs?: number; /** * How collected stats are pushed to connected clients. * * - `'transmit'` -- broadcast via AdonisJS Transmit (SSE). * Requires `@adonisjs/transmit` as a peer dependency. * - `'none'` -- disable real-time push; clients must poll the * HTTP endpoint. * * @default 'transmit' * @deprecated Use {@link realtime} instead (`true` = transmit, `false` = none). Will be removed in the next major version. */ transport?: 'transmit' | 'none'; /** * Transmit channel name used for SSE broadcasting. * * Clients subscribe to this channel to receive live updates. * Only relevant when `transport` is `'transmit'`. * * @default 'admin/server-stats' * @deprecated Use `advanced.channelName` instead. Will be removed in the next major version. */ channelName?: string; /** * HTTP endpoint path that returns the latest stats snapshot as JSON. * * Set to `false` to disable the built-in endpoint entirely * (e.g. if you provide your own controller). * * @default '/admin/api/server-stats' * @deprecated Use {@link statsEndpoint} instead. Will be removed in the next major version. */ endpoint?: string | false; /** * Collector instances that will be run each tick, or `'auto'` * to let the package auto-detect available collectors. * * When an array is provided, order does not matter -- all * collectors run in parallel via `Promise.all`. Each collector * contributes a subset of fields to the merged * {@link ServerStats} snapshot. * * @default 'auto' * * @example * ```ts * collectors: [ * processCollector(), * systemCollector(), * httpCollector({ maxRecords: 10_000 }), * redisCollector(), * ] * ``` */ collectors?: 'auto' | MetricCollector[]; /** * Skip metric collection during test runs (`NODE_ENV=test`). * * Prevents collectors from interfering with test isolation * and speeds up the test suite. * * @default true * @deprecated Use `advanced.skipInTest` instead. Will be removed in the next major version. */ skipInTest?: boolean; /** * Callback invoked after every collection tick with the merged * stats snapshot. * * Useful for custom logging, alerting, or forwarding metrics * to external systems. * * @example * ```ts * onStats: (stats) => { * if (stats.cpuPercent && stats.cpuPercent > 90) { * logger.warn('High CPU usage detected') * } * } * ``` */ onStats?: (stats: Partial) => void; /** * Dev toolbar configuration. * * Adds a debug panel with SQL queries, emitted events, route * table, and live logs. * * @see {@link DevToolbarOptions} * @deprecated Use {@link toolbar}, {@link dashboard}, and {@link advanced} instead. Will be removed in the next major version. */ devToolbar?: DevToolbarOptions; /** * Per-request callback that decides whether the stats bar should * render for the current request. * * Receives the AdonisJS `HttpContext` and must return `true` to * show the bar. When not set, `@serverStats()` always renders. * * The callback is evaluated lazily at render time (after auth * middleware has run), so `ctx.auth.user` is available. * * @example * ```ts * // Only show for admin users * shouldShow: (ctx) => !!ctx.auth?.user?.isAdmin * ``` * * @example * ```ts * // Only in development * shouldShow: () => process.env.NODE_ENV === 'development' * ``` * * @deprecated Use {@link authorize} instead. Will be removed in the next major version. */ shouldShow?: AccessGuard; /** * How often (in **milliseconds**) to run all collectors and * broadcast updated stats. * * Lower values give more responsive dashboards but increase * CPU and network overhead. * * @default 3000 */ pollInterval?: number; /** * Enable real-time updates via Server-Sent Events (SSE). * * - `true` — broadcast stats via AdonisJS Transmit (requires * `@adonisjs/transmit` as a peer dependency) * - `false` — disable SSE; clients poll the HTTP endpoint instead * * @default true */ realtime?: boolean; /** * HTTP endpoint path that returns the latest stats snapshot as JSON. * * The stats bar polls this endpoint at the configured interval. * Set to `false` to disable the built-in endpoint entirely * (e.g. if you provide your own controller). * * @default '/admin/api/server-stats' */ statsEndpoint?: string | false; /** * Per-request access control callback. * * Gates **all** auto-registered routes (stats bar, debug panel, * dashboard). Return `true` to allow access, `false` to deny (403). * * Runs after middleware, so `ctx.auth` is available. * * @example * ```ts * // Only admins * authorize: (ctx) => ctx.auth?.user?.role === 'admin' * ``` * * @example * ```ts * // Only in development * authorize: () => process.env.NODE_ENV === 'development' * ``` */ authorize?: AccessGuard; /** * Register the sensitive dashboard/debug/stats routes WITHOUT any access * guard when no {@link authorize} callback is provided. * * The package fails closed: without either {@link authorize} or this flag, * the sensitive routes are **not** registered. Enabling this exposes the * dashboard — which can surface secrets, email bodies, and SQL — to anyone * who can reach it. Local development only. * * @default false */ unsafeAllowNoAuth?: boolean; /** * Enable the debug panel (toolbar overlay). * * - `true` — enable with sensible defaults (tracing on, no persistence) * - `false` — disable the debug panel * - `ToolbarConfig` — enable with custom settings * * The debug panel adds tabs for SQL queries, events, emails, routes, * logs, and per-request tracing. Only active in non-production. * * @see {@link ToolbarConfig} * * @example * ```ts * toolbar: true * // or * toolbar: { tracing: true, persist: true, slowQueryThreshold: 200 } * ``` */ toolbar?: boolean | ToolbarConfig; /** * Enable the full-page dashboard at `/__stats`. * * - `true` — enable at the default path (`/__stats`) * - `false` — disable the dashboard * - `DashboardConfig` — enable with custom path or retention * * The dashboard provides historical request data, charts, query * analysis with EXPLAIN plans, cache/queue inspection, and more. * Requires `better-sqlite3` for local SQLite storage. * * @see {@link DashboardConfig} * * @example * ```ts * dashboard: true * // or * dashboard: { path: '/admin/stats', retentionDays: 14 } * ``` */ dashboard?: boolean | DashboardConfig; /** * Restrict all server-stats routes to a specific domain or subdomain. * * When set, routes are only matched when the request's `Host` header * matches the given domain. Useful when admin routes live on a * dedicated subdomain (e.g. `admin.example.com`). * * Supports dynamic subdomains using `:param` syntax * (e.g. `':tenant.example.com'`). * * Pass a bare host — a protocol, path, or port (`'https://admin.example.com'`, * `'admin.example.com:3333'`) yields routes that match nothing. * * Note that the `@serverStats()` toolbar and the React/Vue components request * relative URLs, so they only work on pages served from this domain. * * @example * ```ts * // Fixed subdomain * domain: 'admin.example.com' * ``` * * @example * ```ts * // Dynamic subdomain * domain: ':tenant.example.com' * ``` */ domain?: string; /** * Opt in to running in production, where this package otherwise registers * nothing at all. * * Requires an {@link authorize} guard, and leaves data capture off unless you * enable it per subsystem. * * @see {@link ProductionConfig} * * @example * ```ts * production: { enabled: true, capture: { queries: true } } * ``` */ production?: ProductionConfig; /** * Advanced options for fine-tuning internal behavior. * * Controls buffer sizes, file paths, channel names, and the * Edge rendering library. Most users don't need to touch these. * * @see {@link AdvancedConfig} */ advanced?: AdvancedConfig; /** * Enable verbose logging during initialization. * * When `true`, the package logs detailed info messages about each * boot step (SQLite init, migrations, route registration, etc.). * When `false` (the default), only warnings are logged. * * @default false */ verbose?: boolean; } /** * Fully resolved configuration with all defaults applied. * * This is the return type of {@link defineConfig}. Consumers that * read from `app.config.get('server_stats')` receive this type, * so all required fields are guaranteed to be present. */ export interface ResolvedServerStatsConfig { /** Collection interval in milliseconds. Always present after `defineConfig()`. */ intervalMs: number; /** Transport mode. Always present after `defineConfig()`. */ transport: 'transmit' | 'none'; /** Transmit channel name. Always present after `defineConfig()`. */ channelName: string; /** HTTP endpoint path or `false` to disable. Always present after `defineConfig()`. */ endpoint: string | false; /** Collectors array or `'auto'`. Always present after `defineConfig()`. */ collectors: 'auto' | MetricCollector[]; /** Whether to skip collection in test environments. Always present after `defineConfig()`. */ skipInTest: boolean; /** Optional per-tick callback. */ onStats?: (stats: Partial) => void; /** Optional dev toolbar configuration. */ devToolbar?: DevToolbarOptions; /** Optional access-control callback. */ shouldShow?: AccessGuard; /** Collection interval in milliseconds (new name for {@link intervalMs}). */ pollInterval?: number; /** Whether real-time (SSE) broadcasting is enabled (new name for {@link transport}). */ realtime?: boolean; /** HTTP endpoint path or `false` to disable (new name for {@link endpoint}). */ statsEndpoint?: string | false; /** Access-control callback (new name for {@link shouldShow}). */ authorize?: AccessGuard; /** * Escape hatch to register sensitive routes without an access guard. * Exposes the dashboard without auth — local development only. */ unsafeAllowNoAuth?: boolean; /** Debug panel configuration (new name/shape replacing {@link devToolbar}). */ toolbar?: boolean | ToolbarConfig; /** Full-page dashboard configuration. */ dashboard?: boolean | DashboardConfig; /** Advanced fine-tuning options. */ advanced?: AdvancedConfig; /** Whether verbose informational logging is enabled. Always present after `defineConfig()`. */ verbose: boolean; /** Optional domain restriction for all routes. */ domain?: string; /** Opt-in production behavior. Absent means this package is inert in production. */ production?: ProductionConfig; }