@forinda/kickjs-devtools 5.2.1 → 5.2.3

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["serveStatic"],"sources":["../src/topology.ts","../src/devtools-tabs.ts","../src/bus/server.ts","../src/adapter.ts"],"sourcesContent":["/**\n * Topology aggregator — walks the running KickJS application + DI\n * container and produces a JSON-serialisable {@link TopologySnapshot}.\n *\n * Calls `introspect()` on every plugin and adapter that implements it\n * (architecture.md §23.3); falls back to a minimal `{ protocolVersion,\n * name, kind }` stub for primitives that don't. Per-primitive\n * introspection failures are caught + collected into the snapshot's\n * `errors` field rather than failing the entire endpoint.\n *\n * @module @forinda/kickjs-devtools/topology\n */\n\nimport type { AppAdapter, Container, KickPlugin } from '@forinda/kickjs'\nimport {\n PROTOCOL_VERSION,\n type IntrospectionSnapshot,\n type TopologyContributorEntry,\n type TopologyError,\n type TopologySnapshot,\n type TopologyTokenEntry,\n} from '@forinda/kickjs-devtools-kit'\n\n/** Minimal Application surface the aggregator needs — keeps coupling thin. */\nexport interface TopologyApplicationLike {\n getAdapters(): AppAdapter[]\n getPlugins(): readonly KickPlugin[]\n /**\n * Optional in older Application implementations — when present, returns\n * the union of contributors across adapters/plugins/global with proper\n * source labels. The topology aggregator prefers this over walking\n * `adapter.contributors()` + `plugin.contributors()` directly because\n * the application-level walk preserves source provenance.\n */\n getContributors?(): ReadonlyArray<{\n key: string\n source: 'adapter' | 'plugin' | 'module' | 'global'\n label: string\n dependsOn: readonly string[]\n }>\n}\n\n/** Inputs to {@link collectTopologySnapshot}. */\nexport interface CollectTopologyOptions {\n /** The running KickJS application (or anything that exposes its surface). */\n app: TopologyApplicationLike\n /** The DI container — used to enumerate registered tokens. */\n container: Container\n /**\n * Optional per-call introspect timeout in milliseconds. An adapter\n * whose `introspect()` doesn't settle within the budget gets a stub\n * snapshot + an entry in `errors`. Default: 100ms — keeps the\n * topology endpoint snappy even if one adapter misbehaves.\n */\n introspectTimeoutMs?: number\n}\n\nconst DEFAULT_INTROSPECT_TIMEOUT_MS = 100\n\n/**\n * Collect a {@link TopologySnapshot} for the given application.\n *\n * Async because plugin/adapter `introspect()` may be async; the work\n * is parallelised across all primitives so wall-clock time scales\n * with the slowest introspector, not their sum.\n */\nexport async function collectTopologySnapshot(\n opts: CollectTopologyOptions,\n): Promise<TopologySnapshot> {\n const { app, container, introspectTimeoutMs = DEFAULT_INTROSPECT_TIMEOUT_MS } = opts\n const errors: TopologyError[] = []\n\n const plugins = await Promise.all(\n app.getPlugins().map((p) => snapshotFor(p, 'plugin', introspectTimeoutMs, errors)),\n )\n const adapters = await Promise.all(\n app.getAdapters().map((a) => snapshotFor(a, 'adapter', introspectTimeoutMs, errors)),\n )\n\n return {\n protocolVersion: PROTOCOL_VERSION,\n timestamp: Date.now(),\n plugins,\n adapters,\n contributors: collectContributors(app),\n diTokens: collectTokens(container),\n errors,\n }\n}\n\n/**\n * Coerce one primitive into an {@link IntrospectionSnapshot}. Tries\n * the primitive's own `introspect()` first; falls back to a stub on\n * any of: missing implementation, throw, timeout, or non-object return.\n */\nasync function snapshotFor(\n primitive: AppAdapter | KickPlugin,\n kind: 'plugin' | 'adapter',\n timeoutMs: number,\n errors: TopologyError[],\n): Promise<IntrospectionSnapshot> {\n const name = primitive.name ?? '(unnamed)'\n const stub: IntrospectionSnapshot = {\n protocolVersion: PROTOCOL_VERSION,\n name,\n kind,\n }\n if (typeof primitive.introspect !== 'function') return stub\n\n try {\n const result = await Promise.race([\n Promise.resolve(primitive.introspect()),\n new Promise<never>((_, reject) =>\n setTimeout(\n () => reject(new Error(`introspect() timed out after ${timeoutMs}ms`)),\n timeoutMs,\n ),\n ),\n ])\n if (result && typeof result === 'object') {\n // Accept whatever the primitive returned; the kit's\n // IntrospectionSnapshot is opt-in typed via the kit, not enforced\n // at this layer (see plugin.ts / adapter.ts comment about avoiding\n // a runtime dep on the kit).\n const snap = result as Partial<IntrospectionSnapshot>\n return {\n protocolVersion: PROTOCOL_VERSION,\n name: snap.name ?? name,\n kind: snap.kind ?? kind,\n version: snap.version,\n state: snap.state,\n tokens: snap.tokens,\n metrics: snap.metrics,\n memoryBytes: snap.memoryBytes,\n }\n }\n return stub\n } catch (err) {\n errors.push({\n name,\n kind,\n message: err instanceof Error ? err.message : String(err),\n })\n return stub\n }\n}\n\n/** Read DI registrations into the topology shape — drops noisy HMR tokens. */\nfunction collectTokens(container: Container): TopologyTokenEntry[] {\n return container\n .getRegistrations()\n .filter((r) => !r.token.startsWith('__hmr__'))\n .map((r) => ({\n token: r.token,\n scope: r.scope,\n kind: r.kind,\n instantiated: r.instantiated,\n }))\n}\n\n/**\n * Contributor enumeration. Prefers `app.getContributors()` (the\n * Application-level walk that preserves adapter / plugin / global\n * source labels) when present; falls back to walking\n * `adapter.contributors()` + `plugin.contributors()` directly for\n * older Application implementations that don't expose the helper.\n *\n * Module-level contributors are still not surfaced here — module\n * instances aren't retained post-bootstrap. Per-route enumeration\n * lands in a later iteration alongside the route detail panel.\n */\nfunction collectContributors(app: TopologyApplicationLike): TopologyContributorEntry[] {\n const seen = new Map<string, TopologyContributorEntry>()\n\n if (typeof app.getContributors === 'function') {\n for (const c of app.getContributors()) {\n if (seen.has(c.key)) continue\n // The kit's source enum currently only allows 'adapter' | 'module';\n // 'plugin' + 'global' both map to 'adapter' provenance for now —\n // the Topology UI labels them by `label` so the source field is\n // mainly a coarse category. Future kit version can widen.\n const mapped: TopologyContributorEntry['source'] =\n c.source === 'module' ? 'module' : 'adapter'\n seen.set(c.key, {\n key: c.key,\n source: mapped,\n dependsOn: c.dependsOn as string[],\n })\n }\n return [...seen.values()]\n }\n\n // Legacy path — direct walk.\n const ingest = (\n list: ReadonlyArray<unknown> | null | undefined,\n source: TopologyContributorEntry['source'],\n ): void => {\n if (!list) return\n for (const reg of list) {\n const r = reg as { key?: string; dependsOn?: readonly string[] }\n const key = typeof r.key === 'string' ? r.key : null\n if (!key || seen.has(key)) continue\n seen.set(key, {\n key,\n source,\n dependsOn: Array.isArray(r.dependsOn) ? r.dependsOn : [],\n })\n }\n }\n\n for (const plugin of app.getPlugins()) {\n ingest(plugin.contributors?.(), 'adapter')\n }\n for (const adapter of app.getAdapters()) {\n ingest(adapter.contributors?.(), 'adapter')\n }\n\n return [...seen.values()]\n}\n","/**\n * Custom-tab aggregator — collects every plugin/adapter's\n * `devtoolsTabs()` contribution into a single deduped list for the\n * panel's `/_debug/tabs` endpoint.\n *\n * Validation is permissive: anything that doesn't look like a\n * {@link DevtoolsTabDescriptor} is dropped with a console warning\n * rather than throwing — a misconfigured adapter shouldn't break the\n * whole DevTools panel.\n *\n * @module @forinda/kickjs-devtools/devtools-tabs\n */\n\nimport type { DevtoolsTabDescriptor } from '@forinda/kickjs-devtools-kit'\nimport type { TopologyApplicationLike } from './topology'\n\n/** Result of {@link collectDevtoolsTabs}. */\nexport interface DevtoolsTabsResult {\n /** Deduped, validated tabs in registration order. */\n tabs: DevtoolsTabDescriptor[]\n /** Per-source collection errors (drop reason, source name). */\n errors: ReadonlyArray<{ source: string; reason: string }>\n}\n\nconst VALID_VIEW_TYPES = new Set(['iframe', 'launch', 'html'])\n\n/**\n * Walk every plugin + adapter, call `devtoolsTabs?()`, validate each\n * entry, and dedupe by `id`. Last-source-wins on collision is too\n * surprising — first-source-wins + a warning entry instead.\n */\nexport function collectDevtoolsTabs(app: TopologyApplicationLike): DevtoolsTabsResult {\n const tabs: DevtoolsTabDescriptor[] = []\n const seen = new Map<string, string>() // id → source name (for collision warnings)\n const errors: Array<{ source: string; reason: string }> = []\n\n const ingest = (sourceName: string, raw: unknown): void => {\n if (!Array.isArray(raw)) {\n errors.push({ source: sourceName, reason: 'devtoolsTabs() did not return an array' })\n return\n }\n for (const entry of raw) {\n const validation = validateTab(entry)\n if (!validation.ok) {\n errors.push({ source: sourceName, reason: validation.reason })\n continue\n }\n const tab = validation.tab\n const owner = seen.get(tab.id)\n if (owner) {\n errors.push({\n source: sourceName,\n reason: `tab id '${tab.id}' already registered by ${owner} — first-source wins`,\n })\n continue\n }\n seen.set(tab.id, sourceName)\n tabs.push(tab)\n }\n }\n\n for (const plugin of app.getPlugins()) {\n if (typeof plugin.devtoolsTabs !== 'function') continue\n try {\n ingest(plugin.name ?? '(unnamed plugin)', plugin.devtoolsTabs())\n } catch (err) {\n errors.push({\n source: plugin.name ?? '(unnamed plugin)',\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n for (const adapter of app.getAdapters()) {\n if (typeof adapter.devtoolsTabs !== 'function') continue\n try {\n ingest(adapter.name ?? '(unnamed adapter)', adapter.devtoolsTabs())\n } catch (err) {\n errors.push({\n source: adapter.name ?? '(unnamed adapter)',\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n return { tabs, errors }\n}\n\ninterface ValidationOk {\n ok: true\n tab: DevtoolsTabDescriptor\n}\n\ninterface ValidationFail {\n ok: false\n reason: string\n}\n\n/**\n * Coerce + validate a tab descriptor. Returns the typed object on\n * success; a structured reason on failure. Uses a permissive checker\n * so a partially-correct entry from a third-party adapter doesn't\n * break the whole panel.\n */\nfunction validateTab(raw: unknown): ValidationOk | ValidationFail {\n if (!raw || typeof raw !== 'object') {\n return { ok: false, reason: 'tab entry is not an object' }\n }\n const obj = raw as Record<string, unknown>\n if (typeof obj.id !== 'string' || obj.id.length === 0) {\n return { ok: false, reason: 'tab.id must be a non-empty string' }\n }\n if (typeof obj.title !== 'string' || obj.title.length === 0) {\n return { ok: false, reason: `tab '${obj.id}': title must be a non-empty string` }\n }\n const view = obj.view as Record<string, unknown> | undefined\n if (!view || typeof view !== 'object') {\n return { ok: false, reason: `tab '${obj.id}': view object is required` }\n }\n if (typeof view.type !== 'string' || !VALID_VIEW_TYPES.has(view.type)) {\n return {\n ok: false,\n reason: `tab '${obj.id}': view.type must be one of iframe / launch / html`,\n }\n }\n switch (view.type) {\n case 'iframe':\n if (typeof view.src !== 'string' || view.src.length === 0) {\n return { ok: false, reason: `tab '${obj.id}': iframe view requires a non-empty src` }\n }\n break\n case 'html':\n if (typeof view.html !== 'string') {\n return { ok: false, reason: `tab '${obj.id}': html view requires html string` }\n }\n break\n case 'launch':\n if (!Array.isArray(view.actions)) {\n return { ok: false, reason: `tab '${obj.id}': launch view requires actions array` }\n }\n break\n }\n return { ok: true, tab: obj as unknown as DevtoolsTabDescriptor }\n}\n","// Server-side KickEventBus implementation.\n//\n// Wraps the bus core from `@forinda/kickjs-devtools-kit/bus` with a\n// `ws` server bound to a path on the framework's existing\n// `http.Server`. Architecture:\n//\n// server.on('upgrade') ─┐\n// ├──► WebSocketServer.handleUpgrade()\n// │ └─► ws clients: receive emits as JSON\n// bus.emit(type, payload) ─┴──► serialize → fan out to clients +\n// dispatch locally to in-process subs\n//\n// Why piggyback on the framework's http.Server instead of starting a\n// dedicated WS server: the framework already owns the listener, the\n// upgrade event is the canonical hook, and reusing it means devtools\n// inherits whatever TLS / proxy / port config the application provides.\n//\n// Lifecycle:\n// - createServerBus() builds the WebSocketServer in `noServer: true`\n// mode (no listener of its own) and returns the bus + attach/close\n// handles.\n// - attachUpgrade(httpServer) wires server.on('upgrade') so upgrades\n// matching `wsPath` route into the WebSocketServer. Other upgrade\n// paths (kickjs-ws, etc.) ignore us by virtue of path matching.\n// - close() drops every client and detaches from the http server so\n// repeated dev-mode restarts don't leak listener handles.\n//\n// Authentication:\n// - The optional `secret` matches the devtools panel's existing\n// `x-devtools-token` / `?token=` access guard. When set, upgrades\n// without the right token get rejected at HTTP-handshake time —\n// never reaching the bus.\n//\n// Loop avoidance:\n// - Server emits fan out to every connected client. Client-side\n// emits sent UP the socket dispatch into the local core (so\n// server tabs can react) but are NOT re-broadcast to other\n// clients. This keeps the same \"no echo\" contract the browser\n// bus enforces; without it a tab's emit would round-trip through\n// the server and back to itself.\n\nimport type { IncomingMessage } from 'node:http'\nimport type http from 'node:http'\nimport type { Socket } from 'node:net'\n\nimport { createBusCore } from '@forinda/kickjs-devtools-kit/bus'\nimport type { KickDevtoolsEvent, KickEventBus, Unsubscribe } from '@forinda/kickjs-devtools-kit/bus'\nimport { WebSocketServer, type WebSocket } from 'ws'\n\nexport interface ServerBusOptions {\n /** Path the WebSocket upgrade listens on. Default `/_debug/_bus`. */\n wsPath?: string\n /**\n * Optional shared secret. When set, clients must include either\n * `?token=<secret>` on the upgrade URL or an\n * `x-devtools-token: <secret>` header. Unauthorized upgrades return\n * 401 and never reach the bus. Pass `false` (or omit) to disable.\n */\n secret?: string | false\n}\n\ninterface TaggedEnvelope extends KickDevtoolsEvent {\n __kick_origin?: 'local' | 'broadcast' | 'ws'\n}\n\nexport interface ServerBus extends KickEventBus {\n /** Hook into an existing http.Server's `upgrade` event. */\n attachUpgrade(httpServer: http.Server): void\n /** Drop all clients + detach. Idempotent. */\n close(): void\n /** Currently connected client count. Useful for the devtools health card. */\n clientCount(): number\n}\n\nexport function createServerBus(opts: ServerBusOptions = {}): ServerBus {\n const wsPath = opts.wsPath ?? '/_debug/_bus'\n const secret = opts.secret ?? false\n const core = createBusCore()\n const wss = new WebSocketServer({ noServer: true })\n const clients = new Set<WebSocket>()\n let attachedServer: http.Server | null = null\n let upgradeHandler: ((req: IncomingMessage, socket: Socket, head: Buffer) => void) | null = null\n\n wss.on('connection', (ws: WebSocket) => {\n clients.add(ws)\n ws.on('message', (data: Buffer | string) => {\n try {\n const text = typeof data === 'string' ? data : data.toString('utf-8')\n const parsed = JSON.parse(text) as TaggedEnvelope\n if (!parsed || typeof parsed.type !== 'string' || typeof parsed.ts !== 'number') return\n // Dispatch locally only — never echo back to other clients.\n // (Tabs that need cross-tab fan-out use BroadcastChannel; the\n // server is point-to-point per client.)\n core.dispatch({ ...parsed, __kick_origin: 'ws' } as KickDevtoolsEvent)\n } catch {\n // Malformed — drop silently. A misbehaving tab shouldn't\n // crash the server bus.\n }\n })\n ws.on('close', () => {\n clients.delete(ws)\n })\n ws.on('error', () => {\n clients.delete(ws)\n })\n })\n\n const fanOut = (envelope: TaggedEnvelope): void => {\n if (clients.size === 0) return\n const text = JSON.stringify(envelope)\n for (const client of clients) {\n // OPEN === 1 in the ws spec; reusing the import for the type\n // guard keeps this readable without pulling in WebSocket consts.\n if (client.readyState === client.OPEN) {\n try {\n client.send(text)\n } catch {\n // Network error mid-fan-out — clean removal happens via the\n // 'close' / 'error' handlers; nothing to do here.\n }\n }\n }\n }\n\n const checkAuth = (req: IncomingMessage): boolean => {\n if (secret === false) return true\n const header = req.headers['x-devtools-token']\n if (typeof header === 'string' && header === secret) return true\n // Parse query — `req.url` is path + ?query for upgrade requests.\n const url = req.url ?? ''\n const queryIdx = url.indexOf('?')\n if (queryIdx === -1) return false\n const params = new URLSearchParams(url.slice(queryIdx + 1))\n return params.get('token') === secret\n }\n\n const attachUpgrade = (httpServer: http.Server): void => {\n if (attachedServer) return // idempotent\n attachedServer = httpServer\n upgradeHandler = (req, socket, head) => {\n // Path match — ignore upgrades destined for other adapters\n // (kickjs-ws, custom adapters, etc.). They register their own\n // upgrade handlers; ours just no-ops on non-matching URLs.\n const url = req.url ?? ''\n const pathOnly = url.split('?')[0]\n if (pathOnly !== wsPath) return\n\n if (!checkAuth(req)) {\n socket.write('HTTP/1.1 401 Unauthorized\\r\\n\\r\\n')\n socket.destroy()\n return\n }\n\n wss.handleUpgrade(req, socket, head, (ws: WebSocket) => {\n wss.emit('connection', ws, req)\n })\n }\n httpServer.on('upgrade', upgradeHandler)\n }\n\n const close = (): void => {\n if (attachedServer && upgradeHandler) {\n attachedServer.off('upgrade', upgradeHandler)\n }\n attachedServer = null\n upgradeHandler = null\n for (const client of clients) {\n try {\n client.close()\n } catch {\n // ignore\n }\n }\n clients.clear()\n wss.close()\n }\n\n return {\n on(type: string, handler: (payload: unknown) => void): Unsubscribe {\n return core.on(type, handler)\n },\n onAny(handler: (event: KickDevtoolsEvent) => void): Unsubscribe {\n return core.onAny(handler)\n },\n emit(type: string, payload: unknown): void {\n const envelope: TaggedEnvelope = {\n type,\n payload,\n ts: Date.now(),\n __kick_origin: 'local',\n }\n core.dispatch(envelope)\n fanOut(envelope)\n },\n attachUpgrade,\n close,\n clientCount: () => clients.size,\n } as ServerBus\n}\n","import type { Request, Response, NextFunction } from 'express'\nimport { Router, static as serveStatic } from 'express'\nimport { dirname, join } from 'node:path'\nimport { tmpdir } from 'node:os'\nimport { fileURLToPath } from 'node:url'\nimport { createReadStream, existsSync, readFileSync, statSync, unlink } from 'node:fs'\nimport { randomBytes } from 'node:crypto'\nimport { writeHeapSnapshot } from 'node:v8'\nimport {\n type AdapterMiddleware,\n type Container,\n METADATA,\n defineAdapter,\n ref,\n computed,\n reactive,\n watch,\n createLogger,\n type Ref,\n type ComputedRef,\n getClassMeta,\n getMethodMeta,\n} from '@forinda/kickjs'\nimport {\n MemoryAnalyzer,\n PROTOCOL_VERSION,\n RuntimeSampler,\n type IntrospectionSnapshot,\n} from '@forinda/kickjs-devtools-kit'\nimport { DEVTOOLS_BUS } from '@forinda/kickjs-devtools-kit/bus/token'\nimport { collectTopologySnapshot, type TopologyApplicationLike } from './topology'\nimport { collectDevtoolsTabs } from './devtools-tabs'\nimport { createServerBus, type ServerBus } from './bus/server'\n\nconst log = createLogger('DevTools')\n\n/** Route metadata collected during mount */\ninterface RouteInfo {\n method: string\n path: string\n controller: string\n handler: string\n middleware: string[]\n}\n\n/** Per-route latency stats with percentile tracking */\ninterface RouteStats {\n count: number\n totalMs: number\n minMs: number\n maxMs: number\n /** Ring buffer of last N samples for percentile computation */\n samples: number[]\n}\n\nconst MAX_SAMPLES = 1000\n\n/** Compute a percentile from a sorted array of numbers */\nfunction percentile(sorted: number[], p: number): number {\n if (sorted.length === 0) return 0\n const idx = Math.ceil(p * sorted.length) - 1\n return sorted[Math.max(0, idx)]\n}\n\n/** Compute p50, p95, p99 from a RouteStats samples buffer */\nfunction computePercentiles(stats: RouteStats): { p50: number; p95: number; p99: number } {\n const sorted = [...stats.samples].toSorted((a, b) => a - b)\n return {\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n p99: percentile(sorted, 0.99),\n }\n}\n\n/**\n * Open an SSE response — sets the headers, flushes them, and disables\n * any compression middleware that may have been registered upstream\n * (compression buffers SSE chunks indefinitely; we need flush-on-write).\n */\nfunction openSseStream(req: Request, res: Response): void {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n })\n res.flushHeaders?.()\n // Defensive: the compression middleware checks this header. Some\n // setups also wrap res.write — calling res.flush after each write\n // is safe even when no compression is in play.\n void req\n}\n\n/** Write a single SSE `data:` event with a JSON payload + double newline. */\nfunction writeSseEvent(res: Response, payload: unknown): void {\n res.write(`data: ${JSON.stringify(payload)}\\n\\n`)\n}\n\n/**\n * Module-scoped guard for `POST /_debug/memory/snapshot`. `writeHeapSnapshot()`\n * blocks the event loop for the duration of the capture (multi-second\n * for large heaps); two concurrent captures would compound the pause.\n * The endpoint returns 503 + a hint message when this flag is set so\n * the SPA can surface a \"snapshot already running\" warning rather than\n * silently queueing.\n *\n * Module-scoped (not per-adapter-instance) because writeHeapSnapshot\n * acts on the V8 process — multiple DevToolsAdapter instances would\n * still race at the v8 layer.\n */\nlet snapshotInProgress = false\n\nexport interface DevToolsOptions {\n /** Base path for debug endpoints (default: '/_debug') */\n basePath?: string\n /** Only enable when this is true (default: process.env.NODE_ENV !== 'production') */\n enabled?: boolean\n /** Include environment variables (sanitized) at /_debug/config (default: false) */\n exposeConfig?: boolean\n /** Env var prefixes to expose (default: ['APP_', 'NODE_ENV']). Others are redacted. */\n configPrefixes?: string[]\n /** Callback when error rate exceeds threshold */\n onErrorRateExceeded?: (rate: number) => void\n /** Error rate threshold (default: 0.5 = 50%) */\n errorRateThreshold?: number\n /** Other adapters to discover stats from (e.g., WsAdapter) */\n adapters?: any[]\n\n /**\n * Secret token to guard DevTools access. When set, all requests must\n * include this token as `x-devtools-token` header or `?token=` query param.\n *\n * Auto-generated on startup if not provided. The token is logged to the console.\n * Set to `false` to disable the guard entirely (not recommended).\n *\n * @example\n * ```ts\n * DevToolsAdapter({ secret: getEnv('DEVTOOLS_SECRET') })\n * ```\n */\n secret?: string | false\n\n /**\n * Tuning for the runtime sampler that powers `/_debug/runtime` and\n * the upcoming Memory tab (architecture.md §23). Defaults to\n * 1-second polling with a 60-sample (~1 minute) ring buffer.\n *\n * Set `runtime.enabled = false` to skip starting the sampler — the\n * `/_debug/runtime` endpoint then returns 404 instead of an empty\n * snapshot, signalling deliberate opt-out rather than a startup race.\n */\n runtime?: {\n /** Whether to start the runtime sampler at all. Default: true. */\n enabled?: boolean\n /** Polling interval in milliseconds. Default: 1000. */\n intervalMs?: number\n /** Ring-buffer size — number of past samples retained. Default: 60. */\n bufferSize?: number\n }\n}\n\n/**\n * Public reactive surface exposed by a DevToolsAdapter instance —\n * counters, computed metrics, and the route latency map. Tests and\n * peer adapters consume these directly to drive their own behavior.\n */\nexport interface DevToolsAdapterExtensions {\n /** Total requests received. */\n readonly requestCount: Ref<number>\n /** Total responses with status >= 500. */\n readonly errorCount: Ref<number>\n /** Total responses with status >= 400 and < 500. */\n readonly clientErrorCount: Ref<number>\n /** Server start time. */\n readonly startedAt: Ref<number>\n /** Computed error rate (server errors / total requests). */\n readonly errorRate: ComputedRef<number>\n /** Computed uptime in seconds. */\n readonly uptimeSeconds: ComputedRef<number>\n /** Per-route latency tracking. */\n readonly routeLatency: Record<string, RouteStats>\n /**\n * Tier-1 runtime sampler from `@forinda/kickjs-devtools-kit`. `null`\n * when `runtime.enabled` is `false`. Tests can `latest()` and\n * `history()` directly without going through the HTTP endpoint.\n */\n readonly runtimeSampler: RuntimeSampler | null\n /**\n * Memory analyzer fed by the runtime sampler. `null` when the\n * sampler is disabled. Use `analyzer.health(sampler.history())` to\n * compose a composite memory-health snapshot.\n */\n readonly memoryAnalyzer: MemoryAnalyzer | null\n}\n\n/**\n * DevToolsAdapter — Vue-style reactive introspection for KickJS applications.\n *\n * Exposes debug endpoints powered by reactive state (ref, computed, watch):\n * - `GET /_debug/routes` — all registered routes with middleware\n * - `GET /_debug/container` — DI registry with scopes and instantiation status\n * - `GET /_debug/metrics` — live request/error counts, error rate, uptime\n * - `GET /_debug/health` — deep health check with adapter status\n * - `GET /_debug/config` — sanitized environment variables (opt-in)\n * - `GET /_debug/state` — full reactive state snapshot\n *\n * @example\n * ```ts\n * import { DevToolsAdapter } from '@forinda/kickjs-devtools'\n *\n * bootstrap({\n * modules: [UserModule],\n * adapters: [\n * DevToolsAdapter({\n * enabled: process.env.NODE_ENV !== 'production',\n * exposeConfig: true,\n * configPrefixes: ['APP_', 'DATABASE_'],\n * }),\n * ],\n * })\n * ```\n */\nexport const DevToolsAdapter = defineAdapter<DevToolsOptions, DevToolsAdapterExtensions>({\n name: 'DevToolsAdapter',\n defaults: {\n basePath: '/_debug',\n errorRateThreshold: 0.5,\n exposeConfig: false,\n configPrefixes: ['APP_', 'NODE_ENV'],\n },\n build: (options) => {\n const basePath = options.basePath!\n const enabled = options.enabled ?? process.env.NODE_ENV !== 'production'\n const exposeConfig = options.exposeConfig!\n const configPrefixes = options.configPrefixes!\n const errorRateThreshold = options.errorRateThreshold!\n const peerAdapters = options.adapters ?? []\n\n // Secret token guard\n let secret: string | false\n if (options.secret === false) {\n secret = false\n } else if (options.secret) {\n secret = options.secret\n } else {\n secret = randomBytes(16).toString('hex')\n }\n\n // ── Runtime sampler + memory analyzer (kit) ────────────────────\n // Lazily instantiated so an adopter that disables runtime monitoring\n // doesn't pay the perf_hooks histogram cost. Lifecycle: start in\n // `beforeMount`, stop in `shutdown`.\n const runtimeEnabled = options.runtime?.enabled ?? true\n const runtimeSampler = runtimeEnabled\n ? new RuntimeSampler({\n intervalMs: options.runtime?.intervalMs ?? 1000,\n bufferSize: options.runtime?.bufferSize ?? 60,\n })\n : null\n const memoryAnalyzer = runtimeEnabled ? new MemoryAnalyzer() : null\n\n // ── Server-side event bus ──────────────────────────────────────\n // Lazily resolved in `beforeMount` — when the devtools adapter is\n // rebuilt during HMR, the same `Container` may already hold a bus\n // from a previous mount with live WebSocket clients + in-flight\n // subscriptions. Creating a fresh bus on every rebuild would\n // silently swap the registered instance, leaving plugins that\n // already captured the old reference publishing into a dead bus.\n // Using `container.has(DEVTOOLS_BUS)` to reuse instead keeps event\n // delivery stable across rebuilds.\n //\n // When the devtools adapter is disabled (`enabled === false`) we\n // register a no-op stub instead so adopters who Inject(DEVTOOLS_BUS)\n // under @Optional() get a callable instance rather than undefined.\n let bus: ServerBus | null = null\n\n const ensureBus = (container: Container): ServerBus => {\n if (container.has(DEVTOOLS_BUS)) {\n // The token is typed `KickEventBus` but the registered instance\n // is the wider `ServerBus` (KickEventBus + attachUpgrade /\n // close / clientCount). Explicit generic on resolve avoids the\n // structural-cast — Container.resolve's last overload accepts\n // an explicit T and returns it.\n bus = container.resolve<ServerBus>(DEVTOOLS_BUS)\n return bus\n }\n bus = enabled\n ? createServerBus({\n wsPath: `${basePath}/_bus`,\n secret: secret === false ? false : secret,\n })\n : ({\n on: () => () => {},\n onAny: () => () => {},\n emit: () => {},\n attachUpgrade: () => {},\n close: () => {},\n clientCount: () => 0,\n } as ServerBus)\n container.registerInstance(DEVTOOLS_BUS, bus)\n return bus\n }\n\n // ── Reactive state ─────────────────────────────────────────────\n const requestCount = ref(0)\n const errorCount = ref(0)\n const clientErrorCount = ref(0)\n const startedAt = ref(Date.now())\n const routeLatency = reactive<Record<string, RouteStats>>({})\n\n const errorRate = computed(() =>\n requestCount.value > 0 ? errorCount.value / requestCount.value : 0,\n )\n\n const uptimeSeconds = computed(() => Math.floor((Date.now() - startedAt.value) / 1000))\n\n // ── Internal mutable state ─────────────────────────────────────\n let routes: RouteInfo[] = []\n let container: Container | null = null\n let appRef: any = null\n const adapterStatuses: Record<string, string> = {}\n let stopErrorWatch: (() => void) | null = null\n\n // Watch error rate — log warnings when elevated\n if (options.onErrorRateExceeded) {\n const callback = options.onErrorRateExceeded\n stopErrorWatch = watch(errorRate, (rate) => {\n if (rate > errorRateThreshold) {\n callback(rate)\n }\n })\n } else {\n stopErrorWatch = watch(errorRate, (rate) => {\n if (rate > errorRateThreshold) {\n log.warn(`Error rate elevated: ${(rate * 100).toFixed(1)}%`)\n }\n })\n }\n\n /**\n * Find the dashboard's public directory. Prefers the new Solid SPA\n * (public/spa/, shipped from PR 4 of §23); falls back to the legacy\n * Vue+Tailwind dashboard (public/devtools/) for environments that\n * haven't run `pnpm --filter @forinda/kickjs-devtools build:spa`.\n */\n const resolvePublicDir = (): string | null => {\n const thisDir = dirname(fileURLToPath(import.meta.url))\n const candidates = [\n join(thisDir, '..', 'public', 'spa'), // dist/ -> public/spa\n join(thisDir, '..', '..', 'public', 'spa'), // src/ -> public/spa\n join(thisDir, '..', 'public', 'devtools'), // legacy Vue dashboard\n join(thisDir, '..', '..', 'public', 'devtools'), // legacy from src/\n ]\n for (const dir of candidates) {\n if (existsSync(join(dir, 'index.html'))) return dir\n }\n return null\n }\n\n /**\n * Resolve peer adapters at request time. Prefers live adapters from the\n * Application registry (survives HMR rebuild) and falls back to the\n * constructor-provided refs.\n */\n const getPeerAdapters = (): any[] => {\n const kickApp = appRef?.__kickApp\n if (kickApp && typeof kickApp.getAdapters === 'function') {\n return kickApp.getAdapters()\n }\n return peerAdapters\n }\n\n return {\n // ── Extensions (TExtra) ───────────────────────────────────────\n requestCount,\n errorCount,\n clientErrorCount,\n startedAt,\n errorRate,\n uptimeSeconds,\n routeLatency,\n runtimeSampler,\n memoryAnalyzer,\n\n // ── DevTools introspection (architecture.md §23) ─────────────\n // Cheap snapshot — counters + flags only. Anything that requires\n // a container walk or DB hit belongs in the per-endpoint RPCs\n // (`/_debug/container`, `/_debug/graph`), not here.\n introspect(): IntrospectionSnapshot {\n return {\n protocolVersion: PROTOCOL_VERSION,\n name: 'DevToolsAdapter',\n kind: 'adapter',\n state: {\n basePath,\n enabled,\n runtimeEnabled,\n secret: secret === false ? false : 'present',\n },\n metrics: {\n requestCount: requestCount.value,\n serverErrors: errorCount.value,\n clientErrors: clientErrorCount.value,\n uptimeSeconds: uptimeSeconds.value,\n routesTracked: routes.length,\n },\n }\n },\n\n // ── Lifecycle ─────────────────────────────────────────────────\n\n beforeMount({ app, container: containerArg }) {\n if (!enabled) return\n\n appRef = app\n container = containerArg\n // Lazy resolve — reuses the existing bus when the same\n // container is reused across HMR rebuilds, otherwise creates\n // and registers a fresh instance. See `ensureBus` for why.\n ensureBus(containerArg)\n startedAt.value = Date.now()\n // Clear routes on rebuild/restart to prevent HMR duplication\n routes = []\n adapterStatuses['DevToolsAdapter'] = 'running'\n\n // Start the runtime sampler + memory analyzer here (rather than\n // at construction) so test harnesses that build the adapter but\n // never mount it don't leak interval timers.\n runtimeSampler?.start()\n memoryAnalyzer?.start()\n\n const router = Router()\n\n // ── Access guard — require secret token ──────────────────\n if (secret !== false) {\n const token = secret\n router.use((req: Request, res: Response, next: NextFunction) => {\n const provided = req.headers['x-devtools-token'] ?? req.query?.token\n if (provided === token) return next()\n // Allow the dashboard HTML itself (it will include the token in API calls)\n if (req.path === '/' && req.method === 'GET' && !req.query?.token) {\n return next() // serve dashboard, it handles auth via token\n }\n // Serve static assets for the dashboard (js files)\n if (req.path.endsWith('.js') || req.path.endsWith('.css')) {\n return next()\n }\n res.status(403).json({ error: 'Forbidden — invalid or missing devtools token' })\n })\n }\n\n router.get('/routes', (_req: Request, res: Response) => {\n res.json({ routes })\n })\n\n router.get('/container', (_req: Request, res: Response) => {\n const registrations = container?.getRegistrations() ?? []\n res.json({ registrations, count: registrations.length })\n })\n\n router.get('/metrics', (_req: Request, res: Response) => {\n // Build latency with percentiles, omitting raw samples from response\n const latency: Record<string, any> = {}\n for (const [key, stats] of Object.entries(routeLatency)) {\n const { samples: _, ...rest } = stats\n latency[key] = { ...rest, ...computePercentiles(stats) }\n }\n res.json({\n requests: requestCount.value,\n serverErrors: errorCount.value,\n clientErrors: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n startedAt: new Date(startedAt.value).toISOString(),\n routeLatency: latency,\n })\n })\n\n router.get('/health', (_req: Request, res: Response) => {\n const healthy = errorRate.value < errorRateThreshold\n const status = healthy ? 'healthy' : 'degraded'\n\n res.status(healthy ? 200 : 503).json({\n status,\n errorRate: errorRate.value,\n uptime: uptimeSeconds.value,\n adapters: adapterStatuses,\n })\n })\n\n router.get('/state', (_req: Request, res: Response) => {\n const wsAdapter = getPeerAdapters().find(\n (a) => a.name === 'WsAdapter' && typeof a.getStats === 'function',\n )\n res.json({\n reactive: {\n requestCount: requestCount.value,\n errorCount: errorCount.value,\n clientErrorCount: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n startedAt: new Date(startedAt.value).toISOString(),\n },\n routes: routes.length,\n container: container?.getRegistrations().length ?? 0,\n routeLatency,\n ...(wsAdapter ? { ws: wsAdapter.getStats() } : {}),\n })\n })\n\n // ── Tier-1 runtime monitoring (architecture.md §23) ─────────\n // Returns the latest RuntimeSnapshot + a composite MemoryHealth\n // computed from the sampler's ring buffer. Returns 404 when the\n // sampler is disabled so adopters can distinguish \"off\" from\n // \"starting up\".\n router.get('/runtime', (_req: Request, res: Response) => {\n if (!runtimeSampler || !memoryAnalyzer) {\n res.status(404).json({ error: 'runtime sampler disabled — set runtime.enabled = true' })\n return\n }\n const latest = runtimeSampler.latest()\n const history = runtimeSampler.history()\n const health = memoryAnalyzer.health(history)\n res.json({\n protocolVersion: PROTOCOL_VERSION,\n latest,\n history,\n health,\n })\n })\n\n // ── SSE: live runtime snapshots (architecture.md §23) ───────\n // Pushes the latest RuntimeSnapshot every `intervalMs`. SSE\n // (not WebSocket) avoids the http.Server `upgrade`-event\n // coordination cost — see devtools-flows.md §3 for rationale.\n router.get('/runtime/stream', (req: Request, res: Response) => {\n if (!runtimeSampler) {\n res.status(404).json({ error: 'runtime sampler disabled' })\n return\n }\n openSseStream(req, res)\n const intervalMs = options.runtime?.intervalMs ?? 1000\n const tick = (): void => {\n const snap = runtimeSampler.latest()\n if (snap) writeSseEvent(res, snap)\n }\n tick()\n const interval = setInterval(tick, intervalMs)\n const heartbeat = setInterval(() => res.write(': heartbeat\\n\\n'), 30_000)\n req.on('close', () => {\n clearInterval(interval)\n clearInterval(heartbeat)\n })\n })\n\n // ── SSE: memory health composite (architecture.md §23) ──────\n router.get('/memory/stream', (req: Request, res: Response) => {\n if (!runtimeSampler || !memoryAnalyzer) {\n res.status(404).json({ error: 'runtime sampler disabled' })\n return\n }\n openSseStream(req, res)\n const intervalMs = options.runtime?.intervalMs ?? 1000\n const tick = (): void => {\n const snap = runtimeSampler.latest()\n if (!snap) return\n const health = memoryAnalyzer.health(runtimeSampler.history())\n writeSseEvent(res, { snapshot: snap, health })\n }\n tick()\n const interval = setInterval(tick, intervalMs)\n const heartbeat = setInterval(() => res.write(': heartbeat\\n\\n'), 30_000)\n req.on('close', () => {\n clearInterval(interval)\n clearInterval(heartbeat)\n })\n })\n\n // ── Heap snapshot — Tier 3 monitoring (architecture.md §23) ─\n // POST /_debug/memory/snapshot — captures a V8 heap snapshot\n // and streams the resulting .heapsnapshot file back as\n // application/json with Content-Disposition. Snapshot capture\n // blocks the event loop while writing (multi-second pause for\n // large heaps), so the endpoint enforces single-flight via a\n // module-scoped flag — concurrent calls return 503.\n //\n // The temp file is deleted as soon as the response stream\n // completes (success or error). Worst case if the process\n // dies mid-snapshot is a stranded file in `os.tmpdir()`,\n // which the OS cleans up on next boot.\n router.post('/memory/snapshot', (_req: Request, res: Response) => {\n if (snapshotInProgress) {\n res\n .status(503)\n .json({ error: 'heap snapshot already in progress — wait for it to complete' })\n return\n }\n snapshotInProgress = true\n const startedAt = Date.now()\n const filename = `kickjs-heap-${new Date().toISOString().replace(/[:.]/g, '-')}.heapsnapshot`\n const targetPath = join(tmpdir(), filename)\n\n let written: string\n try {\n // writeHeapSnapshot is synchronous — the event loop is\n // blocked for the duration. There's no async variant in\n // the v8 module today; if one ships, swap here.\n written = writeHeapSnapshot(targetPath)\n } catch (err) {\n snapshotInProgress = false\n log.error({ err }, 'heap snapshot capture failed')\n res\n .status(500)\n .json({ error: 'snapshot capture failed', message: (err as Error).message })\n return\n }\n\n let size = 0\n try {\n size = statSync(written).size\n } catch {\n /* size header is best-effort */\n }\n const elapsedMs = Date.now() - startedAt\n log.info(\n `Heap snapshot captured: ${written} (${(size / 1024 / 1024).toFixed(1)} MiB in ${elapsedMs}ms)`,\n )\n\n res.setHeader('Content-Type', 'application/json')\n res.setHeader('Content-Disposition', `attachment; filename=\"${filename}\"`)\n if (size > 0) res.setHeader('Content-Length', String(size))\n res.setHeader('X-Snapshot-Capture-Ms', String(elapsedMs))\n\n const cleanup = (): void => {\n unlink(written, (err) => {\n if (err) log.warn(`Failed to delete heap snapshot ${written}: ${err.message}`)\n snapshotInProgress = false\n })\n }\n const stream = createReadStream(written)\n stream.on('end', cleanup)\n stream.on('error', (err) => {\n log.error({ err }, 'heap snapshot stream failed')\n if (!res.headersSent) res.status(500).end()\n cleanup()\n })\n // Defensive: if the client disconnects mid-download, abort\n // the stream + run cleanup so the temp file doesn't linger.\n res.on('close', () => {\n stream.destroy()\n // If the stream already fired 'end', cleanup already ran\n // — the unlink is idempotent enough that running twice\n // just yields ENOENT which we ignore in cleanup.\n })\n stream.pipe(res)\n })\n\n // ── Force GC — Tier 3 monitoring (architecture.md §23) ──────\n // POST /_debug/memory/gc — calls `global.gc()` if Node was\n // started with --expose-gc, returning before/after heap size\n // so the panel can show how much was reclaimed. Useful for\n // confirming \"is this growth real or just delayed GC?\".\n //\n // Returns 412 Precondition Failed (with hint) when the flag\n // wasn't set, so the SPA can show \"Run with --expose-gc to\n // enable this button\" instead of a generic 5xx.\n router.post('/memory/gc', (_req: Request, res: Response) => {\n const gc = (globalThis as { gc?: () => void }).gc\n if (typeof gc !== 'function') {\n res.status(412).json({\n error: 'global.gc unavailable — start Node with --expose-gc to enable this endpoint',\n })\n return\n }\n const before = process.memoryUsage().heapUsed\n const startedAt = Date.now()\n try {\n gc()\n } catch (err) {\n res.status(500).json({\n error: 'forced GC failed',\n message: err instanceof Error ? err.message : String(err),\n })\n return\n }\n const after = process.memoryUsage().heapUsed\n const reclaimedBytes = Math.max(0, before - after)\n const elapsedMs = Date.now() - startedAt\n log.info(\n `Forced GC reclaimed ${(reclaimedBytes / 1024 / 1024).toFixed(2)} MiB in ${elapsedMs}ms`,\n )\n res.json({ before, after, reclaimedBytes, elapsedMs })\n })\n\n // ── Custom-tab discovery (architecture.md §23) ──────────────\n // Walks every plugin/adapter `devtoolsTabs?()` contribution\n // and serves the deduped + validated list. The SPA fetches\n // this once at boot to render dynamic tabs after the four\n // built-ins.\n router.get('/tabs', (_req: Request, res: Response) => {\n const kickApp = appRef?.__kickApp as TopologyApplicationLike | undefined\n if (!kickApp) {\n res.status(503).json({ error: 'tabs unavailable — application surface not exposed' })\n return\n }\n res.json(collectDevtoolsTabs(kickApp))\n })\n\n // ── Topology RPC (architecture.md §23) ──────────────────────\n // Aggregates plugins + adapters + contributors + DI tokens\n // into one snapshot; calls each primitive's introspect() in\n // parallel with a per-call timeout so a misbehaving adapter\n // can't block the endpoint. Errors are collected, not thrown.\n router.get('/topology', async (_req: Request, res: Response) => {\n if (!container) {\n res.status(503).json({ error: 'topology unavailable — container not bound yet' })\n return\n }\n const kickApp = appRef?.__kickApp as TopologyApplicationLike | undefined\n if (!kickApp) {\n res\n .status(503)\n .json({ error: 'topology unavailable — application surface not exposed' })\n return\n }\n try {\n const snapshot = await collectTopologySnapshot({ app: kickApp, container })\n res.json(snapshot)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n res.status(500).json({ error: 'topology collection failed', message })\n }\n })\n\n router.get('/ws', (_req: Request, res: Response) => {\n const wsAdapter = getPeerAdapters().find(\n (a) => a.name === 'WsAdapter' && typeof a.getStats === 'function',\n )\n if (!wsAdapter) {\n res.json({ enabled: false, message: 'WsAdapter not found' })\n return\n }\n res.json({ enabled: true, ...wsAdapter.getStats() })\n })\n\n router.get('/queues', async (_req: Request, res: Response) => {\n const queueAdapter = getPeerAdapters().find(\n (a) => a.name === 'QueueAdapter' && typeof a.getQueueNames === 'function',\n )\n if (!queueAdapter) {\n res.json({ enabled: false, message: 'QueueAdapter not found' })\n return\n }\n try {\n const names: string[] = queueAdapter.getQueueNames?.() ?? []\n const queues: any[] = []\n for (const name of names) {\n const stats = await queueAdapter.getQueueStats?.(name)\n queues.push({ name, ...stats })\n }\n res.json({ enabled: true, queues })\n } catch {\n res.json({ enabled: true, queues: [], error: 'Failed to fetch queue stats' })\n }\n })\n\n // ── Dependency graph ────────────────────────────────────────\n router.get('/graph', (_req: Request, res: Response) => {\n const registrations = container?.getRegistrations() ?? []\n const nodes = registrations\n .filter((r) => !r.token.startsWith('__hmr__'))\n .map((r) => ({\n id: r.token,\n kind: r.kind,\n scope: r.scope,\n resolveCount: r.resolveCount,\n }))\n const nodeIds = new Set(nodes.map((n) => n.id))\n const edges: Array<{ from: string; to: string }> = []\n for (const r of registrations) {\n if (r.token.startsWith('__hmr__')) continue\n for (const dep of r.dependencies) {\n if (nodeIds.has(dep)) {\n edges.push({ from: r.token, to: dep })\n }\n }\n }\n res.json({ nodes, edges })\n })\n\n // ── SSE stream for real-time updates ────────────────────────\n router.get('/stream', (req: Request, res: Response) => {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n })\n\n const sendMetrics = () => {\n const data = {\n type: 'metrics',\n requestCount: requestCount.value,\n errorCount: errorCount.value,\n clientErrorCount: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n }\n res.write(`data: ${JSON.stringify(data)}\\n\\n`)\n }\n sendMetrics()\n\n const unsubContainer = container?.onChange?.((changes) => {\n res.write(\n `data: ${JSON.stringify({ type: 'container', changes, timestamp: Date.now() })}\\n\\n`,\n )\n sendMetrics()\n })\n\n const stopRequestWatch = watch(requestCount, () => sendMetrics())\n const stopErrWatch = watch(errorCount, () => sendMetrics())\n\n const heartbeat = setInterval(() => {\n res.write(`: heartbeat\\n\\n`)\n }, 30000)\n\n req.on('close', () => {\n unsubContainer?.()\n stopRequestWatch()\n stopErrWatch()\n clearInterval(heartbeat)\n })\n })\n\n if (exposeConfig) {\n router.get('/config', (_req: Request, res: Response) => {\n const config: Record<string, string> = {}\n for (const [key, value] of Object.entries(process.env)) {\n if (value === undefined) continue\n const allowed = configPrefixes.some((prefix) => key.startsWith(prefix))\n config[key] = allowed ? value : '[REDACTED]'\n }\n res.json({ config })\n })\n }\n\n // Dashboard UI — Vue + Tailwind from public/devtools directory\n const publicDir = resolvePublicDir()\n if (publicDir) {\n router.use(serveStatic(publicDir))\n\n const indexHtml = readFileSync(join(publicDir, 'index.html'), 'utf-8')\n router.get('/', (_req: Request, res: Response) => {\n const html = indexHtml.replace('<body', `<body data-base=\"${basePath}\"`)\n res.type('html').send(html)\n })\n } else {\n router.get('/', (_req: Request, res: Response) => {\n res.type('html').send('<h1>DevTools: public directory not found</h1>')\n })\n }\n\n app.use(basePath, router)\n\n if (secret) {\n log.info(`DevTools mounted at ${basePath} [token: ${secret}]`)\n log.info(`Access: ${basePath}?token=${secret}`)\n } else {\n log.info(`DevTools mounted at ${basePath} [no guard]`)\n }\n },\n\n middleware(): AdapterMiddleware[] {\n if (!enabled) return []\n\n return [\n {\n handler: (req: Request, res: Response, next: NextFunction) => {\n const start = Date.now()\n requestCount.value++\n\n res.on('finish', () => {\n if (res.statusCode >= 500) errorCount.value++\n else if (res.statusCode >= 400) clientErrorCount.value++\n\n const routeKey = `${req.method} ${req.route?.path ?? req.path}`\n const elapsed = Date.now() - start\n\n if (!routeLatency[routeKey]) {\n routeLatency[routeKey] = {\n count: 0,\n totalMs: 0,\n minMs: Infinity,\n maxMs: 0,\n samples: [],\n }\n }\n const stats = routeLatency[routeKey]\n stats.count++\n stats.totalMs += elapsed\n stats.minMs = Math.min(stats.minMs, elapsed)\n stats.maxMs = Math.max(stats.maxMs, elapsed)\n stats.samples.push(elapsed)\n if (stats.samples.length > MAX_SAMPLES) stats.samples.shift()\n })\n\n next()\n },\n phase: 'beforeGlobal',\n },\n ]\n },\n\n onRouteMount(controllerClass, mountPath) {\n if (!enabled) return\n\n const collectedRoutes = getClassMeta<\n Array<{ method: string; path: string; handlerName: string }>\n >(METADATA.ROUTES, controllerClass, [])\n\n const classMiddleware = getClassMeta<any[]>(METADATA.CLASS_MIDDLEWARES, controllerClass, [])\n\n for (const route of collectedRoutes) {\n const methodMiddleware = getMethodMeta<any[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass.prototype,\n route.handlerName,\n [],\n )\n\n routes.push({\n method: route.method.toUpperCase(),\n path: `${mountPath}${route.path === '/' ? '' : route.path}`,\n controller: controllerClass.name,\n handler: route.handlerName,\n middleware: [\n ...classMiddleware.map((m: any) => m.name || 'anonymous'),\n ...methodMiddleware.map((m: any) => m.name || 'anonymous'),\n ],\n })\n }\n },\n\n afterStart({ server }) {\n if (!enabled) return\n // Wire the bus's WS upgrade to the framework's http.Server.\n // Path-based routing inside attachUpgrade means kickjs-ws or\n // any other adapter sharing the same listener stays\n // unaffected — only `${basePath}/_bus` is claimed.\n if (server) bus?.attachUpgrade(server)\n log.info(\n `DevTools ready — ${routes.length} routes tracked, ` +\n `${container?.getRegistrations().length ?? 0} DI bindings, ` +\n `event bus on ${basePath}/_bus`,\n )\n },\n\n shutdown() {\n stopErrorWatch?.()\n runtimeSampler?.stop()\n memoryAnalyzer?.stop()\n bus?.close()\n adapterStatuses['DevToolsAdapter'] = 'stopped'\n },\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyDA,MAAM,gCAAgC;;;;;;;;AAStC,eAAsB,wBACpB,MAC2B;CAC3B,MAAM,EAAE,KAAK,WAAW,sBAAsB,kCAAkC;CAChF,MAAM,SAA0B,EAAE;CAElC,MAAM,UAAU,MAAM,QAAQ,IAC5B,IAAI,YAAY,CAAC,KAAK,MAAM,YAAY,GAAG,UAAU,qBAAqB,OAAO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C;AAE5F,SAAK,MAAM,SAAS,iBAAiB;KACnC,MAAM,mBAAmB,cACvB,SAAS,oBACT,gBAAgB,WAChB,MAAM,aACN,EAAE,CACH;AAED,YAAO,KAAK;MACV,QAAQ,MAAM,OAAO,aAAa;MAClC,MAAM,GAAG,YAAY,MAAM,SAAS,MAAM,KAAK,MAAM;MACrD,YAAY,gBAAgB;MAC5B,SAAS,MAAM;MACf,YAAY,CACV,GAAG,gBAAgB,KAAK,MAAW,EAAE,QAAQ,YAAY,EACzD,GAAG,iBAAiB,KAAK,MAAW,EAAE,QAAQ,YAAY,CAC3D;MACF,CAAC;;;GAIN,WAAW,EAAE,UAAU;AACrB,QAAI,CAAC,QAAS;AAKd,QAAI,OAAQ,MAAK,cAAc,OAAO;AACtC,QAAI,KACF,oBAAoB,OAAO,OAAO,mBAC7B,WAAW,kBAAkB,CAAC,UAAU,EAAE,6BAC7B,SAAS,OAC5B;;GAGH,WAAW;AACT,sBAAkB;AAClB,oBAAgB,MAAM;AACtB,oBAAgB,MAAM;AACtB,SAAK,OAAO;AACZ,oBAAgB,qBAAqB;;GAExC;;CAEJ,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["serveStatic"],"sources":["../src/topology.ts","../src/devtools-tabs.ts","../src/bus/server.ts","../src/adapter.ts"],"sourcesContent":["/**\n * Topology aggregator — walks the running KickJS application + DI\n * container and produces a JSON-serialisable {@link TopologySnapshot}.\n *\n * Calls `introspect()` on every plugin and adapter that implements it\n * (architecture.md §23.3); falls back to a minimal `{ protocolVersion,\n * name, kind }` stub for primitives that don't. Per-primitive\n * introspection failures are caught + collected into the snapshot's\n * `errors` field rather than failing the entire endpoint.\n *\n * @module @forinda/kickjs-devtools/topology\n */\n\nimport type { AppAdapter, Container, KickPlugin } from '@forinda/kickjs'\nimport {\n PROTOCOL_VERSION,\n type IntrospectionSnapshot,\n type TopologyContributorEntry,\n type TopologyError,\n type TopologySnapshot,\n type TopologyTokenEntry,\n} from '@forinda/kickjs-devtools-kit'\n\n/** Minimal Application surface the aggregator needs — keeps coupling thin. */\nexport interface TopologyApplicationLike {\n getAdapters(): AppAdapter[]\n getPlugins(): readonly KickPlugin[]\n /**\n * Optional in older Application implementations — when present, returns\n * the union of contributors across adapters/plugins/global with proper\n * source labels. The topology aggregator prefers this over walking\n * `adapter.contributors()` + `plugin.contributors()` directly because\n * the application-level walk preserves source provenance.\n */\n getContributors?(): ReadonlyArray<{\n key: string\n source: 'adapter' | 'plugin' | 'module' | 'global'\n label: string\n dependsOn: readonly string[]\n }>\n}\n\n/** Inputs to {@link collectTopologySnapshot}. */\nexport interface CollectTopologyOptions {\n /** The running KickJS application (or anything that exposes its surface). */\n app: TopologyApplicationLike\n /** The DI container — used to enumerate registered tokens. */\n container: Container\n /**\n * Optional per-call introspect timeout in milliseconds. An adapter\n * whose `introspect()` doesn't settle within the budget gets a stub\n * snapshot + an entry in `errors`. Default: 100ms — keeps the\n * topology endpoint snappy even if one adapter misbehaves.\n */\n introspectTimeoutMs?: number\n}\n\nconst DEFAULT_INTROSPECT_TIMEOUT_MS = 100\n\n/**\n * Collect a {@link TopologySnapshot} for the given application.\n *\n * Async because plugin/adapter `introspect()` may be async; the work\n * is parallelised across all primitives so wall-clock time scales\n * with the slowest introspector, not their sum.\n */\nexport async function collectTopologySnapshot(\n opts: CollectTopologyOptions,\n): Promise<TopologySnapshot> {\n const { app, container, introspectTimeoutMs = DEFAULT_INTROSPECT_TIMEOUT_MS } = opts\n const errors: TopologyError[] = []\n\n const plugins = await Promise.all(\n app.getPlugins().map((p) => snapshotFor(p, 'plugin', introspectTimeoutMs, errors)),\n )\n const adapters = await Promise.all(\n app.getAdapters().map((a) => snapshotFor(a, 'adapter', introspectTimeoutMs, errors)),\n )\n\n return {\n protocolVersion: PROTOCOL_VERSION,\n timestamp: Date.now(),\n plugins,\n adapters,\n contributors: collectContributors(app),\n diTokens: collectTokens(container),\n errors,\n }\n}\n\n/**\n * Coerce one primitive into an {@link IntrospectionSnapshot}. Tries\n * the primitive's own `introspect()` first; falls back to a stub on\n * any of: missing implementation, throw, timeout, or non-object return.\n */\nasync function snapshotFor(\n primitive: AppAdapter | KickPlugin,\n kind: 'plugin' | 'adapter',\n timeoutMs: number,\n errors: TopologyError[],\n): Promise<IntrospectionSnapshot> {\n const name = primitive.name ?? '(unnamed)'\n const stub: IntrospectionSnapshot = {\n protocolVersion: PROTOCOL_VERSION,\n name,\n kind,\n }\n if (typeof primitive.introspect !== 'function') return stub\n\n try {\n const result = await Promise.race([\n Promise.resolve(primitive.introspect()),\n new Promise<never>((_, reject) =>\n setTimeout(\n () => reject(new Error(`introspect() timed out after ${timeoutMs}ms`)),\n timeoutMs,\n ),\n ),\n ])\n if (result && typeof result === 'object') {\n // Accept whatever the primitive returned; the kit's\n // IntrospectionSnapshot is opt-in typed via the kit, not enforced\n // at this layer (see plugin.ts / adapter.ts comment about avoiding\n // a runtime dep on the kit).\n const snap = result as Partial<IntrospectionSnapshot>\n return {\n protocolVersion: PROTOCOL_VERSION,\n name: snap.name ?? name,\n kind: snap.kind ?? kind,\n version: snap.version,\n state: snap.state,\n tokens: snap.tokens,\n metrics: snap.metrics,\n memoryBytes: snap.memoryBytes,\n }\n }\n return stub\n } catch (err) {\n errors.push({\n name,\n kind,\n message: err instanceof Error ? err.message : String(err),\n })\n return stub\n }\n}\n\n/** Read DI registrations into the topology shape — drops noisy HMR tokens. */\nfunction collectTokens(container: Container): TopologyTokenEntry[] {\n return container\n .getRegistrations()\n .filter((r) => !r.token.startsWith('__hmr__'))\n .map((r) => ({\n token: r.token,\n scope: r.scope,\n kind: r.kind,\n instantiated: r.instantiated,\n }))\n}\n\n/**\n * Contributor enumeration. Prefers `app.getContributors()` (the\n * Application-level walk that preserves adapter / plugin / global\n * source labels) when present; falls back to walking\n * `adapter.contributors()` + `plugin.contributors()` directly for\n * older Application implementations that don't expose the helper.\n *\n * Module-level contributors are still not surfaced here — module\n * instances aren't retained post-bootstrap. Per-route enumeration\n * lands in a later iteration alongside the route detail panel.\n */\nfunction collectContributors(app: TopologyApplicationLike): TopologyContributorEntry[] {\n const seen = new Map<string, TopologyContributorEntry>()\n\n if (typeof app.getContributors === 'function') {\n for (const c of app.getContributors()) {\n if (seen.has(c.key)) continue\n // The kit's source enum currently only allows 'adapter' | 'module';\n // 'plugin' + 'global' both map to 'adapter' provenance for now —\n // the Topology UI labels them by `label` so the source field is\n // mainly a coarse category. Future kit version can widen.\n const mapped: TopologyContributorEntry['source'] =\n c.source === 'module' ? 'module' : 'adapter'\n seen.set(c.key, {\n key: c.key,\n source: mapped,\n dependsOn: c.dependsOn as string[],\n })\n }\n return [...seen.values()]\n }\n\n // Legacy path — direct walk.\n const ingest = (\n list: ReadonlyArray<unknown> | null | undefined,\n source: TopologyContributorEntry['source'],\n ): void => {\n if (!list) return\n for (const reg of list) {\n const r = reg as { key?: string; dependsOn?: readonly string[] }\n const key = typeof r.key === 'string' ? r.key : null\n if (!key || seen.has(key)) continue\n seen.set(key, {\n key,\n source,\n dependsOn: Array.isArray(r.dependsOn) ? r.dependsOn : [],\n })\n }\n }\n\n for (const plugin of app.getPlugins()) {\n ingest(plugin.contributors?.(), 'adapter')\n }\n for (const adapter of app.getAdapters()) {\n ingest(adapter.contributors?.(), 'adapter')\n }\n\n return [...seen.values()]\n}\n","/**\n * Custom-tab aggregator — collects every plugin/adapter's\n * `devtoolsTabs()` contribution into a single deduped list for the\n * panel's `/_debug/tabs` endpoint.\n *\n * Validation is permissive: anything that doesn't look like a\n * {@link DevtoolsTabDescriptor} is dropped with a console warning\n * rather than throwing — a misconfigured adapter shouldn't break the\n * whole DevTools panel.\n *\n * @module @forinda/kickjs-devtools/devtools-tabs\n */\n\nimport type { DevtoolsTabDescriptor } from '@forinda/kickjs-devtools-kit'\nimport type { TopologyApplicationLike } from './topology'\n\n/** Result of {@link collectDevtoolsTabs}. */\nexport interface DevtoolsTabsResult {\n /** Deduped, validated tabs in registration order. */\n tabs: DevtoolsTabDescriptor[]\n /** Per-source collection errors (drop reason, source name). */\n errors: ReadonlyArray<{ source: string; reason: string }>\n}\n\nconst VALID_VIEW_TYPES = new Set(['iframe', 'launch', 'html'])\n\n/**\n * Walk every plugin + adapter, call `devtoolsTabs?()`, validate each\n * entry, and dedupe by `id`. Last-source-wins on collision is too\n * surprising — first-source-wins + a warning entry instead.\n */\nexport function collectDevtoolsTabs(app: TopologyApplicationLike): DevtoolsTabsResult {\n const tabs: DevtoolsTabDescriptor[] = []\n const seen = new Map<string, string>() // id → source name (for collision warnings)\n const errors: Array<{ source: string; reason: string }> = []\n\n const ingest = (sourceName: string, raw: unknown): void => {\n if (!Array.isArray(raw)) {\n errors.push({ source: sourceName, reason: 'devtoolsTabs() did not return an array' })\n return\n }\n for (const entry of raw) {\n const validation = validateTab(entry)\n if (!validation.ok) {\n errors.push({ source: sourceName, reason: validation.reason })\n continue\n }\n const tab = validation.tab\n const owner = seen.get(tab.id)\n if (owner) {\n errors.push({\n source: sourceName,\n reason: `tab id '${tab.id}' already registered by ${owner} — first-source wins`,\n })\n continue\n }\n seen.set(tab.id, sourceName)\n tabs.push(tab)\n }\n }\n\n for (const plugin of app.getPlugins()) {\n if (typeof plugin.devtoolsTabs !== 'function') continue\n try {\n ingest(plugin.name ?? '(unnamed plugin)', plugin.devtoolsTabs())\n } catch (err) {\n errors.push({\n source: plugin.name ?? '(unnamed plugin)',\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n for (const adapter of app.getAdapters()) {\n if (typeof adapter.devtoolsTabs !== 'function') continue\n try {\n ingest(adapter.name ?? '(unnamed adapter)', adapter.devtoolsTabs())\n } catch (err) {\n errors.push({\n source: adapter.name ?? '(unnamed adapter)',\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n return { tabs, errors }\n}\n\ninterface ValidationOk {\n ok: true\n tab: DevtoolsTabDescriptor\n}\n\ninterface ValidationFail {\n ok: false\n reason: string\n}\n\n/**\n * Coerce + validate a tab descriptor. Returns the typed object on\n * success; a structured reason on failure. Uses a permissive checker\n * so a partially-correct entry from a third-party adapter doesn't\n * break the whole panel.\n */\nfunction validateTab(raw: unknown): ValidationOk | ValidationFail {\n if (!raw || typeof raw !== 'object') {\n return { ok: false, reason: 'tab entry is not an object' }\n }\n const obj = raw as Record<string, unknown>\n if (typeof obj.id !== 'string' || obj.id.length === 0) {\n return { ok: false, reason: 'tab.id must be a non-empty string' }\n }\n if (typeof obj.title !== 'string' || obj.title.length === 0) {\n return { ok: false, reason: `tab '${obj.id}': title must be a non-empty string` }\n }\n const view = obj.view as Record<string, unknown> | undefined\n if (!view || typeof view !== 'object') {\n return { ok: false, reason: `tab '${obj.id}': view object is required` }\n }\n if (typeof view.type !== 'string' || !VALID_VIEW_TYPES.has(view.type)) {\n return {\n ok: false,\n reason: `tab '${obj.id}': view.type must be one of iframe / launch / html`,\n }\n }\n switch (view.type) {\n case 'iframe':\n if (typeof view.src !== 'string' || view.src.length === 0) {\n return { ok: false, reason: `tab '${obj.id}': iframe view requires a non-empty src` }\n }\n break\n case 'html':\n if (typeof view.html !== 'string') {\n return { ok: false, reason: `tab '${obj.id}': html view requires html string` }\n }\n break\n case 'launch':\n if (!Array.isArray(view.actions)) {\n return { ok: false, reason: `tab '${obj.id}': launch view requires actions array` }\n }\n break\n }\n return { ok: true, tab: obj as unknown as DevtoolsTabDescriptor }\n}\n","// Server-side KickEventBus implementation.\n//\n// Wraps the bus core from `@forinda/kickjs-devtools-kit/bus` with a\n// `ws` server bound to a path on the framework's existing\n// `http.Server`. Architecture:\n//\n// server.on('upgrade') ─┐\n// ├──► WebSocketServer.handleUpgrade()\n// │ └─► ws clients: receive emits as JSON\n// bus.emit(type, payload) ─┴──► serialize → fan out to clients +\n// dispatch locally to in-process subs\n//\n// Why piggyback on the framework's http.Server instead of starting a\n// dedicated WS server: the framework already owns the listener, the\n// upgrade event is the canonical hook, and reusing it means devtools\n// inherits whatever TLS / proxy / port config the application provides.\n//\n// Lifecycle:\n// - createServerBus() builds the WebSocketServer in `noServer: true`\n// mode (no listener of its own) and returns the bus + attach/close\n// handles.\n// - attachUpgrade(httpServer) wires server.on('upgrade') so upgrades\n// matching `wsPath` route into the WebSocketServer. Other upgrade\n// paths (kickjs-ws, etc.) ignore us by virtue of path matching.\n// - close() drops every client and detaches from the http server so\n// repeated dev-mode restarts don't leak listener handles.\n//\n// Authentication:\n// - The optional `secret` matches the devtools panel's existing\n// `x-devtools-token` / `?token=` access guard. When set, upgrades\n// without the right token get rejected at HTTP-handshake time —\n// never reaching the bus.\n//\n// Loop avoidance:\n// - Server emits fan out to every connected client. Client-side\n// emits sent UP the socket dispatch into the local core (so\n// server tabs can react) but are NOT re-broadcast to other\n// clients. This keeps the same \"no echo\" contract the browser\n// bus enforces; without it a tab's emit would round-trip through\n// the server and back to itself.\n\nimport type { IncomingMessage } from 'node:http'\nimport type http from 'node:http'\nimport type { Socket } from 'node:net'\n\nimport { createBusCore } from '@forinda/kickjs-devtools-kit/bus'\nimport type { KickDevtoolsEvent, KickEventBus, Unsubscribe } from '@forinda/kickjs-devtools-kit/bus'\nimport { WebSocketServer, type WebSocket } from 'ws'\n\nexport interface ServerBusOptions {\n /** Path the WebSocket upgrade listens on. Default `/_debug/_bus`. */\n wsPath?: string\n /**\n * Optional shared secret. When set, clients must include either\n * `?token=<secret>` on the upgrade URL or an\n * `x-devtools-token: <secret>` header. Unauthorized upgrades return\n * 401 and never reach the bus. Pass `false` (or omit) to disable.\n */\n secret?: string | false\n}\n\ninterface TaggedEnvelope extends KickDevtoolsEvent {\n __kick_origin?: 'local' | 'broadcast' | 'ws'\n}\n\nexport interface ServerBus extends KickEventBus {\n /** Hook into an existing http.Server's `upgrade` event. */\n attachUpgrade(httpServer: http.Server): void\n /** Drop all clients + detach. Idempotent. */\n close(): void\n /** Currently connected client count. Useful for the devtools health card. */\n clientCount(): number\n}\n\nexport function createServerBus(opts: ServerBusOptions = {}): ServerBus {\n const wsPath = opts.wsPath ?? '/_debug/_bus'\n const secret = opts.secret ?? false\n const core = createBusCore()\n const wss = new WebSocketServer({ noServer: true })\n const clients = new Set<WebSocket>()\n let attachedServer: http.Server | null = null\n let upgradeHandler: ((req: IncomingMessage, socket: Socket, head: Buffer) => void) | null = null\n\n wss.on('connection', (ws: WebSocket) => {\n clients.add(ws)\n ws.on('message', (data: Buffer | string) => {\n try {\n const text = typeof data === 'string' ? data : data.toString('utf-8')\n const parsed = JSON.parse(text) as TaggedEnvelope\n if (!parsed || typeof parsed.type !== 'string' || typeof parsed.ts !== 'number') return\n // Dispatch locally only — never echo back to other clients.\n // (Tabs that need cross-tab fan-out use BroadcastChannel; the\n // server is point-to-point per client.)\n core.dispatch({ ...parsed, __kick_origin: 'ws' } as KickDevtoolsEvent)\n } catch {\n // Malformed — drop silently. A misbehaving tab shouldn't\n // crash the server bus.\n }\n })\n ws.on('close', () => {\n clients.delete(ws)\n })\n ws.on('error', () => {\n clients.delete(ws)\n })\n })\n\n const fanOut = (envelope: TaggedEnvelope): void => {\n if (clients.size === 0) return\n const text = JSON.stringify(envelope)\n for (const client of clients) {\n // OPEN === 1 in the ws spec; reusing the import for the type\n // guard keeps this readable without pulling in WebSocket consts.\n if (client.readyState === client.OPEN) {\n try {\n client.send(text)\n } catch {\n // Network error mid-fan-out — clean removal happens via the\n // 'close' / 'error' handlers; nothing to do here.\n }\n }\n }\n }\n\n const checkAuth = (req: IncomingMessage): boolean => {\n if (secret === false) return true\n const header = req.headers['x-devtools-token']\n if (typeof header === 'string' && header === secret) return true\n // Parse query — `req.url` is path + ?query for upgrade requests.\n const url = req.url ?? ''\n const queryIdx = url.indexOf('?')\n if (queryIdx === -1) return false\n const params = new URLSearchParams(url.slice(queryIdx + 1))\n return params.get('token') === secret\n }\n\n const attachUpgrade = (httpServer: http.Server): void => {\n if (attachedServer) return // idempotent\n attachedServer = httpServer\n upgradeHandler = (req, socket, head) => {\n // Path match — ignore upgrades destined for other adapters\n // (kickjs-ws, custom adapters, etc.). They register their own\n // upgrade handlers; ours just no-ops on non-matching URLs.\n const url = req.url ?? ''\n const pathOnly = url.split('?')[0]\n if (pathOnly !== wsPath) return\n\n if (!checkAuth(req)) {\n socket.write('HTTP/1.1 401 Unauthorized\\r\\n\\r\\n')\n socket.destroy()\n return\n }\n\n wss.handleUpgrade(req, socket, head, (ws: WebSocket) => {\n wss.emit('connection', ws, req)\n })\n }\n httpServer.on('upgrade', upgradeHandler)\n }\n\n const close = (): void => {\n if (attachedServer && upgradeHandler) {\n attachedServer.off('upgrade', upgradeHandler)\n }\n attachedServer = null\n upgradeHandler = null\n for (const client of clients) {\n try {\n client.close()\n } catch {\n // ignore\n }\n }\n clients.clear()\n wss.close()\n }\n\n return {\n on(type: string, handler: (payload: unknown) => void): Unsubscribe {\n return core.on(type, handler)\n },\n onAny(handler: (event: KickDevtoolsEvent) => void): Unsubscribe {\n return core.onAny(handler)\n },\n emit(type: string, payload: unknown): void {\n const envelope: TaggedEnvelope = {\n type,\n payload,\n ts: Date.now(),\n __kick_origin: 'local',\n }\n core.dispatch(envelope)\n fanOut(envelope)\n },\n attachUpgrade,\n close,\n clientCount: () => clients.size,\n } as ServerBus\n}\n","import type { Request, Response, NextFunction } from 'express'\nimport { Router, static as serveStatic } from 'express'\nimport { dirname, join } from 'node:path'\nimport { tmpdir } from 'node:os'\nimport { fileURLToPath } from 'node:url'\nimport { createReadStream, existsSync, readFileSync, statSync, unlink } from 'node:fs'\nimport { randomBytes } from 'node:crypto'\nimport { writeHeapSnapshot } from 'node:v8'\nimport {\n type AdapterMiddleware,\n type Container,\n METADATA,\n defineAdapter,\n ref,\n computed,\n reactive,\n watch,\n createLogger,\n type Ref,\n type ComputedRef,\n getClassMeta,\n getMethodMeta,\n} from '@forinda/kickjs'\nimport {\n MemoryAnalyzer,\n PROTOCOL_VERSION,\n RuntimeSampler,\n type IntrospectionSnapshot,\n} from '@forinda/kickjs-devtools-kit'\nimport { DEVTOOLS_BUS } from '@forinda/kickjs-devtools-kit/bus/token'\nimport { collectTopologySnapshot, type TopologyApplicationLike } from './topology'\nimport { collectDevtoolsTabs } from './devtools-tabs'\nimport { createServerBus, type ServerBus } from './bus/server'\n\nconst log = createLogger('DevTools')\n\n/** Route metadata collected during mount */\ninterface RouteInfo {\n method: string\n path: string\n controller: string\n handler: string\n middleware: string[]\n}\n\n/** Per-route latency stats with percentile tracking */\ninterface RouteStats {\n count: number\n totalMs: number\n minMs: number\n maxMs: number\n /** Ring buffer of last N samples for percentile computation */\n samples: number[]\n}\n\nconst MAX_SAMPLES = 1000\n\n/** Compute a percentile from a sorted array of numbers */\nfunction percentile(sorted: number[], p: number): number {\n if (sorted.length === 0) return 0\n const idx = Math.ceil(p * sorted.length) - 1\n return sorted[Math.max(0, idx)]\n}\n\n/** Compute p50, p95, p99 from a RouteStats samples buffer */\nfunction computePercentiles(stats: RouteStats): { p50: number; p95: number; p99: number } {\n const sorted = [...stats.samples].toSorted((a, b) => a - b)\n return {\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n p99: percentile(sorted, 0.99),\n }\n}\n\n/**\n * Open an SSE response — sets the headers, flushes them, and disables\n * any compression middleware that may have been registered upstream\n * (compression buffers SSE chunks indefinitely; we need flush-on-write).\n */\nfunction openSseStream(req: Request, res: Response): void {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n })\n res.flushHeaders?.()\n // Defensive: the compression middleware checks this header. Some\n // setups also wrap res.write — calling res.flush after each write\n // is safe even when no compression is in play.\n void req\n}\n\n/** Write a single SSE `data:` event with a JSON payload + double newline. */\nfunction writeSseEvent(res: Response, payload: unknown): void {\n res.write(`data: ${JSON.stringify(payload)}\\n\\n`)\n}\n\n/**\n * Race a promise against a timeout. Clears the timer when the inner\n * promise wins so we don't leak handles every time a peer responds\n * quickly. Used to bound peer `onHealthCheck()` calls inside the\n * `/_debug/health` handler — one slow peer must not be able to stall\n * the dashboard request.\n */\nfunction raceWithTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)\n })\n return Promise.race([promise, timeout]).finally(() => {\n if (timer) clearTimeout(timer)\n })\n}\n\n/**\n * Per-peer budget for `onHealthCheck()` inside `/_debug/health`.\n * Long enough for a typical DB ping or remote check, short enough that\n * one misbehaving adapter can't stall the dashboard endpoint.\n */\nconst PEER_HEALTHCHECK_TIMEOUT_MS = 1500\n\n/**\n * Module-scoped guard for `POST /_debug/memory/snapshot`. `writeHeapSnapshot()`\n * blocks the event loop for the duration of the capture (multi-second\n * for large heaps); two concurrent captures would compound the pause.\n * The endpoint returns 503 + a hint message when this flag is set so\n * the SPA can surface a \"snapshot already running\" warning rather than\n * silently queueing.\n *\n * Module-scoped (not per-adapter-instance) because writeHeapSnapshot\n * acts on the V8 process — multiple DevToolsAdapter instances would\n * still race at the v8 layer.\n */\nlet snapshotInProgress = false\n\nexport interface DevToolsOptions {\n /** Base path for debug endpoints (default: '/_debug') */\n basePath?: string\n /** Only enable when this is true (default: process.env.NODE_ENV !== 'production') */\n enabled?: boolean\n /** Include environment variables (sanitized) at /_debug/config (default: false) */\n exposeConfig?: boolean\n /** Env var prefixes to expose (default: ['APP_', 'NODE_ENV']). Others are redacted. */\n configPrefixes?: string[]\n /** Callback when error rate exceeds threshold */\n onErrorRateExceeded?: (rate: number) => void\n /** Error rate threshold (default: 0.5 = 50%) */\n errorRateThreshold?: number\n /** Other adapters to discover stats from (e.g., WsAdapter) */\n adapters?: any[]\n\n /**\n * Secret token to guard DevTools access. When set, all requests must\n * include this token as `x-devtools-token` header or `?token=` query param.\n *\n * Auto-generated on startup if not provided. The token is logged to the console.\n * Set to `false` to disable the guard entirely (not recommended).\n *\n * @example\n * ```ts\n * DevToolsAdapter({ secret: getEnv('DEVTOOLS_SECRET') })\n * ```\n */\n secret?: string | false\n\n /**\n * Tuning for the runtime sampler that powers `/_debug/runtime` and\n * the upcoming Memory tab (architecture.md §23). Defaults to\n * 1-second polling with a 60-sample (~1 minute) ring buffer.\n *\n * Set `runtime.enabled = false` to skip starting the sampler — the\n * `/_debug/runtime` endpoint then returns 404 instead of an empty\n * snapshot, signalling deliberate opt-out rather than a startup race.\n */\n runtime?: {\n /** Whether to start the runtime sampler at all. Default: true. */\n enabled?: boolean\n /** Polling interval in milliseconds. Default: 1000. */\n intervalMs?: number\n /** Ring-buffer size — number of past samples retained. Default: 60. */\n bufferSize?: number\n }\n}\n\n/**\n * Public reactive surface exposed by a DevToolsAdapter instance —\n * counters, computed metrics, and the route latency map. Tests and\n * peer adapters consume these directly to drive their own behavior.\n */\nexport interface DevToolsAdapterExtensions {\n /** Total requests received. */\n readonly requestCount: Ref<number>\n /** Total responses with status >= 500. */\n readonly errorCount: Ref<number>\n /** Total responses with status >= 400 and < 500. */\n readonly clientErrorCount: Ref<number>\n /** Server start time. */\n readonly startedAt: Ref<number>\n /** Computed error rate (server errors / total requests). */\n readonly errorRate: ComputedRef<number>\n /** Computed uptime in seconds. */\n readonly uptimeSeconds: ComputedRef<number>\n /** Per-route latency tracking. */\n readonly routeLatency: Record<string, RouteStats>\n /**\n * Tier-1 runtime sampler from `@forinda/kickjs-devtools-kit`. `null`\n * when `runtime.enabled` is `false`. Tests can `latest()` and\n * `history()` directly without going through the HTTP endpoint.\n */\n readonly runtimeSampler: RuntimeSampler | null\n /**\n * Memory analyzer fed by the runtime sampler. `null` when the\n * sampler is disabled. Use `analyzer.health(sampler.history())` to\n * compose a composite memory-health snapshot.\n */\n readonly memoryAnalyzer: MemoryAnalyzer | null\n}\n\n/**\n * DevToolsAdapter — Vue-style reactive introspection for KickJS applications.\n *\n * Exposes debug endpoints powered by reactive state (ref, computed, watch):\n * - `GET /_debug/routes` — all registered routes with middleware\n * - `GET /_debug/container` — DI registry with scopes and instantiation status\n * - `GET /_debug/metrics` — live request/error counts, error rate, uptime\n * - `GET /_debug/health` — deep health check with adapter status\n * - `GET /_debug/config` — sanitized environment variables (opt-in)\n * - `GET /_debug/state` — full reactive state snapshot\n *\n * @example\n * ```ts\n * import { DevToolsAdapter } from '@forinda/kickjs-devtools'\n *\n * bootstrap({\n * modules: [UserModule],\n * adapters: [\n * DevToolsAdapter({\n * enabled: process.env.NODE_ENV !== 'production',\n * exposeConfig: true,\n * configPrefixes: ['APP_', 'DATABASE_'],\n * }),\n * ],\n * })\n * ```\n */\nexport const DevToolsAdapter = defineAdapter<DevToolsOptions, DevToolsAdapterExtensions>({\n name: 'DevToolsAdapter',\n defaults: {\n basePath: '/_debug',\n errorRateThreshold: 0.5,\n exposeConfig: false,\n configPrefixes: ['APP_', 'NODE_ENV'],\n },\n build: (options) => {\n const basePath = options.basePath!\n const enabled = options.enabled ?? process.env.NODE_ENV !== 'production'\n const exposeConfig = options.exposeConfig!\n const configPrefixes = options.configPrefixes!\n const errorRateThreshold = options.errorRateThreshold!\n const peerAdapters = options.adapters ?? []\n\n // Secret token guard\n let secret: string | false\n if (options.secret === false) {\n secret = false\n } else if (options.secret) {\n secret = options.secret\n } else {\n secret = randomBytes(16).toString('hex')\n }\n\n // ── Runtime sampler + memory analyzer (kit) ────────────────────\n // Lazily instantiated so an adopter that disables runtime monitoring\n // doesn't pay the perf_hooks histogram cost. Lifecycle: start in\n // `beforeMount`, stop in `shutdown`.\n const runtimeEnabled = options.runtime?.enabled ?? true\n const runtimeSampler = runtimeEnabled\n ? new RuntimeSampler({\n intervalMs: options.runtime?.intervalMs ?? 1000,\n bufferSize: options.runtime?.bufferSize ?? 60,\n })\n : null\n const memoryAnalyzer = runtimeEnabled ? new MemoryAnalyzer() : null\n\n // ── Server-side event bus ──────────────────────────────────────\n // Lazily resolved in `beforeMount` — when the devtools adapter is\n // rebuilt during HMR, the same `Container` may already hold a bus\n // from a previous mount with live WebSocket clients + in-flight\n // subscriptions. Creating a fresh bus on every rebuild would\n // silently swap the registered instance, leaving plugins that\n // already captured the old reference publishing into a dead bus.\n // Using `container.has(DEVTOOLS_BUS)` to reuse instead keeps event\n // delivery stable across rebuilds.\n //\n // When the devtools adapter is disabled (`enabled === false`) we\n // register a no-op stub instead so adopters who Inject(DEVTOOLS_BUS)\n // under @Optional() get a callable instance rather than undefined.\n let bus: ServerBus | null = null\n\n const ensureBus = (container: Container): ServerBus => {\n if (container.has(DEVTOOLS_BUS)) {\n // The token is typed `KickEventBus` but the registered instance\n // is the wider `ServerBus` (KickEventBus + attachUpgrade /\n // close / clientCount). Explicit generic on resolve avoids the\n // structural-cast — Container.resolve's last overload accepts\n // an explicit T and returns it.\n bus = container.resolve<ServerBus>(DEVTOOLS_BUS)\n return bus\n }\n bus = enabled\n ? createServerBus({\n wsPath: `${basePath}/_bus`,\n secret: secret === false ? false : secret,\n })\n : ({\n on: () => () => {},\n onAny: () => () => {},\n emit: () => {},\n attachUpgrade: () => {},\n close: () => {},\n clientCount: () => 0,\n } as ServerBus)\n container.registerInstance(DEVTOOLS_BUS, bus)\n return bus\n }\n\n // ── Reactive state ─────────────────────────────────────────────\n const requestCount = ref(0)\n const errorCount = ref(0)\n const clientErrorCount = ref(0)\n const startedAt = ref(Date.now())\n const routeLatency = reactive<Record<string, RouteStats>>({})\n\n const errorRate = computed(() =>\n requestCount.value > 0 ? errorCount.value / requestCount.value : 0,\n )\n\n const uptimeSeconds = computed(() => Math.floor((Date.now() - startedAt.value) / 1000))\n\n // ── Internal mutable state ─────────────────────────────────────\n let routes: RouteInfo[] = []\n let container: Container | null = null\n let appRef: any = null\n const adapterStatuses: Record<string, string> = {}\n let stopErrorWatch: (() => void) | null = null\n\n // Watch error rate — log warnings when elevated\n if (options.onErrorRateExceeded) {\n const callback = options.onErrorRateExceeded\n stopErrorWatch = watch(errorRate, (rate) => {\n if (rate > errorRateThreshold) {\n callback(rate)\n }\n })\n } else {\n stopErrorWatch = watch(errorRate, (rate) => {\n if (rate > errorRateThreshold) {\n log.warn(`Error rate elevated: ${(rate * 100).toFixed(1)}%`)\n }\n })\n }\n\n /**\n * Find the dashboard's public directory. Prefers the new Solid SPA\n * (public/spa/, shipped from PR 4 of §23); falls back to the legacy\n * Vue+Tailwind dashboard (public/devtools/) for environments that\n * haven't run `pnpm --filter @forinda/kickjs-devtools build:spa`.\n */\n const resolvePublicDir = (): string | null => {\n const thisDir = dirname(fileURLToPath(import.meta.url))\n const candidates = [\n join(thisDir, '..', 'public', 'spa'), // dist/ -> public/spa\n join(thisDir, '..', '..', 'public', 'spa'), // src/ -> public/spa\n join(thisDir, '..', 'public', 'devtools'), // legacy Vue dashboard\n join(thisDir, '..', '..', 'public', 'devtools'), // legacy from src/\n ]\n for (const dir of candidates) {\n if (existsSync(join(dir, 'index.html'))) return dir\n }\n return null\n }\n\n /**\n * Resolve peer adapters at request time. Prefers live adapters from the\n * Application registry (survives HMR rebuild) and falls back to the\n * constructor-provided refs.\n */\n const getPeerAdapters = (): any[] => {\n const kickApp = appRef?.__kickApp\n if (kickApp && typeof kickApp.getAdapters === 'function') {\n return kickApp.getAdapters()\n }\n return peerAdapters\n }\n\n return {\n // ── Extensions (TExtra) ───────────────────────────────────────\n requestCount,\n errorCount,\n clientErrorCount,\n startedAt,\n errorRate,\n uptimeSeconds,\n routeLatency,\n runtimeSampler,\n memoryAnalyzer,\n\n // ── DevTools introspection (architecture.md §23) ─────────────\n // Cheap snapshot — counters + flags only. Anything that requires\n // a container walk or DB hit belongs in the per-endpoint RPCs\n // (`/_debug/container`, `/_debug/graph`), not here.\n introspect(): IntrospectionSnapshot {\n return {\n protocolVersion: PROTOCOL_VERSION,\n name: 'DevToolsAdapter',\n kind: 'adapter',\n state: {\n basePath,\n enabled,\n runtimeEnabled,\n secret: secret === false ? false : 'present',\n },\n metrics: {\n requestCount: requestCount.value,\n serverErrors: errorCount.value,\n clientErrors: clientErrorCount.value,\n uptimeSeconds: uptimeSeconds.value,\n routesTracked: routes.length,\n },\n }\n },\n\n // ── Lifecycle ─────────────────────────────────────────────────\n\n beforeMount({ app, container: containerArg }) {\n if (!enabled) return\n\n appRef = app\n container = containerArg\n // Lazy resolve — reuses the existing bus when the same\n // container is reused across HMR rebuilds, otherwise creates\n // and registers a fresh instance. See `ensureBus` for why.\n ensureBus(containerArg)\n startedAt.value = Date.now()\n // Clear routes on rebuild/restart to prevent HMR duplication\n routes = []\n adapterStatuses['DevToolsAdapter'] = 'running'\n\n // Start the runtime sampler + memory analyzer here (rather than\n // at construction) so test harnesses that build the adapter but\n // never mount it don't leak interval timers.\n runtimeSampler?.start()\n memoryAnalyzer?.start()\n\n const router = Router()\n\n // ── Access guard — require secret token ──────────────────\n if (secret !== false) {\n const token = secret\n router.use((req: Request, res: Response, next: NextFunction) => {\n const provided = req.headers['x-devtools-token'] ?? req.query?.token\n if (provided === token) return next()\n // Allow the dashboard HTML itself (it will include the token in API calls)\n if (req.path === '/' && req.method === 'GET' && !req.query?.token) {\n return next() // serve dashboard, it handles auth via token\n }\n // Serve static assets for the dashboard (js files)\n if (req.path.endsWith('.js') || req.path.endsWith('.css')) {\n return next()\n }\n res.status(403).json({ error: 'Forbidden — invalid or missing devtools token' })\n })\n }\n\n router.get('/routes', (_req: Request, res: Response) => {\n res.json({ routes })\n })\n\n router.get('/container', (_req: Request, res: Response) => {\n const registrations = container?.getRegistrations() ?? []\n res.json({ registrations, count: registrations.length })\n })\n\n router.get('/metrics', (_req: Request, res: Response) => {\n // Build latency with percentiles, omitting raw samples from response\n const latency: Record<string, any> = {}\n for (const [key, stats] of Object.entries(routeLatency)) {\n const { samples: _, ...rest } = stats\n latency[key] = { ...rest, ...computePercentiles(stats) }\n }\n res.json({\n requests: requestCount.value,\n serverErrors: errorCount.value,\n clientErrors: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n startedAt: new Date(startedAt.value).toISOString(),\n routeLatency: latency,\n })\n })\n\n router.get('/health', async (_req: Request, res: Response) => {\n const healthy = errorRate.value < errorRateThreshold\n const status = healthy ? 'healthy' : 'degraded'\n\n // Refresh peer statuses from `onHealthCheck()` when present.\n // The static `adapterStatuses` dict (seeded in `afterStart`)\n // proves a peer was mounted; calling `onHealthCheck()` here\n // upgrades that to a live `up`/`down`/`degraded` reading so\n // the Overview > Health card reflects actual adapter state,\n // not just \"registered at boot\".\n //\n // Each peer call is bounded by `PEER_HEALTHCHECK_TIMEOUT_MS` —\n // an adapter whose check hangs (network DB ping, remote\n // service, etc.) must not be able to stall the entire\n // dashboard request. Timed-out peers fall through to the\n // catch arm and are reported as `down`.\n const live: Record<string, string> = { ...adapterStatuses }\n await Promise.all(\n getPeerAdapters().map(async (peer) => {\n if (typeof peer?.onHealthCheck !== 'function') return\n const name: unknown = peer?.name\n if (typeof name !== 'string' || name === 'DevToolsAdapter') return\n try {\n const result = await raceWithTimeout(\n Promise.resolve(peer.onHealthCheck()),\n PEER_HEALTHCHECK_TIMEOUT_MS,\n `onHealthCheck(${name})`,\n )\n if (result && typeof result.status === 'string') {\n live[name] = result.status\n }\n } catch {\n live[name] = 'down'\n }\n }),\n )\n\n res.status(healthy ? 200 : 503).json({\n status,\n errorRate: errorRate.value,\n uptime: uptimeSeconds.value,\n adapters: live,\n })\n })\n\n router.get('/state', (_req: Request, res: Response) => {\n const wsAdapter = getPeerAdapters().find(\n (a) => a.name === 'WsAdapter' && typeof a.getStats === 'function',\n )\n res.json({\n reactive: {\n requestCount: requestCount.value,\n errorCount: errorCount.value,\n clientErrorCount: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n startedAt: new Date(startedAt.value).toISOString(),\n },\n routes: routes.length,\n container: container?.getRegistrations().length ?? 0,\n routeLatency,\n ...(wsAdapter ? { ws: wsAdapter.getStats() } : {}),\n })\n })\n\n // ── Tier-1 runtime monitoring (architecture.md §23) ─────────\n // Returns the latest RuntimeSnapshot + a composite MemoryHealth\n // computed from the sampler's ring buffer. Returns 404 when the\n // sampler is disabled so adopters can distinguish \"off\" from\n // \"starting up\".\n router.get('/runtime', (_req: Request, res: Response) => {\n if (!runtimeSampler || !memoryAnalyzer) {\n res.status(404).json({ error: 'runtime sampler disabled — set runtime.enabled = true' })\n return\n }\n const latest = runtimeSampler.latest()\n const history = runtimeSampler.history()\n const health = memoryAnalyzer.health(history)\n res.json({\n protocolVersion: PROTOCOL_VERSION,\n latest,\n history,\n health,\n })\n })\n\n // ── SSE: live runtime snapshots (architecture.md §23) ───────\n // Pushes the latest RuntimeSnapshot every `intervalMs`. SSE\n // (not WebSocket) avoids the http.Server `upgrade`-event\n // coordination cost — see devtools-flows.md §3 for rationale.\n router.get('/runtime/stream', (req: Request, res: Response) => {\n if (!runtimeSampler) {\n res.status(404).json({ error: 'runtime sampler disabled' })\n return\n }\n openSseStream(req, res)\n const intervalMs = options.runtime?.intervalMs ?? 1000\n const tick = (): void => {\n const snap = runtimeSampler.latest()\n if (snap) writeSseEvent(res, snap)\n }\n tick()\n const interval = setInterval(tick, intervalMs)\n const heartbeat = setInterval(() => res.write(': heartbeat\\n\\n'), 30_000)\n req.on('close', () => {\n clearInterval(interval)\n clearInterval(heartbeat)\n })\n })\n\n // ── SSE: memory health composite (architecture.md §23) ──────\n router.get('/memory/stream', (req: Request, res: Response) => {\n if (!runtimeSampler || !memoryAnalyzer) {\n res.status(404).json({ error: 'runtime sampler disabled' })\n return\n }\n openSseStream(req, res)\n const intervalMs = options.runtime?.intervalMs ?? 1000\n const tick = (): void => {\n const snap = runtimeSampler.latest()\n if (!snap) return\n const health = memoryAnalyzer.health(runtimeSampler.history())\n writeSseEvent(res, { snapshot: snap, health })\n }\n tick()\n const interval = setInterval(tick, intervalMs)\n const heartbeat = setInterval(() => res.write(': heartbeat\\n\\n'), 30_000)\n req.on('close', () => {\n clearInterval(interval)\n clearInterval(heartbeat)\n })\n })\n\n // ── Heap snapshot — Tier 3 monitoring (architecture.md §23) ─\n // POST /_debug/memory/snapshot — captures a V8 heap snapshot\n // and streams the resulting .heapsnapshot file back as\n // application/json with Content-Disposition. Snapshot capture\n // blocks the event loop while writing (multi-second pause for\n // large heaps), so the endpoint enforces single-flight via a\n // module-scoped flag — concurrent calls return 503.\n //\n // The temp file is deleted as soon as the response stream\n // completes (success or error). Worst case if the process\n // dies mid-snapshot is a stranded file in `os.tmpdir()`,\n // which the OS cleans up on next boot.\n router.post('/memory/snapshot', (_req: Request, res: Response) => {\n if (snapshotInProgress) {\n res\n .status(503)\n .json({ error: 'heap snapshot already in progress — wait for it to complete' })\n return\n }\n snapshotInProgress = true\n const startedAt = Date.now()\n const filename = `kickjs-heap-${new Date().toISOString().replace(/[:.]/g, '-')}.heapsnapshot`\n const targetPath = join(tmpdir(), filename)\n\n let written: string\n try {\n // writeHeapSnapshot is synchronous — the event loop is\n // blocked for the duration. There's no async variant in\n // the v8 module today; if one ships, swap here.\n written = writeHeapSnapshot(targetPath)\n } catch (err) {\n snapshotInProgress = false\n log.error({ err }, 'heap snapshot capture failed')\n res\n .status(500)\n .json({ error: 'snapshot capture failed', message: (err as Error).message })\n return\n }\n\n let size = 0\n try {\n size = statSync(written).size\n } catch {\n /* size header is best-effort */\n }\n const elapsedMs = Date.now() - startedAt\n log.info(\n `Heap snapshot captured: ${written} (${(size / 1024 / 1024).toFixed(1)} MiB in ${elapsedMs}ms)`,\n )\n\n res.setHeader('Content-Type', 'application/json')\n res.setHeader('Content-Disposition', `attachment; filename=\"${filename}\"`)\n if (size > 0) res.setHeader('Content-Length', String(size))\n res.setHeader('X-Snapshot-Capture-Ms', String(elapsedMs))\n\n const cleanup = (): void => {\n unlink(written, (err) => {\n if (err) log.warn(`Failed to delete heap snapshot ${written}: ${err.message}`)\n snapshotInProgress = false\n })\n }\n const stream = createReadStream(written)\n stream.on('end', cleanup)\n stream.on('error', (err) => {\n log.error({ err }, 'heap snapshot stream failed')\n if (!res.headersSent) res.status(500).end()\n cleanup()\n })\n // Defensive: if the client disconnects mid-download, abort\n // the stream + run cleanup so the temp file doesn't linger.\n res.on('close', () => {\n stream.destroy()\n // If the stream already fired 'end', cleanup already ran\n // — the unlink is idempotent enough that running twice\n // just yields ENOENT which we ignore in cleanup.\n })\n stream.pipe(res)\n })\n\n // ── Force GC — Tier 3 monitoring (architecture.md §23) ──────\n // POST /_debug/memory/gc — calls `global.gc()` if Node was\n // started with --expose-gc, returning before/after heap size\n // so the panel can show how much was reclaimed. Useful for\n // confirming \"is this growth real or just delayed GC?\".\n //\n // Returns 412 Precondition Failed (with hint) when the flag\n // wasn't set, so the SPA can show \"Run with --expose-gc to\n // enable this button\" instead of a generic 5xx.\n router.post('/memory/gc', (_req: Request, res: Response) => {\n const gc = (globalThis as { gc?: () => void }).gc\n if (typeof gc !== 'function') {\n res.status(412).json({\n error: 'global.gc unavailable — start Node with --expose-gc to enable this endpoint',\n })\n return\n }\n const before = process.memoryUsage().heapUsed\n const startedAt = Date.now()\n try {\n gc()\n } catch (err) {\n res.status(500).json({\n error: 'forced GC failed',\n message: err instanceof Error ? err.message : String(err),\n })\n return\n }\n const after = process.memoryUsage().heapUsed\n const reclaimedBytes = Math.max(0, before - after)\n const elapsedMs = Date.now() - startedAt\n log.info(\n `Forced GC reclaimed ${(reclaimedBytes / 1024 / 1024).toFixed(2)} MiB in ${elapsedMs}ms`,\n )\n res.json({ before, after, reclaimedBytes, elapsedMs })\n })\n\n // ── Custom-tab discovery (architecture.md §23) ──────────────\n // Walks every plugin/adapter `devtoolsTabs?()` contribution\n // and serves the deduped + validated list. The SPA fetches\n // this once at boot to render dynamic tabs after the four\n // built-ins.\n router.get('/tabs', (_req: Request, res: Response) => {\n const kickApp = appRef?.__kickApp as TopologyApplicationLike | undefined\n if (!kickApp) {\n res.status(503).json({ error: 'tabs unavailable — application surface not exposed' })\n return\n }\n res.json(collectDevtoolsTabs(kickApp))\n })\n\n // ── Topology RPC (architecture.md §23) ──────────────────────\n // Aggregates plugins + adapters + contributors + DI tokens\n // into one snapshot; calls each primitive's introspect() in\n // parallel with a per-call timeout so a misbehaving adapter\n // can't block the endpoint. Errors are collected, not thrown.\n router.get('/topology', async (_req: Request, res: Response) => {\n if (!container) {\n res.status(503).json({ error: 'topology unavailable — container not bound yet' })\n return\n }\n const kickApp = appRef?.__kickApp as TopologyApplicationLike | undefined\n if (!kickApp) {\n res\n .status(503)\n .json({ error: 'topology unavailable — application surface not exposed' })\n return\n }\n try {\n const snapshot = await collectTopologySnapshot({ app: kickApp, container })\n res.json(snapshot)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n res.status(500).json({ error: 'topology collection failed', message })\n }\n })\n\n router.get('/ws', (_req: Request, res: Response) => {\n const wsAdapter = getPeerAdapters().find(\n (a) => a.name === 'WsAdapter' && typeof a.getStats === 'function',\n )\n if (!wsAdapter) {\n res.json({ enabled: false, message: 'WsAdapter not found' })\n return\n }\n res.json({ enabled: true, ...wsAdapter.getStats() })\n })\n\n router.get('/queues', async (_req: Request, res: Response) => {\n const queueAdapter = getPeerAdapters().find(\n (a) => a.name === 'QueueAdapter' && typeof a.getQueueNames === 'function',\n )\n if (!queueAdapter) {\n res.json({ enabled: false, message: 'QueueAdapter not found' })\n return\n }\n try {\n const names: string[] = queueAdapter.getQueueNames?.() ?? []\n const queues: any[] = []\n for (const name of names) {\n const stats = await queueAdapter.getQueueStats?.(name)\n queues.push({ name, ...stats })\n }\n res.json({ enabled: true, queues })\n } catch {\n res.json({ enabled: true, queues: [], error: 'Failed to fetch queue stats' })\n }\n })\n\n // ── Dependency graph ────────────────────────────────────────\n router.get('/graph', (_req: Request, res: Response) => {\n const registrations = container?.getRegistrations() ?? []\n const nodes = registrations\n .filter((r) => !r.token.startsWith('__hmr__'))\n .map((r) => ({\n id: r.token,\n kind: r.kind,\n scope: r.scope,\n resolveCount: r.resolveCount,\n }))\n const nodeIds = new Set(nodes.map((n) => n.id))\n const edges: Array<{ from: string; to: string }> = []\n for (const r of registrations) {\n if (r.token.startsWith('__hmr__')) continue\n for (const dep of r.dependencies) {\n if (nodeIds.has(dep)) {\n edges.push({ from: r.token, to: dep })\n }\n }\n }\n res.json({ nodes, edges })\n })\n\n // ── SSE stream for real-time updates ────────────────────────\n router.get('/stream', (req: Request, res: Response) => {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n })\n\n const sendMetrics = () => {\n const data = {\n type: 'metrics',\n requestCount: requestCount.value,\n errorCount: errorCount.value,\n clientErrorCount: clientErrorCount.value,\n errorRate: errorRate.value,\n uptimeSeconds: uptimeSeconds.value,\n }\n res.write(`data: ${JSON.stringify(data)}\\n\\n`)\n }\n sendMetrics()\n\n const unsubContainer = container?.onChange?.((changes) => {\n res.write(\n `data: ${JSON.stringify({ type: 'container', changes, timestamp: Date.now() })}\\n\\n`,\n )\n sendMetrics()\n })\n\n const stopRequestWatch = watch(requestCount, () => sendMetrics())\n const stopErrWatch = watch(errorCount, () => sendMetrics())\n\n const heartbeat = setInterval(() => {\n res.write(`: heartbeat\\n\\n`)\n }, 30000)\n\n req.on('close', () => {\n unsubContainer?.()\n stopRequestWatch()\n stopErrWatch()\n clearInterval(heartbeat)\n })\n })\n\n if (exposeConfig) {\n router.get('/config', (_req: Request, res: Response) => {\n const config: Record<string, string> = {}\n for (const [key, value] of Object.entries(process.env)) {\n if (value === undefined) continue\n const allowed = configPrefixes.some((prefix) => key.startsWith(prefix))\n config[key] = allowed ? value : '[REDACTED]'\n }\n res.json({ config })\n })\n }\n\n // Dashboard UI — Vue + Tailwind from public/devtools directory\n const publicDir = resolvePublicDir()\n if (publicDir) {\n router.use(serveStatic(publicDir))\n\n const indexHtml = readFileSync(join(publicDir, 'index.html'), 'utf-8')\n router.get('/', (_req: Request, res: Response) => {\n const html = indexHtml.replace('<body', `<body data-base=\"${basePath}\"`)\n res.type('html').send(html)\n })\n } else {\n router.get('/', (_req: Request, res: Response) => {\n res.type('html').send('<h1>DevTools: public directory not found</h1>')\n })\n }\n\n app.use(basePath, router)\n\n if (secret) {\n log.info(`DevTools mounted at ${basePath} [token: ${secret}]`)\n log.info(`Access: ${basePath}?token=${secret}`)\n } else {\n log.info(`DevTools mounted at ${basePath} [no guard]`)\n }\n },\n\n middleware(): AdapterMiddleware[] {\n if (!enabled) return []\n\n return [\n {\n handler: (req: Request, res: Response, next: NextFunction) => {\n const start = Date.now()\n requestCount.value++\n\n res.on('finish', () => {\n if (res.statusCode >= 500) errorCount.value++\n else if (res.statusCode >= 400) clientErrorCount.value++\n\n // Bucket unmatched paths (404s) under a single key. The\n // previous `?? req.path` fallback used the raw URL, which\n // grows the reactive map unboundedly under 404 probing —\n // each random path became its own entry, bloating\n // `/_debug/metrics` and leaking memory.\n const routeKey = req.route?.path\n ? `${req.method} ${req.route.path}`\n : `${req.method} <unmatched>`\n const elapsed = Date.now() - start\n\n if (!routeLatency[routeKey]) {\n routeLatency[routeKey] = {\n count: 0,\n totalMs: 0,\n minMs: Infinity,\n maxMs: 0,\n samples: [],\n }\n }\n const stats = routeLatency[routeKey]\n stats.count++\n stats.totalMs += elapsed\n stats.minMs = Math.min(stats.minMs, elapsed)\n stats.maxMs = Math.max(stats.maxMs, elapsed)\n stats.samples.push(elapsed)\n if (stats.samples.length > MAX_SAMPLES) stats.samples.shift()\n })\n\n next()\n },\n phase: 'beforeGlobal',\n },\n ]\n },\n\n onRouteMount(controllerClass, mountPath) {\n if (!enabled) return\n\n const collectedRoutes = getClassMeta<\n Array<{ method: string; path: string; handlerName: string }>\n >(METADATA.ROUTES, controllerClass, [])\n\n const classMiddleware = getClassMeta<any[]>(METADATA.CLASS_MIDDLEWARES, controllerClass, [])\n\n for (const route of collectedRoutes) {\n const methodMiddleware = getMethodMeta<any[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass.prototype,\n route.handlerName,\n [],\n )\n\n routes.push({\n method: route.method.toUpperCase(),\n path: `${mountPath}${route.path === '/' ? '' : route.path}`,\n controller: controllerClass.name,\n handler: route.handlerName,\n middleware: [\n ...classMiddleware.map((m: any) => m.name || 'anonymous'),\n ...methodMiddleware.map((m: any) => m.name || 'anonymous'),\n ],\n })\n }\n },\n\n afterStart({ server }) {\n if (!enabled) return\n // Wire the bus's WS upgrade to the framework's http.Server.\n // Path-based routing inside attachUpgrade means kickjs-ws or\n // any other adapter sharing the same listener stays\n // unaffected — only `${basePath}/_bus` is claimed.\n if (server) bus?.attachUpgrade(server)\n\n // Seed `/_debug/health.adapters` with every peer the framework\n // mounted alongside us. Before this, only `DevToolsAdapter`\n // appeared in the Overview > Health card because the dict was\n // only ever written in `beforeMount` (self) and `shutdown`\n // (self). Peers with `onHealthCheck` get their live status;\n // anything else is reported as `running` since reaching\n // `afterStart` means the framework already mounted them.\n for (const peer of getPeerAdapters()) {\n const name = peer?.name\n if (typeof name !== 'string' || name === 'DevToolsAdapter') continue\n adapterStatuses[name] = 'running'\n }\n\n log.info(\n `DevTools ready — ${routes.length} routes tracked, ` +\n `${container?.getRegistrations().length ?? 0} DI bindings, ` +\n `event bus on ${basePath}/_bus`,\n )\n },\n\n shutdown() {\n stopErrorWatch?.()\n runtimeSampler?.stop()\n memoryAnalyzer?.stop()\n bus?.close()\n adapterStatuses['DevToolsAdapter'] = 'stopped'\n },\n }\n },\n})\n"],"mappings":";;;;;;;;;;orBAkEA,eAAsB,wBACpB,KAC2B,CAC3B,GAAM,CAAE,IAAK,UAAW,oBAAsB,KAAkC,KAC1E,OAA0B,EAAE,CAE5B,QAAU,MAAM,QAAQ,IAC5B,IAAI,YAAY,CAAC,IAAK,GAAM,YAAY,EAAG,SAAU,oBAAqB,OAAO,CAAC,CACnF,CACK,SAAW,MAAM,QAAQ,IAC7B,IAAI,aAAa,CAAC,IAAK,GAAM,YAAY,EAAG,UAAW,oBAAqB,OAAO,CAAC,CACrF,CAED,MAAO,CACL,gBAAiB,iBACjB,UAAW,KAAK,KAAK,CACrB,QACA,SACA,aAAc,oBAAoB,IAAI,CACtC,SAAU,cAAc,UAAU,CAClC,OACD,CAQH,eAAe,YACb,UACA,KACA,UACA,OACgC,CAChC,IAAM,KAAO,UAAU,MAAQ,YACzB,KAA8B,CAClC,gBAAiB,iBACjB,KACA,KACD,CACD,GAAI,OAA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MAAM,CACtB,KAAK,OAAO,CACZ,gBAAgB,gBAAqB,WAExC,EAEJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forinda/kickjs-devtools",
3
- "version": "5.2.1",
3
+ "version": "5.2.3",
4
4
  "description": "Development introspection dashboard for KickJS — routes, DI container, metrics, health",
5
5
  "keywords": [
6
6
  "kickjs",
@@ -62,8 +62,8 @@
62
62
  },
63
63
  "dependencies": {
64
64
  "reflect-metadata": "^0.2.2",
65
- "ws": "^8.20.0",
66
- "@forinda/kickjs-devtools-kit": "5.3.0"
65
+ "ws": "^8.20.1",
66
+ "@forinda/kickjs-devtools-kit": "5.3.2"
67
67
  },
68
68
  "peerDependencies": {
69
69
  "express": "^5.1.0",
@@ -79,7 +79,7 @@
79
79
  "vite": "^8.0.9",
80
80
  "vite-plugin-solid": "^2.11.12",
81
81
  "vitest": "^4.1.5",
82
- "@forinda/kickjs": "5.3.0"
82
+ "@forinda/kickjs": "5.7.1"
83
83
  },
84
84
  "publishConfig": {
85
85
  "access": "public"