@brickkit/cli 0.9.1 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dashboard-dist/CollapsiblePanel-BX79_W-b.js +2 -0
- package/dashboard-dist/CompositeRoot-xzybXjnx.js +1 -0
- package/dashboard-dist/PopoverPopup-CvlmC7EL.js +1 -0
- package/dashboard-dist/{api-reference-r893F8zi.js → api-reference-BcAYVYwJ.js} +8 -8
- package/dashboard-dist/app.css +1 -1
- package/dashboard-dist/app.js +13 -13
- package/dashboard-dist/core-BGO9JZ1r.js +1 -0
- package/dashboard-dist/docs-DHikPD2v.js +4 -0
- package/dashboard-dist/kit.js +1 -0
- package/dashboard-dist/popover-DG498XHH.js +1 -0
- package/dashboard-dist/react-dom-client.js +3 -0
- package/dashboard-dist/react-dom.js +3 -0
- package/dashboard-dist/react-jsx-runtime.js +1 -1
- package/dashboard-dist/react.js +3 -3
- package/dashboard-dist/theme.css +123 -0
- package/dist/bin.d.ts.map +1 -1
- package/dist/bin.js +440 -44
- package/dist/bin.js.map +1 -1
- package/dist/client-contract-file2.js +1 -1
- package/dist/client-contract2.js +34 -8
- package/dist/client-contract2.js.map +1 -1
- package/dist/config.js +252 -0
- package/dist/config.js.map +1 -0
- package/dist/dashboard-extension.d.ts +27 -0
- package/dist/dashboard-extension.d.ts.map +1 -0
- package/dist/dashboard.d.ts +3127 -0
- package/dist/dev-telemetry-store.js +1407 -952
- package/dist/dev-telemetry-store.js.map +1 -1
- package/dist/dev-worker.js +2 -2
- package/dist/index.d.ts +95 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -4
- package/dist/lint/eslint.d.ts +2 -0
- package/dist/lint/eslint.js +1 -0
- package/dist/lint/oxlint.d.ts +19 -0
- package/dist/lint/oxlint.d.ts.map +1 -0
- package/dist/lint/oxlint.js +19 -0
- package/dist/lint/oxlint.js.map +1 -0
- package/dist/plugin.d.ts +76 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +66 -0
- package/dist/plugin.js.map +1 -0
- package/dist/presets.js +1070 -0
- package/dist/presets.js.map +1 -0
- package/dist/runner.js +112 -26
- package/dist/runner.js.map +1 -1
- package/dist/vite.d.ts +6 -3
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +9 -3
- package/dist/vite.js.map +1 -1
- package/dist/workflows2.js +1 -1
- package/inspector-dist/client/assets/app-CvoGgWcV.css +1 -0
- package/inspector-dist/client/assets/{manifest-4baa7c6f.js → manifest-139c9319.js} +1 -1
- package/inspector-dist/client/assets/root-BMHd_XHz.css +1 -0
- package/inspector-dist/server/assets/{app-C-ZVJtic.js → app-DUP5RybL.js} +11 -11
- package/inspector-dist/server/assets/{highlighted-body-B3W2YXNL-C8sq8F_D.js → highlighted-body-B3W2YXNL-D2g4hL2-.js} +1 -1
- package/inspector-dist/server/assets/{index-CYlmUaKx.js → index-D71yP6AL.js} +2 -2
- package/inspector-dist/server/assets/{index-CWJr34WJ.js → index-wGSWRns3.js} +1 -1
- package/inspector-dist/server/assets/{mermaid-3ZIDBTTL-Dv5rjfMN.js → mermaid-3ZIDBTTL-DsvuKoEV.js} +1 -1
- package/inspector-dist/server/assets/{token-DnLp3wBO.js → token-ClUZZwXl.js} +1 -1
- package/inspector-dist/server/assets/{token-util-Bpfp-B0w.js → token-util-DSxMZ6nI.js} +1 -1
- package/inspector-dist/server/assets/{wrapper-D5LIcZ_u.js → wrapper-B3vstpCO.js} +2 -2
- package/inspector-dist/server/assets/{zstd-browser-decoder-BM8GpVB8.js → zstd-browser-decoder-Dn82m2BU.js} +1 -1
- package/inspector-dist/server/index.js +1 -1
- package/package.json +30 -6
- package/dashboard-dist/CollapsiblePanel-a54TwMKb.js +0 -2
- package/dashboard-dist/PopoverPopup-BLzjTqsi.js +0 -1
- package/dashboard-dist/core-BWAwhSFf.js +0 -1
- package/dashboard-dist/docs-CkMy3Y5i.js +0 -4
- package/dashboard-dist/preload-helper-CjQDFR0M.js +0 -1
- package/dist/build.js +0 -88
- package/dist/build.js.map +0 -1
- package/inspector-dist/client/assets/app-CY7CQBRo.css +0 -1
- package/inspector-dist/client/assets/root-CfCr265_.css +0 -1
- /package/inspector-dist/client/assets/{root-Bmn5n3jF.js → root-cbi6iYwg.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev-telemetry-store.js","names":[],"sources":["../src/dev-inspector.ts","../src/dev-history-csv.ts","../src/dev-history.ts","../src/dev-dashboard-shell.ts","../src/dashboard-access.ts","../src/dev-dashboard.ts","../src/dev-docs.ts","../src/dev-telemetry-store.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { existsSync, statSync } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport type { BrickApp } from \"@brickkit/core\";\n\n/** Where the dashboard serves the inspector. */\nexport const INSPECTOR_PATH = \"/workflows\";\n/** The header that proves a request comes from the dashboard. */\nexport const INSPECTOR_TOKEN_HEADER = \"x-brick-inspector\";\n\nexport interface Inspector {\n readonly port: number;\n /** Every request must carry it in `INSPECTOR_TOKEN_HEADER`. */\n readonly token: string;\n stop(): void;\n}\n\n/** The built inspector, next to `src/` in the repo and next to `dist/` when published. */\nconst INSPECTOR_DIRECTORY = fileURLToPath(\n new URL(\"../inspector-dist/\", import.meta.url),\n);\n\n/** Whether a path is a regular file; any failure to find out (not a directory, name too long) says no. */\nfunction isFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * A file of the inspector's browser build. Its names carry a hash of their\n * content, so a browser may keep them for good. Anything else under `assets/`\n * is a plain 404: the page would answer with HTML. `undefined` for requests\n * outside `assets/`, which are the page's to answer.\n */\nfunction browserAsset(request: Request, client: string): Response | undefined {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return undefined;\n const { pathname } = new URL(request.url);\n if (!pathname.startsWith(`${INSPECTOR_PATH}/assets/`)) return undefined;\n const file = resolve(client, pathname.slice(INSPECTOR_PATH.length + 1));\n if (!file.startsWith(client + sep) || !isFile(file))\n return new Response(\"Not found\", { status: 404 });\n return new Response(Bun.file(file), {\n headers: { \"cache-control\": \"public, max-age=31536000, immutable\" },\n });\n}\n\n/**\n * Serve the Workflow inspector (the Workflow SDK's observability UI, built into\n * this package) for the app's world, on a loopback port of its own. The\n * dashboard proxies it at `/workflows`; it is the only caller that knows the\n * token. The UI can cancel runs and resume hooks, so nothing else may reach it,\n * and it exists only under `brick dev`.\n *\n * @param app - The loaded app, running in this process.\n * @param directory - The inspector's build; this package's own by default.\n * @returns The inspector, or `undefined` when the app runs no workflows.\n * @throws When the inspector's build is missing.\n */\nexport async function startInspector(\n app: BrickApp,\n directory = INSPECTOR_DIRECTORY,\n): Promise<Inspector | undefined> {\n const target = app.events?.workflows;\n if (!target) return undefined;\n const entry = join(directory, \"server\", \"index.js\");\n if (!existsSync(entry))\n throw new Error(\n \"The workflow inspector is not built. Build it with: bun run --filter @brickkit/cli build\",\n );\n const { createFetchHandler } = (await import(pathToFileURL(entry).href)) as {\n createFetchHandler(\n basename: string,\n host: { world: unknown },\n ): (request: Request) => Promise<Response>;\n };\n const page = createFetchHandler(INSPECTOR_PATH, { world: target.world });\n const client = join(directory, \"client\");\n const token = randomBytes(16).toString(\"hex\");\n const server = Bun.serve({\n hostname: \"127.0.0.1\",\n port: 0,\n // The UI streams a run's output and holds the connection open.\n idleTimeout: 0,\n fetch: (request) =>\n request.headers.get(INSPECTOR_TOKEN_HEADER) === token\n ? (browserAsset(request, client) ?? page(request))\n : new Response(\"Forbidden\", { status: 403 }),\n });\n return { port: server.port!, token, stop: () => void server.stop(true) };\n}\n","import type { HistoryTrace } from \"./dev-history\";\n\n// Kept apart from dev-history so the dashboard can export what it shows without\n// pulling in the database code.\n\nconst CSV_COLUMNS = [\n \"time\",\n \"method\",\n \"route\",\n \"path\",\n \"status\",\n \"outcome\",\n \"duration_ms\",\n \"service\",\n \"action\",\n \"message\",\n \"trace_id\",\n] as const;\n\nfunction csvCell(value: string | number | undefined): string {\n if (value === undefined) return \"\";\n const text = String(value);\n // Quote anything a spreadsheet could split on, and defuse formulas.\n const safe = /^[=+\\-@\\t\\r]/.test(text) ? `'${text}` : text;\n return /[\",\\n\\r]/.test(safe) ? `\"${safe.replace(/\"/g, '\"\"')}\"` : safe;\n}\n\n/** Requests as CSV with a header row, for the dashboard's export. */\nexport function tracesToCsv(traces: HistoryTrace[]): string {\n const lines = traces.map((trace) => {\n const failed = trace.status === \"error\" || (trace.httpStatus ?? 0) >= 500;\n const client = (trace.httpStatus ?? 0) >= 400;\n return [\n new Date(trace.startMs).toISOString(),\n trace.method,\n trace.route,\n trace.path,\n trace.httpStatus ?? trace.status,\n failed ? \"server\" : client ? \"client\" : \"ok\",\n trace.durationMs === undefined ? undefined : trace.durationMs.toFixed(3),\n trace.service,\n trace.action,\n trace.message,\n trace.traceId,\n ]\n .map(csvCell)\n .join(\",\");\n });\n return [CSV_COLUMNS.join(\",\"), ...lines].join(\"\\n\") + \"\\n\";\n}\n","import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { tracesToCsv } from \"./dev-history-csv\";\nimport type { SpanOutcome, TraceSummary } from \"./dev-telemetry-store\";\n\nexport { tracesToCsv };\n\nexport const DEFAULT_HISTORY_DAYS = 90;\n\nconst DAY_MS = 86_400_000;\nconst MAX_TRACES = 100_000;\nconst FLUSH_MS = 250;\nconst PRUNE_MS = 30 * 60_000;\nconst VOLUME_BUCKETS = 48;\nconst DEFAULT_LIMIT = 100;\nconst MAX_LIMIT = 500;\nconst MAX_FACET_VALUES = 30;\nconst MAX_EXPORT_ROWS = 100_000;\n\n/** A finished request without its spans; fetch the full trace by id. */\nexport interface HistoryTrace {\n traceId: string;\n name: string;\n /** \"GET /api/page/:id\" when the method and route are known, else the span name. */\n endpoint: string;\n method?: string;\n route?: string;\n path?: string;\n httpStatus?: number;\n generation: number;\n startMs: number;\n endMs?: number;\n durationMs?: number;\n status: SpanOutcome;\n truncated: boolean;\n /** The service and action that handled the request, when it ran one. */\n service?: string;\n action?: string;\n /** Why it failed, when it did. */\n message?: string;\n}\n\n/** How a request ended: a 5xx or crash, a 4xx, or neither. */\nexport type Outcome = \"ok\" | \"client\" | \"server\";\nconst OUTCOMES = new Set<string>([\"ok\", \"client\", \"server\"]);\n\n/** A filter groups values with OR; separate filters combine with AND. */\nexport interface HistoryQuery {\n from: number;\n to: number;\n endpoints?: string[];\n methods?: string[];\n services?: string[];\n outcomes?: Outcome[];\n /** Only requests at least this slow. */\n minMs?: number;\n /** Matches the endpoint or the request path. */\n query?: string;\n sort?: \"recent\" | \"slowest\";\n limit?: number;\n offset?: number;\n}\n\nexport interface VolumeBucket {\n start: number;\n ok: number;\n client: number;\n server: number;\n}\n\n/** The numbers behind the cards at the top of the log, for what matches. */\nexport interface HistorySummary {\n total: number;\n clientErrors: number;\n serverErrors: number;\n medianMs: number;\n p95Ms: number;\n}\n\nexport interface FacetValue {\n value: string;\n count: number;\n}\n\n/** What is in the range, counted for each filter as if it were not applied. */\nexport interface HistoryFacets {\n outcome: FacetValue[];\n method: FacetValue[];\n service: FacetValue[];\n endpoint: FacetValue[];\n}\n\nexport interface HistoryInfo {\n days: number;\n count: number;\n oldestMs?: number;\n}\n\ninterface Statement {\n run(...params: unknown[]): unknown;\n all(...params: unknown[]): Record<string, unknown>[];\n get(...params: unknown[]): Record<string, unknown> | undefined;\n}\n\ninterface Database {\n exec(sql: string): void;\n prepare(sql: string): Statement;\n close(): void;\n}\n\n/**\n * SQLite from whichever runtime is running: `bun:sqlite` under Bun, and\n * `node:sqlite` under Node, which is what runs Vite's dev server. Both are\n * imported by a variable name so bundlers leave them alone.\n */\nasync function openDatabase(file: string): Promise<Database> {\n if (typeof Bun !== \"undefined\") {\n const specifier = \"bun:sqlite\";\n const { Database } = (await import(specifier)) as {\n Database: new (file: string, options: { create: boolean }) => Database;\n };\n return new Database(file, { create: true });\n }\n const specifier = \"node:sqlite\";\n // Node prints an experimental-feature warning when this module loads. It is\n // stable enough for a local log, and the warning would only confuse.\n const emit = process.emitWarning;\n process.emitWarning = ((warning: unknown, ...rest: unknown[]) => {\n if (typeof warning === \"string\" && warning.includes(\"SQLite\")) return;\n return (emit as (...args: unknown[]) => void).call(\n process,\n warning,\n ...rest,\n );\n }) as typeof process.emitWarning;\n try {\n const { DatabaseSync } = (await import(specifier)) as {\n DatabaseSync: new (file: string) => Database;\n };\n return new DatabaseSync(file);\n } finally {\n process.emitWarning = emit;\n }\n}\n\nexport interface OpenHistoryOptions {\n /** The project folder; the database lives in `.brick/` inside it. */\n directory: string;\n /** How long to keep requests. Zero or less turns history off. */\n days: number;\n warn?: (message: string) => void;\n}\n\n/**\n * Open the request history, or return undefined when it is turned off or this\n * runtime has no SQLite. Never throws: the dashboard works without history.\n */\nexport async function openHistory(\n options: OpenHistoryOptions,\n): Promise<DevHistory | undefined> {\n if (!(options.days > 0)) return undefined;\n try {\n const folder = join(options.directory, \".brick\");\n mkdirSync(folder, { recursive: true });\n // Requests can hold SQL text and error details, so never let them be\n // committed by accident.\n const ignore = join(folder, \".gitignore\");\n if (!existsSync(ignore)) writeFileSync(ignore, \"*\\n\");\n const database = await openDatabase(join(folder, \"telemetry.sqlite\"));\n return new DevHistory(database, options.days);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n options.warn?.(\n `[Brick-TS] Request history is unavailable (${reason}). It needs Bun, or Node 22.5 or later. Continuing without it.`,\n );\n return undefined;\n }\n}\n\nconst text = (value: unknown): string | undefined =>\n value === null || value === undefined ? undefined : String(value);\nconst number = (value: unknown): number | undefined =>\n value === null || value === undefined ? undefined : Number(value);\n\nfunction percentile(sorted: number[], fraction: number): number {\n if (sorted.length === 0) return 0;\n const position = (sorted.length - 1) * fraction;\n const lower = Math.floor(position);\n const upper = Math.ceil(position);\n return sorted[lower] + (sorted[upper] - sorted[lower]) * (position - lower);\n}\n\nconst OUTCOME_SQL: Record<Outcome, string> = {\n server: \"(status = 'error' OR http_status >= 500)\",\n client: \"(status != 'error' AND http_status >= 400 AND http_status < 500)\",\n ok: \"(status != 'error' AND (http_status IS NULL OR http_status < 400))\",\n};\n\n/** The outcome of each row, for counting; agrees with OUTCOME_SQL. */\nconst OUTCOME_CASE = `CASE\n WHEN status = 'error' OR http_status >= 500 THEN 'server'\n WHEN http_status >= 400 AND http_status < 500 THEN 'client'\n ELSE 'ok' END`;\n\ntype Facet = \"outcome\" | \"method\" | \"service\" | \"endpoint\";\n\nconst FACET_COLUMNS: Record<Facet, string> = {\n outcome: OUTCOME_CASE,\n method: \"method\",\n service: \"service\",\n endpoint: \"endpoint\",\n};\n\n/** The WHERE clause for a query, leaving out one filter when counting its facet. */\nfunction filterSql(\n query: HistoryQuery,\n skip?: Facet,\n): { sql: string; params: unknown[] } {\n const clauses = [\"start_ms >= ?\", \"start_ms <= ?\"];\n const params: unknown[] = [query.from, query.to];\n const anyOf = (column: string, values: string[] | undefined) => {\n if (!values || values.length === 0) return;\n clauses.push(`${column} IN (${values.map(() => \"?\").join(\", \")})`);\n params.push(...values);\n };\n if (skip !== \"endpoint\") anyOf(\"endpoint\", query.endpoints);\n if (skip !== \"method\") anyOf(\"method\", query.methods);\n if (skip !== \"service\") anyOf(\"service\", query.services);\n if (skip !== \"outcome\" && query.outcomes && query.outcomes.length > 0) {\n clauses.push(\n `(${query.outcomes.map((outcome) => OUTCOME_SQL[outcome]).join(\" OR \")})`,\n );\n }\n if (query.minMs !== undefined && query.minMs > 0) {\n clauses.push(\"duration_ms >= ?\");\n params.push(query.minMs);\n }\n const needle = query.query?.trim();\n if (needle) {\n const pattern = `%${needle.replace(/[\\\\%_]/g, \"\\\\$&\")}%`;\n clauses.push(\n \"(endpoint LIKE ? ESCAPE '\\\\' OR path LIKE ? ESCAPE '\\\\' OR name LIKE ? ESCAPE '\\\\' OR action LIKE ? ESCAPE '\\\\' OR message LIKE ? ESCAPE '\\\\')\",\n );\n params.push(pattern, pattern, pattern, pattern, pattern);\n }\n return { sql: clauses.join(\" AND \"), params };\n}\n\nconst LIST_COLUMNS = `trace_id, name, endpoint, method, route, path, http_status, generation,\n start_ms, end_ms, duration_ms, status, truncated, service, action, message`;\n\nfunction toHistoryTrace(row: Record<string, unknown>): HistoryTrace {\n return {\n traceId: String(row.trace_id),\n name: String(row.name),\n endpoint: String(row.endpoint),\n method: text(row.method),\n route: text(row.route),\n path: text(row.path),\n httpStatus: number(row.http_status),\n generation: Number(row.generation),\n startMs: Number(row.start_ms),\n endMs: number(row.end_ms),\n durationMs: number(row.duration_ms),\n status: String(row.status) as SpanOutcome,\n truncated: Number(row.truncated) === 1,\n service: text(row.service),\n action: text(row.action),\n message: text(row.message),\n };\n}\n\n/**\n * Requests kept on disk between runs, for looking back over weeks\n * instead of the last few minutes. Writes are batched; reads see them.\n */\nexport class DevHistory {\n readonly days: number;\n readonly #database: Database;\n readonly #pendingTraces = new Map<string, TraceSummary>();\n #flushTimer: ReturnType<typeof setTimeout> | undefined;\n readonly #pruneTimer: ReturnType<typeof setInterval>;\n #closed = false;\n\n constructor(database: Database, days: number) {\n this.#database = database;\n this.days = days;\n database.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n PRAGMA busy_timeout = 2000;\n CREATE TABLE IF NOT EXISTS traces (\n trace_id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n endpoint TEXT NOT NULL,\n method TEXT,\n route TEXT,\n path TEXT,\n http_status INTEGER,\n generation INTEGER NOT NULL,\n start_ms INTEGER NOT NULL,\n end_ms INTEGER,\n duration_ms REAL,\n status TEXT NOT NULL,\n truncated INTEGER NOT NULL,\n spans TEXT NOT NULL,\n service TEXT,\n action TEXT,\n message TEXT\n );\n CREATE INDEX IF NOT EXISTS traces_start ON traces (start_ms);\n CREATE INDEX IF NOT EXISTS traces_endpoint ON traces (endpoint, start_ms);\n -- Earlier versions kept failures here; nothing reads them now.\n DROP TABLE IF EXISTS failures;\n `);\n this.#addMissingColumns();\n this.prune();\n this.#pruneTimer = setInterval(() => this.prune(), PRUNE_MS);\n this.#pruneTimer.unref?.();\n }\n\n /** A folder from an earlier version has the table without the newer columns. */\n #addMissingColumns(): void {\n const present = new Set(\n this.#database\n .prepare(\"PRAGMA table_info(traces)\")\n .all()\n .map((column) => String(column.name)),\n );\n for (const column of [\"service\", \"action\", \"message\"]) {\n if (!present.has(column)) {\n this.#database.exec(`ALTER TABLE traces ADD COLUMN ${column} TEXT`);\n }\n }\n }\n\n /** Queue a finished request. A later save of the same request replaces it. */\n saveTrace(trace: TraceSummary): void {\n if (this.#closed) return;\n this.#pendingTraces.set(trace.traceId, trace);\n this.#scheduleFlush();\n }\n\n #scheduleFlush(): void {\n if (this.#flushTimer) return;\n this.#flushTimer = setTimeout(() => this.flush(), FLUSH_MS);\n this.#flushTimer.unref?.();\n }\n\n /** Write queued requests now. */\n flush(): void {\n if (this.#flushTimer) {\n clearTimeout(this.#flushTimer);\n this.#flushTimer = undefined;\n }\n if (this.#closed || this.#pendingTraces.size === 0) return;\n const traces = [...this.#pendingTraces.values()];\n this.#pendingTraces.clear();\n try {\n this.#database.exec(\"BEGIN\");\n const saveTrace = this.#database.prepare(\n `INSERT OR REPLACE INTO traces (trace_id, name, endpoint, method, route, path,\n http_status, generation, start_ms, end_ms, duration_ms, status, truncated, spans,\n service, action, message)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n );\n for (const trace of traces) {\n saveTrace.run(\n trace.traceId,\n trace.name,\n trace.method && trace.route\n ? `${trace.method} ${trace.route}`\n : trace.name,\n trace.method ?? null,\n trace.route ?? null,\n trace.path ?? null,\n trace.httpStatus ?? null,\n trace.generation,\n trace.startMs,\n trace.endMs ?? null,\n trace.durationMs ?? null,\n trace.status,\n trace.truncated ? 1 : 0,\n JSON.stringify(trace.spans),\n trace.service ?? null,\n trace.action ?? null,\n trace.message ?? null,\n );\n }\n this.#database.exec(\"COMMIT\");\n } catch {\n // A failed write loses a batch of history; it must not break the app.\n try {\n this.#database.exec(\"ROLLBACK\");\n } catch {\n // Nothing was open.\n }\n }\n }\n\n /** Drop what is past retention, then the oldest beyond the size cap. */\n prune(now = Date.now()): void {\n if (this.#closed) return;\n try {\n const cutoff = now - this.days * DAY_MS;\n this.#database\n .prepare(\"DELETE FROM traces WHERE start_ms < ?\")\n .run(cutoff);\n const count = Number(\n this.#database.prepare(\"SELECT COUNT(*) AS n FROM traces\").get()?.n ??\n 0,\n );\n if (count > MAX_TRACES) {\n this.#database\n .prepare(\n \"DELETE FROM traces WHERE trace_id IN (SELECT trace_id FROM traces ORDER BY start_ms ASC LIMIT ?)\",\n )\n .run(count - MAX_TRACES);\n }\n } catch {\n // Pruning is housekeeping; try again next time.\n }\n }\n\n info(): HistoryInfo {\n this.flush();\n const row = this.#database\n .prepare(\"SELECT COUNT(*) AS n, MIN(start_ms) AS oldest FROM traces\")\n .get();\n return {\n days: this.days,\n count: Number(row?.n ?? 0),\n oldestMs: number(row?.oldest),\n };\n }\n\n /** Matching requests, without spans, and how many match in total. */\n traces(query: HistoryQuery): { total: number; traces: HistoryTrace[] } {\n this.flush();\n const { sql, params } = filterSql(query);\n const total = Number(\n this.#database\n .prepare(`SELECT COUNT(*) AS n FROM traces WHERE ${sql}`)\n .get(...params)?.n ?? 0,\n );\n const limit = Math.min(\n Math.max(query.limit ?? DEFAULT_LIMIT, 1),\n MAX_LIMIT,\n );\n const offset = Math.max(query.offset ?? 0, 0);\n const order =\n query.sort === \"slowest\"\n ? \"duration_ms DESC, start_ms DESC\"\n : \"start_ms DESC\";\n const rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${order} LIMIT ? OFFSET ?`,\n )\n .all(...params, limit, offset);\n return { total, traces: rows.map(toHistoryTrace) };\n }\n\n /** Counts for each filter over the range, ignoring that filter's own choice. */\n facets(query: HistoryQuery): HistoryFacets {\n this.flush();\n const count = (facet: Facet): FacetValue[] => {\n const { sql, params } = filterSql(query, facet);\n const column = FACET_COLUMNS[facet];\n return this.#database\n .prepare(\n `SELECT ${column} AS value, COUNT(*) AS n FROM traces\n WHERE ${sql} AND ${column} IS NOT NULL\n GROUP BY value ORDER BY n DESC, value ASC LIMIT ?`,\n )\n .all(...params, MAX_FACET_VALUES)\n .map((row) => ({ value: String(row.value), count: Number(row.n) }));\n };\n return {\n outcome: count(\"outcome\"),\n method: count(\"method\"),\n service: count(\"service\"),\n endpoint: count(\"endpoint\"),\n };\n }\n\n /** Matching requests per time bucket across the range, by outcome. */\n volume(query: HistoryQuery, buckets = VOLUME_BUCKETS): VolumeBucket[] {\n this.flush();\n const { sql, params } = filterSql(query);\n const bucketMs = Math.max(Math.ceil((query.to - query.from) / buckets), 1);\n const result: VolumeBucket[] = Array.from(\n { length: buckets },\n (_, index) => ({\n start: query.from + index * bucketMs,\n ok: 0,\n client: 0,\n server: 0,\n }),\n );\n const rows = this.#database\n .prepare(\n `SELECT CAST((start_ms - ?) / ? AS INTEGER) AS bucket, ${OUTCOME_CASE} AS outcome,\n COUNT(*) AS n\n FROM traces WHERE ${sql} GROUP BY bucket, outcome`,\n )\n .all(query.from, bucketMs, ...params);\n for (const row of rows) {\n const bucket =\n result[Math.min(Math.max(Number(row.bucket), 0), buckets - 1)];\n const outcome = String(row.outcome) as Outcome;\n if (bucket) bucket[outcome] += Number(row.n);\n }\n return result;\n }\n\n /** Every matching request, newest first, as CSV for a spreadsheet. */\n exportCsv(query: HistoryQuery): string {\n this.flush();\n const { sql, params } = filterSql(query);\n const order =\n query.sort === \"slowest\"\n ? \"duration_ms DESC, start_ms DESC\"\n : \"start_ms DESC\";\n const rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${order} LIMIT ?`,\n )\n .all(...params, MAX_EXPORT_ROWS);\n return tracesToCsv(rows.map(toHistoryTrace));\n }\n\n /** One request with all its spans. */\n trace(traceId: string): TraceSummary | undefined {\n this.flush();\n const row = this.#database\n .prepare(`SELECT ${LIST_COLUMNS}, spans FROM traces WHERE trace_id = ?`)\n .get(traceId);\n if (!row) return undefined;\n const { endpoint: _endpoint, ...trace } = toHistoryTrace(row);\n return { ...trace, spans: JSON.parse(String(row.spans)) };\n }\n\n /** How many requests match, how many failed, and how long they took. */\n summary(query: HistoryQuery): HistorySummary {\n this.flush();\n const { sql, params } = filterSql(query);\n let total = 0;\n let clientErrors = 0;\n let serverErrors = 0;\n const counts = this.#database\n .prepare(\n `SELECT ${OUTCOME_CASE} AS outcome, COUNT(*) AS n\n FROM traces WHERE ${sql} GROUP BY outcome`,\n )\n .all(...params);\n for (const row of counts) {\n const n = Number(row.n);\n total += n;\n if (row.outcome === \"client\") clientErrors = n;\n if (row.outcome === \"server\") serverErrors = n;\n }\n const durations = this.#database\n .prepare(\n `SELECT duration_ms FROM traces\n WHERE ${sql} AND duration_ms IS NOT NULL ORDER BY duration_ms`,\n )\n .all(...params)\n .map((row) => Number(row.duration_ms));\n return {\n total,\n clientErrors,\n serverErrors,\n medianMs: percentile(durations, 0.5),\n p95Ms: percentile(durations, 0.95),\n };\n }\n\n /** Write what is queued and release the database. */\n close(): void {\n if (this.#closed) return;\n this.flush();\n this.#closed = true;\n clearInterval(this.#pruneTimer);\n try {\n this.#database.close();\n } catch {\n // Already closed.\n }\n }\n}\n\n/** Query-string values the dashboard sends, parsed defensively. */\nexport function parseHistoryQuery(\n params: URLSearchParams,\n now = Date.now(),\n): HistoryQuery {\n const integer = (name: string): number | undefined => {\n const raw = params.get(name);\n if (raw === null || raw.trim() === \"\") return undefined;\n const value = Number(raw);\n return Number.isFinite(value) ? value : undefined;\n };\n const all = (name: string): string[] | undefined => {\n const values = params.getAll(name).filter((value) => value !== \"\");\n return values.length > 0 ? values : undefined;\n };\n const to = integer(\"to\") ?? now;\n return {\n to,\n from: integer(\"from\") ?? to - 7 * DAY_MS,\n endpoints: all(\"endpoint\"),\n methods: all(\"method\"),\n services: all(\"service\"),\n outcomes: all(\"outcome\")?.filter((value): value is Outcome =>\n OUTCOMES.has(value),\n ),\n minMs: integer(\"minMs\"),\n query: params.get(\"q\") || undefined,\n sort: params.get(\"sort\") === \"slowest\" ? \"slowest\" : \"recent\",\n limit: integer(\"limit\"),\n offset: integer(\"offset\"),\n };\n}\n","/**\n * The page the dashboard serves at `/`. The React app and its styles load from\n * `/assets/`; the inline script applies the saved theme before first paint. The\n * import map lets the project's own docs components, bundled apart from the\n * dashboard, share its copy of React.\n */\nexport const DEV_DASHBOARD_SHELL = `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Brick dev</title>\n<link rel=\"icon\" href=\"data:,\">\n<script>\n(function () {\n try {\n var theme = localStorage.getItem(\"brick-dashboard-theme\");\n var dark = theme === \"dark\" || (theme !== \"light\" && window.matchMedia(\"(prefers-color-scheme: dark)\").matches);\n if (dark) document.documentElement.classList.add(\"dark\");\n } catch (error) {}\n})();\n</script>\n<link rel=\"stylesheet\" href=\"/assets/app.css\">\n<script type=\"importmap\">\n{\"imports\":{\"react\":\"/assets/react.js\",\"react/jsx-runtime\":\"/assets/react-jsx-runtime.js\",\"react/jsx-dev-runtime\":\"/assets/react-jsx-runtime.js\"}}\n</script>\n</head>\n<body>\n<div id=\"root\"></div>\n<script type=\"module\" src=\"/assets/app.js\"></script>\n</body>\n</html>\n`;\n","import { createHash, timingSafeEqual } from \"node:crypto\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { DashboardAuth } from \"@brickkit/core\";\n\n/** What to do with a request: let it through, or answer it with this. */\nexport type Access =\n | { allowed: true }\n | {\n allowed: false;\n status: number;\n headers: Record<string, string | string[]>;\n body: string | Uint8Array;\n };\n\n/** How long the app's `authorize` may take before the request is refused. */\nexport const AUTHORIZE_TIMEOUT_MS = 5000;\n\n/** Whether `host` can only be reached from the machine it runs on. */\nexport function isLoopbackHost(host: string): boolean {\n const name = host.toLowerCase();\n return (\n name === \"localhost\" ||\n name === \"::1\" ||\n name === \"[::1]\" ||\n /^127(\\.\\d{1,3}){3}$/.test(name)\n );\n}\n\nconst NOT_COPIED = new Set([\n \"set-cookie\",\n \"content-length\",\n \"content-encoding\",\n \"transfer-encoding\",\n \"connection\",\n \"keep-alive\",\n]);\n\nconst digest = (value: string) => createHash(\"sha256\").update(value).digest();\n\n/** Whether `candidate` is one of `tokens`, in the same time whichever it is. */\nfunction isToken(candidate: string | undefined, tokens: readonly string[]) {\n if (candidate === undefined) return false;\n const given = digest(candidate);\n let match = false;\n // Every token is compared, so the time does not say which one was close.\n for (const token of tokens)\n if (timingSafeEqual(given, digest(token))) match = true;\n return match;\n}\n\n/** The secret in an `Authorization` header: a Bearer token, or a Basic password. */\nfunction credential(request: IncomingMessage): string | undefined {\n const header = request.headers.authorization;\n if (!header) return undefined;\n const space = header.indexOf(\" \");\n if (space < 0) return undefined;\n const scheme = header.slice(0, space).toLowerCase();\n const value = header.slice(space + 1).trim();\n if (scheme === \"bearer\") return value;\n if (scheme === \"basic\") {\n const decoded = Buffer.from(value, \"base64\").toString(\"utf8\");\n const colon = decoded.indexOf(\":\");\n return colon < 0 ? undefined : decoded.slice(colon + 1);\n }\n return undefined;\n}\n\n/** The request as the app's `authorize` sees it: standard, with no body. */\nfunction webRequest(request: IncomingMessage): Request {\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (value === undefined) continue;\n try {\n headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n } catch {\n // A header the platform will not take cannot matter to a check.\n }\n }\n const forwarded = request.headers[\"x-forwarded-proto\"];\n const protocol =\n (Array.isArray(forwarded) ? forwarded[0] : forwarded)\n ?.split(\",\")[0]\n ?.trim() === \"https\"\n ? \"https\"\n : \"http\";\n const host = request.headers.host ?? \"localhost\";\n let url: string;\n try {\n url = new URL(request.url ?? \"/\", `${protocol}://${host}`).href;\n } catch {\n url = `${protocol}://localhost${request.url ?? \"/\"}`;\n }\n return new Request(url, { method: request.method ?? \"GET\", headers });\n}\n\nconst refusal = (\n status: number,\n body: string,\n headers: Record<string, string> = {},\n): Access => ({\n allowed: false,\n status,\n body,\n headers: { \"content-type\": \"text/plain; charset=utf-8\", ...headers },\n});\n\n/**\n * The check for the dashboard's requests. A request passes with a valid token,\n * or when the app's `authorize` returns `true`. Anything else is answered:\n * what `authorize` returned if it returned a `Response`, else 401 (with a\n * browser sign-in prompt when tokens are in use), and 503 when `authorize`\n * threw or ran out of time, since a check that cannot answer must not let\n * anyone in.\n */\nexport function createAccess(\n auth: DashboardAuth,\n onError: (error: unknown) => void = () => {},\n timeoutMs = AUTHORIZE_TIMEOUT_MS,\n): (request: IncomingMessage) => Promise<Access> {\n const tokens =\n auth.token === undefined\n ? []\n : typeof auth.token === \"string\"\n ? [auth.token]\n : [...auth.token];\n const prompt: Record<string, string> =\n tokens.length > 0\n ? { \"www-authenticate\": 'Basic realm=\"Brick dashboard\", charset=\"UTF-8\"' }\n : {};\n return async (request) => {\n if (tokens.length > 0 && isToken(credential(request), tokens))\n return { allowed: true };\n if (!auth.authorize) return refusal(401, \"Unauthorized\", prompt);\n\n let decision: boolean | Response;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n decision = await Promise.race([\n Promise.resolve(auth.authorize(webRequest(request))),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(\"dashboard authorize timed out\")),\n timeoutMs,\n );\n }),\n ]);\n } catch (error) {\n onError(error);\n return refusal(503, \"Sign-in is unavailable.\");\n } finally {\n clearTimeout(timer);\n }\n if (decision === true) return { allowed: true };\n if (decision instanceof Response) {\n const headers: Record<string, string | string[]> = {};\n decision.headers.forEach((value, name) => {\n // The body is sent as bytes with its own length; these describe the\n // connection or an encoding already undone.\n if (!NOT_COPIED.has(name)) headers[name] = value;\n });\n const cookies = decision.headers.getSetCookie();\n if (cookies.length > 0) headers[\"set-cookie\"] = cookies;\n return {\n allowed: false,\n status: decision.status,\n headers,\n body: new Uint8Array(await decision.arrayBuffer()),\n };\n }\n return refusal(401, \"Unauthorized\", prompt);\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport {\n createServer,\n type IncomingMessage,\n type ServerResponse,\n} from \"node:http\";\nimport { extname, join } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport type { DevDocs } from \"./dev-docs\";\nimport { INSPECTOR_PATH, INSPECTOR_TOKEN_HEADER } from \"./dev-inspector\";\nimport { parseHistoryQuery, type DevHistory } from \"./dev-history\";\nimport type { TelemetryRecord } from \"./dev-telemetry\";\nimport type {\n DevTelemetryEvent,\n DevTelemetryStore,\n} from \"./dev-telemetry-store\";\nimport { DEV_DASHBOARD_SHELL } from \"./dev-dashboard-shell\";\nimport type { DashboardAuth } from \"@brickkit/core\";\nimport { createAccess, isLoopbackHost } from \"./dashboard-access\";\n\nexport const DEFAULT_DASHBOARD_PORT = 9400;\nconst KEEPALIVE_MS = 15_000;\nconst MAX_INGEST_BYTES = 5 * 1024 * 1024;\nconst MAX_PROXY_BYTES = 10 * 1024 * 1024;\n// Request headers that describe one hop or the dashboard's own page, and\n// response headers that fetch has already applied or that mean nothing here.\nconst NOT_FORWARDED = new Set([\n \"host\",\n \"connection\",\n \"keep-alive\",\n \"proxy-connection\",\n \"transfer-encoding\",\n \"te\",\n \"trailer\",\n \"upgrade\",\n \"content-length\",\n \"accept-encoding\",\n \"origin\",\n \"referer\",\n \"cookie\",\n]);\nconst NOT_RETURNED = new Set([\n \"connection\",\n \"keep-alive\",\n \"transfer-encoding\",\n \"content-length\",\n \"content-encoding\",\n \"set-cookie\",\n]);\n\n/**\n * What a production dashboard may show: the shell and its assets, the live\n * state and its event stream, and stored history. Nothing that changes the app\n * or reaches into it (restart, the API proxy, ingest) and nothing from the\n * project's source (documentation, OpenAPI documents).\n */\nconst isMonitoringRoute = (method: string | undefined, pathname: string) =>\n method === \"GET\" &&\n (pathname === \"/\" ||\n pathname.startsWith(\"/assets/\") ||\n pathname === \"/api/state\" ||\n pathname === \"/api/events\" ||\n pathname.startsWith(\"/api/history\"));\n\nconst PRODUCTION_HEADERS = {\n \"x-content-type-options\": \"nosniff\",\n \"x-frame-options\": \"DENY\",\n \"referrer-policy\": \"no-referrer\",\n \"cross-origin-opener-policy\": \"same-origin\",\n \"cross-origin-resource-policy\": \"same-origin\",\n // Requests and logs are private: nothing caches them on the way.\n \"cache-control\": \"no-store\",\n \"content-security-policy\":\n \"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'\",\n};\n\n/** How long `/_health` waits for the app before calling it down. */\nconst PROBE_TIMEOUT_MS = 3000;\n\nexport interface DevDashboardOptions {\n port: number;\n /**\n * The address to listen on; loopback by default. Any other address needs\n * `auth`, and the server refuses to start without it.\n */\n host?: string;\n /**\n * `\"production\"` is the read-only monitoring dashboard of `brick start`: it\n * serves only what `isMonitoringRoute` lists, with security headers, and\n * tells its page to hide the tabs that need a developer's machine.\n */\n mode?: \"dev\" | \"production\";\n /** Who may use the dashboard, checked before anything but `/_health`. */\n auth?: DashboardAuth;\n /** Whether the app answers; `/_health` reports it, for uptime monitors. */\n probe?: () => Promise<boolean>;\n store: DevTelemetryStore;\n /** Requests kept on disk; omit to serve live data only. The page hides its History view. */\n history?: DevHistory;\n /** The app's developer documentation, when it has any, as of this request. */\n docs?: () => DevDocs | undefined;\n /** Omit when the host cannot restart the application; the page hides its button. */\n restart?: () => void;\n}\n\nexport interface DevDashboard {\n readonly port: number;\n stop(): void;\n}\n\n/**\n * Serve the dashboard, on loopback unless told otherwise. On loopback requests\n * must name a local host (blocks DNS rebinding), and restart requires a header\n * that cross-origin pages cannot send without a preflight. Elsewhere `auth` is\n * required and decides who gets in. Uses node:http, so it runs under Bun and\n * under Node (Vite's dev server runs under Node).\n */\nexport function startDevDashboard(\n options: DevDashboardOptions,\n): Promise<DevDashboard> {\n const host = options.host ?? \"127.0.0.1\";\n const loopback = isLoopbackHost(host);\n const production = options.mode === \"production\";\n if (!loopback && !options.auth) {\n return Promise.reject(\n new Error(\n `Brick: the dashboard would listen on ${host}, where others can reach it, so it needs access control. Set dashboard.auth with a token or an authorize function.`,\n ),\n );\n }\n const access = options.auth\n ? createAccess(options.auth, (error) =>\n console.error(\"[Brick-TS] The dashboard sign-in check failed:\", error),\n )\n : undefined;\n let allowedHosts = new Set<string>();\n const server = createServer((request, response) => {\n respond(request, response).catch((error: unknown) => {\n console.error(\"[Brick-TS] The dashboard failed to answer:\", error);\n if (response.headersSent) response.end();\n else send(response, 500, \"Server error\");\n });\n });\n\n async function respond(\n request: IncomingMessage,\n response: ServerResponse,\n ): Promise<void> {\n if (production)\n for (const [name, value] of Object.entries(PRODUCTION_HEADERS))\n response.setHeader(name, value);\n if (loopback && !allowedHosts.has(request.headers.host ?? \"\")) {\n send(response, 403, \"Forbidden\");\n return;\n }\n const url = new URL(request.url ?? \"/\", \"http://127.0.0.1\");\n const { pathname } = url;\n // The one route open to everyone: uptime monitors cannot sign in.\n if (\n pathname === \"/_health\" &&\n (request.method === \"GET\" || request.method === \"HEAD\")\n ) {\n await health(response);\n return;\n }\n if (access) {\n const decision = await access(request);\n if (!decision.allowed) {\n send(response, decision.status, decision.body, decision.headers);\n return;\n }\n }\n if (production && !isMonitoringRoute(request.method, pathname)) {\n send(response, 404, \"Not found\");\n return;\n }\n handle(request, response, url);\n }\n\n /** 200 while the app answers its own health check, 503 when it does not. */\n async function health(response: ServerResponse): Promise<void> {\n const probe = options.probe;\n let up = true;\n if (probe) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n up = await Promise.race([\n probe().catch(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), PROBE_TIMEOUT_MS);\n }),\n ]);\n clearTimeout(timer);\n }\n send(\n response,\n up ? 200 : 503,\n JSON.stringify({\n status: up ? \"ok\" : \"degraded\",\n ...(probe ? { app: up ? \"up\" : \"down\" } : {}),\n }),\n { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" },\n );\n }\n\n function handle(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ): void {\n const { pathname } = url;\n if (request.method === \"GET\" && pathname === \"/\") {\n send(response, 200, DEV_DASHBOARD_SHELL, {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n return;\n }\n if (request.method === \"GET\" && pathname.startsWith(\"/assets/\")) {\n serveAsset(response, pathname.slice(\"/assets/\".length));\n return;\n }\n if (request.method === \"GET\" && pathname === \"/api/state\") {\n send(response, 200, JSON.stringify(snapshot()), {\n \"content-type\": \"application/json\",\n });\n return;\n }\n if (request.method === \"GET\" && pathname === \"/api/events\") {\n eventStream(request, response);\n return;\n }\n if (\n request.method === \"GET\" &&\n pathname.startsWith(\"/api/history\") &&\n options.history\n ) {\n history(options.history, pathname, url.searchParams, response);\n return;\n }\n if (request.method === \"GET\" && pathname.startsWith(\"/api/docs\")) {\n void docsRoute(response, pathname, url.searchParams);\n return;\n }\n if (request.method === \"GET\" && pathname === \"/api/openapi\") {\n send(response, 200, JSON.stringify(options.store.apiDocuments()), {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n });\n return;\n }\n if (pathname === \"/api/proxy\") {\n void proxy(request, response, url);\n return;\n }\n if (\n pathname === INSPECTOR_PATH ||\n pathname.startsWith(`${INSPECTOR_PATH}/`)\n ) {\n // Only the dashboard may frame it: framed by another site, a click could\n // land on Cancel or Replay. The rest of the dashboard may be embedded.\n response.setHeader(\"content-security-policy\", \"frame-ancestors 'self'\");\n response.setHeader(\"x-frame-options\", \"SAMEORIGIN\");\n void inspector(request, response, url);\n return;\n }\n if (request.method === \"POST\" && pathname === \"/api/ingest\") {\n ingest(request, response);\n return;\n }\n if (\n request.method === \"POST\" &&\n pathname === \"/api/restart\" &&\n options.restart\n ) {\n if (request.headers[\"x-brick-dashboard\"] !== \"1\") {\n send(response, 403, \"Forbidden\");\n return;\n }\n options.restart();\n send(response, 202, \"\");\n return;\n }\n send(response, 404, \"Not found\");\n }\n\n function snapshot() {\n return {\n ...options.store.snapshot(),\n canRestart: Boolean(options.restart),\n historyDays: options.history?.days ?? 0,\n mode: production ? \"production\" : \"dev\",\n };\n }\n\n /**\n * Accept telemetry from an application process that cannot share memory with\n * the dashboard, such as a dev server worker: span batches, and a notice when\n * the app loads.\n */\n function ingest(request: IncomingMessage, response: ServerResponse) {\n if (request.headers[\"x-brick-dashboard\"] !== \"1\") {\n send(response, 403, \"Forbidden\");\n return;\n }\n let body = \"\";\n let rejected = false;\n request.setEncoding(\"utf8\");\n request.on(\"data\", (chunk: string) => {\n if (rejected) return;\n body += chunk;\n if (body.length > MAX_INGEST_BYTES) {\n rejected = true;\n send(response, 413, \"Payload too large\");\n request.destroy();\n }\n });\n request.on(\"end\", () => {\n if (rejected) return;\n try {\n const payload = JSON.parse(body) as {\n records?: TelemetryRecord[];\n worker?: string;\n };\n if (Array.isArray(payload.records)) {\n options.store.ingest(payload.records, options.store.latestGeneration);\n }\n if (typeof payload.worker === \"string\") {\n options.store.startGeneration(payload.worker);\n }\n send(response, 204, \"\");\n } catch {\n send(response, 400, \"Bad request\");\n }\n });\n }\n\n /** The Docs tab's data: tree, compiled pages, search, images, components. */\n async function docsRoute(\n response: ServerResponse,\n pathname: string,\n params: URLSearchParams,\n ): Promise<void> {\n const docs = options.docs?.();\n if (!docs) {\n send(response, 404, \"The app has no documentation.\");\n return;\n }\n const json = (body: unknown) =>\n send(response, 200, JSON.stringify(body), {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n });\n try {\n if (pathname === \"/api/docs\") return json(docs.info());\n if (pathname === \"/api/docs/search\")\n return json(await docs.search(params.get(\"q\") ?? \"\"));\n if (pathname === \"/api/docs/components.js\") {\n const code = await docs.components();\n if (code === undefined) return send(response, 404, \"No components.\");\n return send(response, 200, code, {\n \"content-type\": \"text/javascript; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n }\n const pagePrefix = \"/api/docs/page\";\n if (pathname === pagePrefix || pathname.startsWith(`${pagePrefix}/`)) {\n const slugs = pathname\n .slice(pagePrefix.length)\n .split(\"/\")\n .filter(Boolean)\n .map(decodeURIComponent);\n const page = await docs.page(slugs);\n return page ? json(page) : send(response, 404, \"No such page.\");\n }\n const filePrefix = \"/api/docs/files/\";\n if (pathname.startsWith(filePrefix)) {\n const file = await docs.file(\n pathname\n .slice(filePrefix.length)\n .split(\"/\")\n .map(decodeURIComponent)\n .join(\"/\"),\n );\n if (!file) return send(response, 404, \"No such file.\");\n return send(response, 200, file.body, {\n \"content-type\": file.type,\n \"cache-control\": \"no-store\",\n // An image in a page; a document opened directly cannot run scripts.\n \"content-security-policy\": \"sandbox\",\n });\n }\n send(response, 404, \"Not found\");\n } catch (error) {\n send(\n response,\n error instanceof URIError ? 400 : 500,\n error instanceof Error ? error.message : String(error),\n );\n }\n }\n\n /**\n * Send a request on to the app for the APIs view, which cannot call the app\n * directly: it is another origin. Only the dashboard's own page may use this,\n * and only to reach the app being shown. The address to call is `?url=`; a\n * `?cookie=` is the cookie parameters the reader typed into Try it, and the\n * only cookie the app is sent (the dashboard's own are never forwarded).\n */\n /**\n * Pass a request to the workflow inspector, which the app serves on a port of\n * its own, and stream its answer back (it follows a run's output as it\n * grows). Anyone who can open the dashboard may look, but a change must come\n * from the dashboard's own page: the inspector can cancel runs and resume\n * hooks, and a page on another site could otherwise post to it.\n */\n async function inspector(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ): Promise<void> {\n const target = options.store.inspectorTarget();\n if (!target) {\n send(\n response,\n 503,\n \"The workflow inspector is not running. The app may be restarting, or it may run no workflows.\",\n { \"content-type\": \"text/plain; charset=utf-8\" },\n );\n return;\n }\n const bodyless = request.method === \"GET\" || request.method === \"HEAD\";\n const site = request.headers[\"sec-fetch-site\"];\n const origin = request.headers.origin;\n if (\n !bodyless &&\n ((site !== undefined && site !== \"same-origin\") ||\n (origin !== undefined && origin !== `http://${request.headers.host}`))\n ) {\n send(response, 403, \"Forbidden\");\n return;\n }\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (value === undefined || NOT_FORWARDED.has(name)) continue;\n if (name.startsWith(\"sec-\")) continue;\n headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n }\n headers.set(INSPECTOR_TOKEN_HEADER, target.token);\n const abort = new AbortController();\n response.on(\"close\", () => abort.abort());\n try {\n const upstream = await fetch(\n `http://127.0.0.1:${target.port}${url.pathname}${url.search}`,\n {\n method: request.method,\n headers,\n redirect: \"manual\",\n signal: abort.signal,\n ...(bodyless\n ? {}\n : {\n body: Readable.toWeb(request) as unknown as BodyInit,\n duplex: \"half\",\n }),\n } as RequestInit,\n );\n const returned: Record<string, string> = {};\n upstream.headers.forEach((value, name) => {\n if (!NOT_RETURNED.has(name)) returned[name] = value;\n });\n response.writeHead(upstream.status, returned);\n if (!upstream.body || request.method === \"HEAD\") {\n response.end();\n return;\n }\n await pipeline(Readable.fromWeb(upstream.body as never), response);\n } catch {\n if (response.headersSent) response.destroy();\n else send(response, 502, \"Could not reach the workflow inspector.\");\n }\n }\n\n async function proxy(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ): Promise<void> {\n const site = request.headers[\"sec-fetch-site\"];\n const origin = request.headers.origin;\n if (\n (site !== undefined && site !== \"same-origin\") ||\n (origin !== undefined && origin !== `http://${request.headers.host}`)\n ) {\n send(response, 403, \"Forbidden\");\n return;\n }\n let target: URL | undefined;\n try {\n target = new URL(url.searchParams.get(\"url\") ?? \"\");\n } catch {\n // Not an address; refused below.\n }\n const appUrl = options.store.apiSnapshot()?.appUrl;\n if (!target || !appUrl || target.origin !== new URL(appUrl).origin) {\n send(\n response,\n 403,\n \"Only the app shown in the dashboard can be reached.\",\n );\n return;\n }\n const body = await readBytes(request, MAX_PROXY_BYTES);\n if (!body) {\n send(response, 413, \"Payload too large\");\n return;\n }\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (value === undefined || NOT_FORWARDED.has(name)) continue;\n if (name.startsWith(\"sec-\")) continue;\n headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n }\n const cookie = url.searchParams.get(\"cookie\");\n if (cookie) headers.set(\"cookie\", cookie);\n const bodyless = request.method === \"GET\" || request.method === \"HEAD\";\n try {\n const upstream = await fetch(target, {\n method: request.method,\n headers,\n body: bodyless ? undefined : (body as BodyInit),\n redirect: \"manual\",\n });\n const returned: Record<string, string> = {};\n upstream.headers.forEach((value, name) => {\n if (!NOT_RETURNED.has(name)) returned[name] = value;\n });\n send(\n response,\n upstream.status,\n new Uint8Array(await upstream.arrayBuffer()),\n returned,\n );\n } catch {\n send(response, 502, \"Could not reach the app.\");\n }\n }\n\n function eventStream(request: IncomingMessage, response: ServerResponse) {\n response.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n // So a proxy in front passes events on as they come.\n \"x-accel-buffering\": \"no\",\n });\n const write = (chunk: string) => {\n if (response.writableEnded || response.destroyed) return;\n response.write(chunk);\n };\n write(`event: snapshot\\ndata: ${JSON.stringify(snapshot())}\\n\\n`);\n const unsubscribe = options.store.subscribe((event: DevTelemetryEvent) =>\n write(`event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`),\n );\n const keepalive = setInterval(() => write(\": keepalive\\n\\n\"), KEEPALIVE_MS);\n request.on(\"close\", () => {\n clearInterval(keepalive);\n unsubscribe();\n });\n }\n\n return new Promise((resolve, reject) => {\n server.once(\"error\", (error) => {\n reject(\n new Error(\n production\n ? `Brick: dashboard port ${options.port} is unavailable. Set dashboard.port in brick() to another.`\n : `Brick: dashboard port ${options.port} is unavailable. Use --dashboard-port <number> or --no-dashboard.`,\n { cause: error },\n ),\n );\n });\n server.listen(options.port, host, () => {\n const address = server.address();\n const port =\n typeof address === \"object\" && address !== null\n ? address.port\n : options.port;\n allowedHosts = new Set([\n `127.0.0.1:${port}`,\n `localhost:${port}`,\n `[::1]:${port}`,\n ]);\n resolve({\n port,\n stop() {\n server.close();\n server.closeAllConnections();\n },\n });\n });\n });\n}\n\n/** The whole request body, or undefined when it is larger than `limit`. */\nfunction readBytes(\n request: IncomingMessage,\n limit: number,\n): Promise<Uint8Array | undefined> {\n return new Promise((resolve) => {\n const chunks: Buffer[] = [];\n let size = 0;\n request.on(\"data\", (chunk: Buffer) => {\n size += chunk.length;\n if (size > limit) {\n resolve(undefined);\n request.destroy();\n return;\n }\n chunks.push(chunk);\n });\n request.on(\"end\", () => resolve(new Uint8Array(Buffer.concat(chunks))));\n request.on(\"error\", () => resolve(undefined));\n });\n}\n\nfunction history(\n store: DevHistory,\n pathname: string,\n params: URLSearchParams,\n response: ServerResponse,\n): void {\n const json = (body: unknown) =>\n send(response, 200, JSON.stringify(body), {\n \"content-type\": \"application/json\",\n });\n try {\n if (pathname === \"/api/history\") return json(store.info());\n if (pathname === \"/api/history/summary\") {\n return json(store.summary(parseHistoryQuery(params)));\n }\n if (pathname === \"/api/history/traces\") {\n return json(store.traces(parseHistoryQuery(params)));\n }\n if (pathname === \"/api/history/facets\") {\n return json(store.facets(parseHistoryQuery(params)));\n }\n if (pathname === \"/api/history/volume\") {\n return json(store.volume(parseHistoryQuery(params)));\n }\n if (pathname === \"/api/history/export\") {\n return send(response, 200, store.exportCsv(parseHistoryQuery(params)), {\n \"content-type\": \"text/csv; charset=utf-8\",\n \"content-disposition\": 'attachment; filename=\"brick-requests.csv\"',\n \"cache-control\": \"no-store\",\n });\n }\n const prefix = \"/api/history/traces/\";\n if (pathname.startsWith(prefix)) {\n const trace = store.trace(\n decodeURIComponent(pathname.slice(prefix.length)),\n );\n if (trace) return json(trace);\n }\n send(response, 404, \"Not found\");\n } catch {\n send(response, 500, \"History query failed\");\n }\n}\n\nconst ASSET_TYPES: Record<string, string> = {\n \".js\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".woff2\": \"font/woff2\",\n};\n\n/** The built React app, next to `src/` in the repo and next to `dist/` when published. */\nfunction assetsDirectory(): string | undefined {\n for (const relative of [\"../dashboard-dist/\", \"../../dashboard-dist/\"]) {\n const directory = fileURLToPath(new URL(relative, import.meta.url));\n if (existsSync(join(directory, \"app.js\"))) return directory;\n }\n return undefined;\n}\n\nfunction serveAsset(response: ServerResponse, name: string): void {\n // Plain file names only: no separators, so a request cannot leave the folder.\n if (!/^[\\w.-]+$/.test(name) || name.startsWith(\".\")) {\n send(response, 404, \"Not found\");\n return;\n }\n const directory = assetsDirectory();\n if (!directory) {\n send(\n response,\n 503,\n \"Dashboard assets are missing. Build them with: bun run --filter @brickkit/cli build\",\n );\n return;\n }\n readFile(join(directory, name)).then(\n (body) =>\n send(response, 200, body, {\n \"content-type\":\n ASSET_TYPES[extname(name)] ?? \"application/octet-stream\",\n \"cache-control\": \"no-store\",\n }),\n () => send(response, 404, \"Not found\"),\n );\n}\n\nfunction send(\n response: ServerResponse,\n status: number,\n body: string | Uint8Array,\n headers: Record<string, string | string[]> = {\n \"content-type\": \"text/plain; charset=utf-8\",\n },\n): void {\n response.writeHead(status, headers);\n response.end(body);\n}\n","import { watch, type FSWatcher } from \"node:fs\";\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport {\n basename,\n dirname,\n extname,\n join,\n posix,\n relative,\n resolve,\n sep,\n} from \"node:path\";\nimport type { DocumentationOptions } from \"@brickkit/core\";\nimport type { DevTelemetryStore, DocsSnapshot } from \"./dev-telemetry-store\";\n\n/*\n * Developer documentation for the dashboard's Docs tab. The folder follows\n * Fumadocs' layout (frontmatter, meta.json, folder groups), and fumadocs-core\n * builds the page tree and search. MDX is compiled here and run in the browser\n * with the dashboard's components plus the project's own.\n *\n * fumadocs-core and @mdx-js/mdx are optional peers, loaded only when an app\n * sets `documentation`, so projects without docs do not install them.\n */\n\n/** One entry of the docs sidebar. */\nexport type DocsNode =\n | { type: \"page\"; name: string; url: string; description?: string }\n | {\n type: \"folder\";\n name: string;\n index?: { name: string; url: string };\n children: DocsNode[];\n defaultOpen?: boolean;\n }\n | { type: \"separator\"; name?: string };\n\nexport interface DocsTree {\n name: string;\n children: DocsNode[];\n}\n\nexport interface DocsHeading {\n title: string;\n url: string;\n depth: number;\n}\n\n/** A page ready to run in the browser. */\nexport interface DocsPage {\n title: string;\n description?: string;\n /** The file, relative to the docs folder. */\n path: string;\n slugs: string[];\n toc: DocsHeading[];\n /** MDX compiled to a function body; see `runMdx` in the dashboard. */\n code: string;\n /** Set instead of `code` when the page does not compile. */\n error?: string;\n}\n\nexport interface DocsSearchHit {\n id: string;\n type: \"page\" | \"heading\" | \"text\";\n content: string;\n /** Route within the docs, with a `#heading` when the hit is inside a page. */\n url: string;\n}\n\nexport interface DocsInfo {\n tree: DocsTree;\n /** Whether the project supplied components of its own. */\n components: boolean;\n revision: number;\n}\n\nexport type OpenedDocs =\n | { status: \"ready\"; docs: DevDocs }\n | { status: \"missing\"; packages: string[] }\n | { status: \"error\"; message: string };\n\nconst PACKAGES = [\"fumadocs-core\", \"@mdx-js/mdx\"] as const;\nconst PAGE_EXTENSIONS = new Set([\".md\", \".mdx\"]);\nconst IMAGE_TYPES: Record<string, string> = {\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n};\nconst REFRESH_DELAY_MS = 100;\n\ninterface Fumadocs {\n loader: typeof import(\"fumadocs-core/source\").loader;\n frontmatter: typeof import(\"fumadocs-core/content/md/frontmatter\").frontmatter;\n plugins: typeof import(\"fumadocs-core/mdx-plugins\");\n createSearchAPI: typeof import(\"fumadocs-core/search/server\").createSearchAPI;\n compile: typeof import(\"@mdx-js/mdx\").compile;\n}\n\nasync function loadFumadocs(): Promise<Fumadocs | string[]> {\n try {\n const [source, matter, plugins, search, mdx] = await Promise.all([\n import(\"fumadocs-core/source\"),\n import(\"fumadocs-core/content/md/frontmatter\"),\n import(\"fumadocs-core/mdx-plugins\"),\n import(\"fumadocs-core/search/server\"),\n import(\"@mdx-js/mdx\"),\n ]);\n return {\n loader: source.loader,\n frontmatter: matter.frontmatter,\n plugins,\n createSearchAPI: search.createSearchAPI,\n compile: mdx.compile,\n };\n } catch (error) {\n // Only a missing package is the project's to fix; anything else is a bug.\n if (\n (error as { code?: string }).code === \"ERR_MODULE_NOT_FOUND\" ||\n /Cannot find (module|package)/.test(String((error as Error)?.message))\n )\n return [...PACKAGES];\n throw error;\n }\n}\n\ninterface PageFile {\n /** Relative to the docs folder, with forward slashes. */\n path: string;\n absolute: string;\n title: string;\n description?: string;\n /** The file's text after the frontmatter. */\n content: string;\n data: Record<string, unknown>;\n}\n\ninterface MetaFile {\n path: string;\n data: Record<string, unknown>;\n}\n\nconst humanize = (name: string): string => {\n const spaced = name.replace(/[-_]+/g, \" \").trim();\n return spaced.charAt(0).toUpperCase() + spaced.slice(1);\n};\n\nconst H1 = /^#\\s+(.+?)\\s*#*\\s*$/;\n\n/**\n * The first `# Heading` outside code fences: its text, and the content without\n * it. The page shows its title above the content, so a heading that only\n * repeats the title would appear twice.\n */\nfunction firstHeading(\n content: string,\n): { text: string; rest: string; leading: boolean } | undefined {\n const lines = content.split(\"\\n\");\n let fenced = false;\n let seenText = false;\n for (const [index, line] of lines.entries()) {\n if (/^\\s*(```|~~~)/.test(line)) {\n fenced = !fenced;\n seenText = true;\n } else if (!fenced) {\n const match = H1.exec(line);\n if (match) {\n const rest = [...lines.slice(0, index), ...lines.slice(index + 1)];\n // Drop the blank line that followed it as well.\n if (rest[index]?.trim() === \"\") rest.splice(index, 1);\n return { text: match[1]!, rest: rest.join(\"\\n\"), leading: !seenText };\n }\n if (line.trim() !== \"\") seenText = true;\n }\n }\n return undefined;\n}\n\nasync function scan(\n root: string,\n fumadocs: Fumadocs,\n warn: (message: string) => void,\n): Promise<{ pages: PageFile[]; metas: MetaFile[] }> {\n const pages: PageFile[] = [];\n const metas: MetaFile[] = [];\n async function visit(directory: string): Promise<void> {\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n const absolute = join(directory, entry.name);\n const path = relative(root, absolute).split(sep).join(\"/\");\n if (entry.isDirectory()) {\n await visit(absolute);\n } else if (entry.name === \"meta.json\") {\n try {\n const data = JSON.parse(await readFile(absolute, \"utf8\"));\n if (data && typeof data === \"object\") metas.push({ path, data });\n } catch (error) {\n warn(`[Brick-TS] Skipping docs ${path}: ${errorMessage(error)}`);\n }\n } else if (PAGE_EXTENSIONS.has(extname(entry.name))) {\n const text = await readFile(absolute, \"utf8\");\n let data: Record<string, unknown> = {};\n let content = text;\n try {\n const parsed = fumadocs.frontmatter(text);\n data = parsed.data as Record<string, unknown>;\n content = parsed.content;\n } catch (error) {\n warn(\n `[Brick-TS] Ignoring the frontmatter of docs ${path}: ${errorMessage(error)}`,\n );\n }\n const name = basename(entry.name, extname(entry.name));\n const heading = firstHeading(content);\n const given =\n typeof data.title === \"string\" && data.title ? data.title : undefined;\n const title =\n given ??\n heading?.text ??\n humanize(name === \"index\" ? basename(dirname(path)) || \"Home\" : name);\n // A title taken from the heading, or a leading heading that repeats the\n // frontmatter title, is shown once, above the content.\n if (heading && (!given || (heading.leading && heading.text === given)))\n content = heading.rest;\n pages.push({\n path,\n absolute,\n title,\n description:\n typeof data.description === \"string\" ? data.description : undefined,\n content,\n data,\n });\n }\n }\n }\n await visit(root);\n return { pages, metas };\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype MdastNode = {\n type: string;\n url?: string;\n name?: string | null;\n attributes?: { type: string; name?: string; value?: unknown }[];\n children?: MdastNode[];\n};\n\nfunction walk(node: MdastNode, visit: (node: MdastNode) => void): void {\n visit(node);\n for (const child of node.children ?? []) walk(child, visit);\n}\n\n/** Ways a link inside a page can point at another page or a local image. */\nfunction resolveInside(from: string, href: string): string | undefined {\n if (/^[a-z][a-z\\d+.-]*:/i.test(href) || href.startsWith(\"#\"))\n return undefined;\n if (href.startsWith(\"/\")) return undefined;\n const [target] = href.split(/[?#]/);\n if (!target) return undefined;\n const resolved = posix.normalize(posix.join(posix.dirname(from), target));\n return resolved.startsWith(\"../\") ? undefined : resolved;\n}\n\n/**\n * The page tree and compiled pages of one docs folder. It watches the folder,\n * so edits show in the dashboard as they are saved.\n */\nexport class DevDocs {\n readonly #root: string;\n readonly #documentation: DocumentationOptions;\n /** Relative paths in `documentation` start here: the app entry's folder. */\n readonly #base: string;\n readonly #fumadocs: Fumadocs;\n readonly #warn: (message: string) => void;\n readonly #listeners = new Set<() => void>();\n readonly #watchers: FSWatcher[] = [];\n #loader: Source | undefined;\n #pages = new Map<string, PageFile>();\n #byPath = new Map<string, string>();\n #compiled = new Map<string, DocsPage>();\n #search:\n | Promise<{ search(query: string): Promise<DocsSearchHit[]> }>\n | undefined;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #refreshing: Promise<void> = Promise.resolve();\n #closed = false;\n #title = \"Docs\";\n revision = 0;\n\n constructor(\n base: string,\n documentation: DocumentationOptions,\n fumadocs: Fumadocs,\n warn: (message: string) => void,\n ) {\n this.#base = base;\n this.#documentation = documentation;\n this.#root = resolve(base, documentation.dir);\n this.#fumadocs = fumadocs;\n this.#warn = warn;\n }\n\n /** Read the folder again and tell listeners. */\n async refresh(): Promise<void> {\n // Refreshes run one at a time, so a slow scan cannot overwrite a newer one.\n this.#refreshing = this.#refreshing.then(() => this.#scan());\n await this.#refreshing;\n }\n\n async #scan(): Promise<void> {\n const { pages, metas } = await scan(this.#root, this.#fumadocs, this.#warn);\n if (this.#closed) return;\n const source = this.#fumadocs.loader({\n baseUrl: \"/\",\n source: {\n files: [\n ...pages.map((page) => ({\n type: \"page\" as const,\n path: page.path,\n data: {\n ...page.data,\n title: page.title,\n description: page.description,\n },\n })),\n ...metas.map((meta) => ({\n type: \"meta\" as const,\n path: meta.path,\n data: meta.data,\n })),\n ],\n },\n });\n this.#loader = source as unknown as Source;\n this.#pages = new Map();\n this.#byPath = new Map();\n for (const page of this.#loader.getPages()) {\n const slug = page.slugs.join(\"/\");\n const file = pages.find((candidate) => candidate.path === page.path);\n if (!file) continue;\n this.#pages.set(slug, file);\n this.#byPath.set(file.path, slug);\n }\n this.#compiled.clear();\n this.#search = undefined;\n const tree = this.#loader.getPageTree();\n this.#title = typeof tree.name === \"string\" ? tree.name : \"Docs\";\n this.revision++;\n for (const listener of this.#listeners) listener();\n }\n\n /** Start watching the folder, and the project's components module. */\n watch(): void {\n const changed = () => {\n clearTimeout(this.#timer);\n this.#timer = setTimeout(() => {\n void this.refresh().catch((error) =>\n this.#warn(`[Brick-TS] Docs: ${errorMessage(error)}`),\n );\n }, REFRESH_DELAY_MS);\n };\n const folders = [this.#root];\n if (this.#documentation.components)\n folders.push(dirname(this.#componentsPath()!));\n for (const [index, folder] of folders.entries()) {\n try {\n // Recursive for the docs; the components module's folder is the\n // project's own source, where only its direct files matter.\n this.#watchers.push(\n watch(folder, { recursive: index === 0 }, () => changed()),\n );\n } catch {\n try {\n this.#watchers.push(watch(folder, () => changed()));\n } catch {\n // A folder that cannot be watched still works; it just needs a reload.\n }\n }\n }\n }\n\n onChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n snapshot(): DocsSnapshot {\n return {\n revision: this.revision,\n status: \"ready\",\n title: this.#title,\n components: Boolean(this.#documentation.components),\n };\n }\n\n info(): DocsInfo {\n return {\n tree: simplify(this.#loader?.getPageTree()),\n components: Boolean(this.#documentation.components),\n revision: this.revision,\n };\n }\n\n /** Compile one page; undefined when there is no such page. */\n async page(slugs: string[]): Promise<DocsPage | undefined> {\n const key = slugs.join(\"/\");\n const file = this.#pages.get(key);\n if (!file) return undefined;\n const cached = this.#compiled.get(key);\n if (cached) return cached;\n const page = await this.#compile(file, slugs);\n // A refresh while compiling clears the cache; do not put stale output back.\n if (this.#pages.get(key) === file) this.#compiled.set(key, page);\n return page;\n }\n\n async #compile(file: PageFile, slugs: string[]): Promise<DocsPage> {\n const { plugins, compile } = this.#fumadocs;\n const base = {\n title: file.title,\n description: file.description,\n path: file.path,\n slugs,\n };\n try {\n const result = await compile(\n { path: file.absolute, value: file.content },\n {\n outputFormat: \"function-body\",\n development: false,\n remarkPlugins: [\n plugins.remarkGfm,\n plugins.remarkHeading,\n plugins.remarkCodeTab,\n plugins.remarkNpm,\n plugins.remarkAdmonition,\n () => (tree: MdastNode) => this.#rewriteLinks(tree, file.path),\n ],\n rehypePlugins: [plugins.rehypeCode],\n },\n );\n const toc = (result.data.toc ?? []) as {\n title: unknown;\n url: string;\n depth: number;\n }[];\n return {\n ...base,\n toc: toc.map((item) => ({\n title: plainText(item.title),\n url: item.url,\n depth: item.depth,\n })),\n code: String(result),\n };\n } catch (error) {\n return { ...base, toc: [], code: \"\", error: errorMessage(error) };\n }\n }\n\n /**\n * Links to other pages become dashboard routes, and local images are served\n * from the docs folder, so a folder reads the same here as on a docs site.\n * This covers markdown links and the `href` of components such as `<Card>`.\n */\n #rewriteLinks(tree: MdastNode, from: string): void {\n const file = (resolved: string) =>\n `/api/docs/files/${resolved.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n walk(tree, (node) => {\n if (node.type === \"link\" && node.url !== undefined) {\n node.url = this.#route(from, node.url) ?? node.url;\n } else if (node.type === \"image\" && node.url !== undefined) {\n const resolved = resolveInside(from, node.url);\n if (resolved !== undefined) node.url = file(resolved);\n } else if (\n node.type === \"mdxJsxFlowElement\" ||\n node.type === \"mdxJsxTextElement\"\n ) {\n for (const attribute of node.attributes ?? []) {\n if (attribute.type !== \"mdxJsxAttribute\") continue;\n if (typeof attribute.value !== \"string\") continue;\n if (attribute.name === \"href\")\n attribute.value =\n this.#route(from, attribute.value) ?? attribute.value;\n else if (attribute.name === \"src\" && node.name === \"img\") {\n const resolved = resolveInside(from, attribute.value);\n if (resolved !== undefined) attribute.value = file(resolved);\n }\n }\n }\n });\n }\n\n /**\n * The dashboard route for a link to a page of these docs, or undefined for\n * anything else (other sites, in-page anchors, files). A link to a page that\n * does not exist still becomes a route, so it says \"No such page\" here\n * instead of leaving the dashboard.\n */\n #route(from: string, href: string): string | undefined {\n const hashAt = href.indexOf(\"#\");\n const hash = hashAt >= 0 ? href.slice(hashAt) : \"\";\n const target =\n (hashAt >= 0 ? href.slice(0, hashAt) : href).split(\"?\")[0] ?? \"\";\n const route = (slug: string) => `#/docs${slug ? `/${slug}` : \"\"}${hash}`;\n if (/^[a-z][a-z\\d+.-]*:/i.test(href) || href.startsWith(\"#\") || !target)\n return undefined;\n if (target.startsWith(\"/\")) {\n // A docs site links by address (/guide/setup); so can these pages.\n const slug = target.replace(/^\\/+|\\/+$/g, \"\");\n return this.#pages.has(slug) ? route(slug) : undefined;\n }\n const resolved = resolveInside(from, target);\n if (resolved === undefined) return undefined;\n const known = this.#byPath.get(resolved);\n if (known !== undefined) return route(known);\n if (!PAGE_EXTENSIONS.has(extname(resolved))) return undefined;\n const guess = resolved\n .slice(0, -extname(resolved).length)\n .replace(/(^|\\/)index$/, \"\");\n return route(guess);\n }\n\n async search(query: string): Promise<DocsSearchHit[]> {\n if (!query.trim()) return [];\n this.#search ??= this.#buildSearch();\n return (await this.#search).search(query);\n }\n\n async #buildSearch() {\n const { plugins, createSearchAPI } = this.#fumadocs;\n const indexes = [...this.#pages.entries()].map(([slug, file]) => ({\n id: file.path,\n title: file.title,\n description: file.description,\n url: `/${slug}`,\n structuredData: plugins.structure(file.content),\n }));\n const api = createSearchAPI(\"advanced\", { indexes });\n return {\n async search(query: string) {\n return (await api.search(query)) as DocsSearchHit[];\n },\n };\n }\n\n /** A file from the docs folder that a page can show, such as an image. */\n async file(\n relativePath: string,\n ): Promise<{ body: Uint8Array; type: string } | undefined> {\n const type = IMAGE_TYPES[extname(relativePath).toLowerCase()];\n if (!type) return undefined;\n const absolute = resolve(this.#root, relativePath);\n // Stay inside the docs folder, whatever the path says.\n if (absolute !== this.#root && !absolute.startsWith(this.#root + sep))\n return undefined;\n try {\n if (!(await stat(absolute)).isFile()) return undefined;\n return { body: new Uint8Array(await readFile(absolute)), type };\n } catch {\n return undefined;\n }\n }\n\n #componentsPath(): string | undefined {\n const { components } = this.#documentation;\n return components ? resolve(this.#base, components) : undefined;\n }\n\n /** The project's components as one browser module; undefined when it has none. */\n async components(): Promise<string | undefined> {\n const entry = this.#componentsPath();\n return entry ? bundleComponents(entry) : undefined;\n }\n\n close(): void {\n this.#closed = true;\n clearTimeout(this.#timer);\n for (const watcher of this.#watchers) watcher.close();\n this.#watchers.length = 0;\n this.#listeners.clear();\n }\n}\n\n// What the dashboard supplies to the project's components itself, so there is\n// only one copy of React on the page. See the import map in the page shell.\nconst SHARED = [\"react\", \"react/jsx-runtime\", \"react/jsx-dev-runtime\"];\n\n/** Bundle a module of React components for the dashboard to import. */\nexport async function bundleComponents(entry: string): Promise<string> {\n if (typeof Bun !== \"undefined\") {\n const result = await Bun.build({\n entrypoints: [entry],\n target: \"browser\",\n format: \"esm\",\n external: SHARED,\n minify: false,\n });\n if (!result.success)\n throw new Error(result.logs.map((log) => log.message).join(\"\\n\"));\n return result.outputs[0]!.text();\n }\n // Under Node the dev server's own bundler does the work. The name is not\n // written as a literal so the CLI's Bun bundle, which never gets here,\n // stays free of a Vite import.\n const bundler = \"vite\";\n const { build } = (await import(bundler)) as typeof import(\"vite\");\n const output = await build({\n configFile: false,\n logLevel: \"silent\",\n root: dirname(entry),\n oxc: { jsx: { runtime: \"automatic\" } },\n esbuild: { jsx: \"automatic\" },\n define: { \"process.env.NODE_ENV\": '\"development\"' },\n build: {\n write: false,\n minify: false,\n lib: { entry, formats: [\"es\"], fileName: \"components\" },\n rollupOptions: { external: SHARED },\n },\n } as never);\n const bundles = Array.isArray(output) ? output : [output];\n for (const bundle of bundles) {\n const chunk = (\"output\" in bundle ? bundle.output : []).find(\n (item) => item.type === \"chunk\" && item.isEntry,\n );\n if (chunk && \"code\" in chunk) return chunk.code;\n }\n throw new Error(\"Brick: the docs components module produced no output.\");\n}\n\n/** Flatten what MDX gives for a heading to text. */\nfunction plainText(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.map(plainText).join(\"\");\n if (value && typeof value === \"object\") {\n const node = value as {\n props?: { children?: unknown };\n children?: unknown;\n value?: unknown;\n };\n if (typeof node.value === \"string\") return node.value;\n return plainText(node.props?.children ?? node.children);\n }\n return \"\";\n}\n\ninterface RawNode {\n type: string;\n name?: unknown;\n url?: string;\n description?: unknown;\n index?: RawNode;\n children?: RawNode[];\n defaultOpen?: boolean;\n}\ntype RawTree = { name?: unknown; children: RawNode[] };\n\n/** What this module uses of a fumadocs-core loader. */\ninterface Source {\n getPages(): { slugs: string[]; path: string }[];\n getPageTree(): RawTree;\n}\n\n/** The page tree as plain data for the dashboard; icons and links are left out. */\nfunction simplify(tree: RawTree | undefined): DocsTree {\n const text = (value: unknown): string =>\n typeof value === \"string\" ? value : plainText(value);\n const convert = (node: RawNode): DocsNode | undefined => {\n if (node.type === \"page\" && node.url !== undefined)\n return {\n type: \"page\",\n name: text(node.name),\n url: node.url,\n ...(typeof node.description === \"string\"\n ? { description: node.description }\n : {}),\n };\n if (node.type === \"separator\")\n return {\n type: \"separator\",\n ...(node.name ? { name: text(node.name) } : {}),\n };\n if (node.type === \"folder\")\n return {\n type: \"folder\",\n name: text(node.name),\n ...(node.index?.url !== undefined\n ? { index: { name: text(node.index.name), url: node.index.url } }\n : {}),\n children: (node.children ?? []).flatMap(\n (child) => convert(child) ?? [],\n ),\n ...(node.defaultOpen ? { defaultOpen: true } : {}),\n };\n return undefined;\n };\n return {\n name: text(tree?.name) || \"Docs\",\n children: (tree?.children ?? []).flatMap((child) => convert(child) ?? []),\n };\n}\n\n/** Open a docs folder; says what is missing when it cannot be shown. */\nexport async function openDocs(options: {\n /** Where relative paths in `documentation` start: the app entry's folder. */\n base: string;\n documentation: DocumentationOptions;\n warn: (message: string) => void;\n}): Promise<OpenedDocs> {\n const fumadocs = await loadFumadocs();\n if (Array.isArray(fumadocs)) return { status: \"missing\", packages: fumadocs };\n const docs = new DevDocs(\n options.base,\n options.documentation,\n fumadocs,\n options.warn,\n );\n try {\n await docs.refresh();\n } catch (error) {\n docs.close();\n const root = resolve(options.base, options.documentation.dir);\n return {\n status: \"error\",\n message:\n (error as { code?: string }).code === \"ENOENT\"\n ? `The docs folder ${root} does not exist.`\n : errorMessage(error),\n };\n }\n docs.watch();\n return { status: \"ready\", docs };\n}\n\n/**\n * The docs of whichever app is running: opened when the app says where they\n * are, replaced when that changes, and closed when it stops asking for them.\n */\nexport class DocsHost {\n readonly #store: DevTelemetryStore;\n readonly #warn: (message: string) => void;\n #docs: DevDocs | undefined;\n #stopListening: (() => void) | undefined;\n #key: string | undefined;\n #pending: Promise<void> = Promise.resolve();\n\n constructor(store: DevTelemetryStore, warn: (message: string) => void) {\n this.#store = store;\n this.#warn = warn;\n }\n\n get current(): DevDocs | undefined {\n return this.#docs;\n }\n\n /**\n * Follow the app's `documentation`. Relative paths in it start at `base`, the\n * folder of the app entry, as they read in the file that sets them.\n */\n configure(\n base: string,\n documentation: DocumentationOptions | undefined,\n ): Promise<void> {\n this.#pending = this.#pending.then(() =>\n this.#configure(base, documentation),\n );\n return this.#pending;\n }\n\n async #configure(\n base: string,\n documentation: DocumentationOptions | undefined,\n ): Promise<void> {\n const key = JSON.stringify([base, documentation ?? null]);\n if (key === this.#key) return;\n this.#key = key;\n this.#release();\n if (!documentation) {\n this.#store.setDocs(null);\n return;\n }\n const opened = await openDocs({\n base,\n documentation,\n warn: this.#warn,\n });\n if (opened.status !== \"ready\") {\n const message =\n opened.status === \"missing\"\n ? `The docs need ${opened.packages.join(\" and \")}. Install with: bun add -d ${opened.packages.join(\" \")}`\n : opened.message;\n this.#warn(`[Brick-TS] Docs are off. ${message}`);\n this.#store.setDocs({\n revision: 1,\n status: opened.status,\n title: \"Docs\",\n components: false,\n message,\n ...(opened.status === \"missing\" ? { packages: opened.packages } : {}),\n });\n return;\n }\n this.#docs = opened.docs;\n this.#stopListening = opened.docs.onChange(() =>\n this.#store.setDocs(opened.docs.snapshot()),\n );\n this.#store.setDocs(opened.docs.snapshot());\n }\n\n #release(): void {\n this.#stopListening?.();\n this.#stopListening = undefined;\n this.#docs?.close();\n this.#docs = undefined;\n }\n\n close(): void {\n this.#key = undefined;\n this.#release();\n }\n}\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { ApiDocument, ArchitectureSchema } from \"@brickkit/core\";\nimport type { DevHistory } from \"./dev-history\";\nimport type {\n SerializedError,\n SpanEndRecord,\n SpanEventRecord,\n SpanStartRecord,\n TelemetryRecord,\n WorkerErrorPhase,\n} from \"./dev-telemetry\";\n\nexport type SpanOutcome = \"running\" | \"ok\" | \"error\" | \"interrupted\";\n\nexport interface TraceSpan {\n spanId: string;\n parentSpanId?: string;\n name: string;\n startMs: number;\n endMs?: number;\n status: SpanOutcome;\n statusMessage?: string;\n attributes: Attributes;\n events: SpanEventRecord[];\n}\n\nexport interface TraceSummary {\n traceId: string;\n name: string;\n method?: string;\n route?: string;\n /** The request's actual path, which differs from a wildcard route template. */\n path?: string;\n httpStatus?: number;\n generation: number;\n startMs: number;\n endMs?: number;\n durationMs?: number;\n status: SpanOutcome;\n truncated: boolean;\n /** The service and action that handled the request, when it ran one. */\n service?: string;\n action?: string;\n /** Why it failed, when it did. */\n message?: string;\n spans: TraceSpan[];\n}\n\nexport interface FailureSummary {\n id: number;\n at: number;\n phase: \"request\" | WorkerErrorPhase;\n code: string;\n message: string;\n status?: number;\n stack?: string;\n traceId?: string;\n route?: string;\n service?: string;\n action?: string;\n generation: number;\n}\n\nexport type ReloadKind = \"started\" | \"restarting\" | \"exited\" | \"contract-ready\";\n\nexport interface ReloadSummary {\n id: number;\n at: number;\n kind: ReloadKind;\n generation: number;\n detail?: string;\n}\n\n/** Services, actions, and routes of the application as last started. */\nexport interface ArchitectureSnapshot {\n generation: number;\n schema: ArchitectureSchema;\n}\n\n/** The OpenAPI documents the app offers, for the dashboard's APIs view. */\nexport interface ApiSnapshot {\n /** Changes each time the documents are replaced, so views know to reload. */\n revision: number;\n /** Where the app listens; Try it in the APIs view sends requests here. */\n appUrl?: string;\n /** Names of the documents, in order. */\n titles: string[];\n}\n\n/** What the dashboard knows about the app's developer documentation. */\nexport interface DocsSnapshot {\n /** Changes whenever the pages change, so the Docs tab reloads. */\n revision: number;\n status: \"ready\" | \"missing\" | \"error\";\n title: string;\n /** Whether the project supplied components of its own. */\n components: boolean;\n /** Why the docs cannot be shown, when `status` is not ready. */\n message?: string;\n /** Packages to install, when `status` is \"missing\". */\n packages?: string[];\n}\n\nexport type DevTelemetryEvent =\n | { type: \"trace\"; trace: TraceSummary }\n | { type: \"failure\"; failure: FailureSummary }\n | { type: \"reload\"; reload: ReloadSummary }\n | { type: \"architecture\"; architecture: ArchitectureSnapshot }\n | { type: \"api\"; api: ApiSnapshot }\n | { type: \"docs\"; docs: DocsSnapshot | null }\n | { type: \"inspector\"; inspector: boolean };\n\nexport interface DevTelemetrySnapshot {\n traces: TraceSummary[];\n failures: FailureSummary[];\n reloads: ReloadSummary[];\n architecture: ArchitectureSnapshot | null;\n api: ApiSnapshot | null;\n /** Null when the app has no `documentation`. */\n docs: DocsSnapshot | null;\n /** Whether the app serves the workflow inspector the dashboard can show. */\n inspector: boolean;\n}\n\nconst LIMITS = { traces: 200, spansPerTrace: 500, failures: 200, reloads: 100 };\n\nconst WORKER_FAILURE_CODES: Record<WorkerErrorPhase, string> = {\n startup: \"STARTUP_FAILED\",\n uncaught: \"UNCAUGHT_EXCEPTION\",\n \"unhandled-rejection\": \"UNHANDLED_REJECTION\",\n};\n\ninterface TraceEntry {\n traceId: string;\n generation: number;\n spans: Map<string, TraceSpan>;\n rootSpanId?: string;\n name: string;\n method?: string;\n route?: string;\n path?: string;\n httpStatus?: number;\n startMs: number;\n endMs?: number;\n status: SpanOutcome;\n failureRecorded: boolean;\n truncated: boolean;\n message?: string;\n}\n\n/**\n * Supervisor-side history of requests, failures, and reloads. It lives in the\n * parent process, so it survives application restarts.\n */\nexport class DevTelemetryStore {\n readonly #traces = new Map<string, TraceEntry>();\n readonly #failures: FailureSummary[] = [];\n readonly #reloads: ReloadSummary[] = [];\n readonly #listeners = new Set<(event: DevTelemetryEvent) => void>();\n readonly #history: DevHistory | undefined;\n #architecture: ArchitectureSnapshot | null = null;\n #api: ApiSnapshot | null = null;\n #docs: DocsSnapshot | null = null;\n #inspector: { port: number; token: string } | undefined;\n #apiDocuments: ApiDocument[] = [];\n #sequence = 0;\n #generation = 0;\n\n /** Finished requests and failures are also kept in `history`, when given. */\n constructor(options: { history?: DevHistory } = {}) {\n this.#history = options.history;\n }\n\n /** Replace the architecture with the one from the latest successful start. */\n setArchitecture(schema: ArchitectureSchema, generation: number): void {\n this.#architecture = { generation, schema };\n this.#emit({ type: \"architecture\", architecture: this.#architecture });\n }\n\n ingest(records: TelemetryRecord[], generation: number): void {\n const touched = new Set<TraceEntry>();\n for (const record of records) {\n const timeMs = record.phase === \"start\" ? record.startMs : record.endMs;\n const entry = this.#entry(record.traceId, generation, timeMs);\n touched.add(entry);\n if (record.phase === \"start\") this.#start(entry, record);\n else this.#end(entry, record);\n }\n for (const entry of touched) {\n const trace = summarize(entry);\n this.#emit({ type: \"trace\", trace });\n // A request cut off by a restart is not a result worth keeping, and one\n // still running will be saved when it finishes.\n if (entry.status === \"ok\" || entry.status === \"error\") {\n this.#history?.saveTrace(trace);\n }\n }\n }\n\n recordWorkerError(\n phase: WorkerErrorPhase,\n error: SerializedError,\n generation: number,\n ): void {\n this.#pushFailure({\n phase,\n code: WORKER_FAILURE_CODES[phase],\n message: error.message,\n stack: error.stack,\n generation,\n });\n }\n\n recordReload(reload: Omit<ReloadSummary, \"id\" | \"at\">): void {\n const summary: ReloadSummary = {\n id: ++this.#sequence,\n at: Date.now(),\n ...reload,\n };\n this.#reloads.unshift(summary);\n if (this.#reloads.length > LIMITS.reloads) {\n this.#reloads.length = LIMITS.reloads;\n }\n this.#emit({ type: \"reload\", reload: summary });\n }\n\n /** Newest generation; spans reported without a process identity belong to it. */\n get latestGeneration(): number {\n return this.#generation;\n }\n\n /** Begin a generation when an application process loads, and record the reload. */\n startGeneration(detail: string): number {\n this.#generation += 1;\n this.recordReload({\n kind: \"started\",\n generation: this.#generation,\n detail,\n });\n return this.#generation;\n }\n\n /** Mark requests still running in a process that has exited as interrupted. */\n interruptGeneration(generation: number): void {\n const now = Date.now();\n for (const entry of this.#traces.values()) {\n if (entry.generation !== generation || entry.status !== \"running\")\n continue;\n entry.status = \"interrupted\";\n entry.endMs = now;\n for (const span of entry.spans.values()) {\n if (span.status !== \"running\") continue;\n span.status = \"interrupted\";\n span.endMs = now;\n }\n this.#emit({ type: \"trace\", trace: summarize(entry) });\n }\n }\n\n /** Replace the OpenAPI documents with the ones from the latest start. */\n setApiDocuments(documents: ApiDocument[], appUrl?: string): void {\n this.#apiDocuments = documents;\n this.#api = {\n revision: (this.#api?.revision ?? 0) + 1,\n ...(appUrl ? { appUrl } : {}),\n titles: documents.map((item) => item.title),\n };\n this.#emit({ type: \"api\", api: this.#api });\n }\n\n /** Set what the Docs tab shows; null when the app has no documentation. */\n setDocs(docs: DocsSnapshot | null): void {\n this.#docs = docs;\n this.#emit({ type: \"docs\", docs });\n }\n\n /**\n * Set where the app serves its workflow inspector, or `undefined` when it\n * stops. The address stays here: the snapshot says only whether there is one.\n */\n setInspector(target: { port: number; token: string } | undefined): void {\n this.#inspector = target;\n this.#emit({ type: \"inspector\", inspector: Boolean(target) });\n }\n\n /** Where the dashboard proxies the workflow inspector, when the app serves one. */\n inspectorTarget(): { port: number; token: string } | undefined {\n return this.#inspector;\n }\n\n /** What the APIs view knows about the documents, without the documents. */\n apiSnapshot(): ApiSnapshot | null {\n return this.#api;\n }\n\n /** The documents themselves; the snapshot carries only their names. */\n apiDocuments(): ApiDocument[] {\n return this.#apiDocuments;\n }\n\n snapshot(): DevTelemetrySnapshot {\n return {\n traces: [...this.#traces.values()].reverse().map(summarize),\n failures: [...this.#failures],\n reloads: [...this.#reloads],\n architecture: this.#architecture,\n api: this.#api,\n docs: this.#docs,\n inspector: Boolean(this.#inspector),\n };\n }\n\n subscribe(listener: (event: DevTelemetryEvent) => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #entry(traceId: string, generation: number, timeMs: number): TraceEntry {\n let entry = this.#traces.get(traceId);\n if (!entry) {\n entry = {\n traceId,\n generation,\n spans: new Map(),\n name: \"\",\n startMs: timeMs,\n status: \"running\",\n failureRecorded: false,\n truncated: false,\n };\n this.#traces.set(traceId, entry);\n if (this.#traces.size > LIMITS.traces) {\n const oldest = this.#traces.keys().next().value;\n if (oldest !== undefined) this.#traces.delete(oldest);\n }\n }\n return entry;\n }\n\n #start(entry: TraceEntry, record: SpanStartRecord): void {\n entry.startMs = Math.min(entry.startMs, record.startMs);\n // The local root has no parent here: either none, or a remote caller's span\n // from an incoming traceparent. Children start after it in this process.\n const parentIsLocal =\n record.parentSpanId !== undefined && entry.spans.has(record.parentSpanId);\n if (!parentIsLocal && entry.rootSpanId === undefined) {\n entry.rootSpanId = record.spanId;\n entry.name = record.name;\n entry.method = stringAttribute(record.attributes, \"http.request.method\");\n entry.route = stringAttribute(record.attributes, \"http.route\");\n entry.path = stringAttribute(record.attributes, \"url.path\");\n }\n if (entry.spans.size >= LIMITS.spansPerTrace) {\n entry.truncated = true;\n return;\n }\n entry.spans.set(record.spanId, {\n spanId: record.spanId,\n parentSpanId: record.parentSpanId,\n name: record.name,\n startMs: record.startMs,\n status: \"running\",\n attributes: record.attributes,\n events: [],\n });\n }\n\n #end(entry: TraceEntry, record: SpanEndRecord): void {\n const existing = entry.spans.get(record.spanId);\n const span: TraceSpan = existing ?? {\n spanId: record.spanId,\n name: record.name,\n startMs: record.endMs,\n status: \"running\",\n attributes: {},\n events: [],\n };\n if (!existing) {\n if (entry.spans.size < LIMITS.spansPerTrace) {\n entry.spans.set(record.spanId, span);\n } else {\n entry.truncated = true;\n }\n }\n span.endMs = record.endMs;\n span.status = record.status === \"error\" ? \"error\" : \"ok\";\n span.statusMessage = record.statusMessage;\n span.attributes = { ...span.attributes, ...record.attributes };\n span.events = record.events;\n\n const code = stringAttribute(record.attributes, \"brick.error.code\");\n if (code !== undefined) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code,\n message:\n stringAttribute(exception, \"exception.message\") ??\n stringAttribute(record.attributes, \"brick.error.message\") ??\n code,\n status: numberAttribute(record.attributes, \"brick.error.status\"),\n stack: stringAttribute(exception, \"exception.stacktrace\"),\n traceId: entry.traceId,\n route: entry.route,\n service: stringAttribute(record.attributes, \"brick.service\"),\n action: stringAttribute(record.attributes, \"brick.action\"),\n generation: entry.generation,\n });\n entry.failureRecorded = true;\n }\n\n if (record.spanId !== entry.rootSpanId) return;\n entry.endMs = record.endMs;\n entry.httpStatus = numberAttribute(\n record.attributes,\n \"http.response.status_code\",\n );\n // Server faults make the trace an error. Client errors still show in the\n // Errors tab, so a raw route's 401 is visible without a coded failure.\n const status = entry.httpStatus ?? 0;\n const serverFault = status >= 500;\n const failed = record.status === \"error\" || serverFault;\n entry.status = failed ? \"error\" : \"ok\";\n if ((failed || status >= 400) && !entry.failureRecorded) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code: status >= 400 ? `HTTP_${status}` : \"UNHANDLED_ERROR\",\n message:\n stringAttribute(exception, \"exception.message\") ??\n record.statusMessage ??\n describeResponse(entry, status),\n status: entry.httpStatus,\n stack: stringAttribute(exception, \"exception.stacktrace\"),\n traceId: entry.traceId,\n route: entry.route,\n generation: entry.generation,\n });\n entry.failureRecorded = true;\n }\n }\n\n #pushFailure(failure: Omit<FailureSummary, \"id\" | \"at\">): void {\n const entry: FailureSummary = {\n id: ++this.#sequence,\n at: Date.now(),\n ...failure,\n };\n this.#failures.unshift(entry);\n if (this.#failures.length > LIMITS.failures) {\n this.#failures.length = LIMITS.failures;\n }\n // The request keeps the first reason it failed, to show beside it.\n const trace =\n failure.traceId === undefined\n ? undefined\n : this.#traces.get(failure.traceId);\n if (trace) trace.message ??= failure.message;\n this.#emit({ type: \"failure\", failure: entry });\n }\n\n #emit(event: DevTelemetryEvent): void {\n for (const listener of this.#listeners) {\n try {\n listener(event);\n } catch {\n this.#listeners.delete(listener);\n }\n }\n }\n}\n\nfunction summarize(entry: TraceEntry): TraceSummary {\n const spans = [...entry.spans.values()].sort((a, b) => a.startMs - b.startMs);\n const actionSpan = spans.find((span) => span.name.startsWith(\"action \"));\n return {\n traceId: entry.traceId,\n name: entry.name || spans[0]?.name || entry.traceId,\n method: entry.method,\n route: entry.route,\n path: entry.path,\n httpStatus: entry.httpStatus,\n generation: entry.generation,\n startMs: entry.startMs,\n endMs: entry.endMs,\n durationMs:\n entry.endMs === undefined ? undefined : entry.endMs - entry.startMs,\n status: entry.status,\n truncated: entry.truncated,\n service: stringAttribute(actionSpan?.attributes, \"brick.service\"),\n action: stringAttribute(actionSpan?.attributes, \"brick.action\"),\n message: entry.message,\n spans,\n };\n}\n\nfunction describeResponse(entry: TraceEntry, status: number): string {\n const target = entry.path ?? entry.route ?? entry.name;\n const request = entry.method ? `${entry.method} ${target}` : target;\n return status ? `${request} returned ${status}` : request;\n}\n\nfunction findException(events: SpanEventRecord[]): Attributes | undefined {\n return events.find((event) => event.name === \"exception\")?.attributes;\n}\n\nfunction stringAttribute(\n attributes: Attributes | undefined,\n key: string,\n): string | undefined {\n const value = attributes?.[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction numberAttribute(\n attributes: Attributes | undefined,\n key: string,\n): number | undefined {\n const value = attributes?.[key];\n return typeof value === \"number\" ? value : undefined;\n}\n"],"mappings":";;;;;;;;;;AAOA,MAAa,iBAAiB;;AAE9B,MAAa,yBAAyB;;AAU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;CAC7D,OAAO,SAAS,GAAG,QAAQ,YAAY,WAAW;AACpD;AAEA,SAAS,cAAc,QAAmD;CACxE,OAAO,OAAO,MAAM,UAAU,MAAM,SAAS,WAAW,CAAC,EAAE;AAC7D;AAEA,SAAS,gBACP,YACA,KACoB;CACpB,MAAM,QAAQ,aAAa;CAC3B,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;AAEA,SAAS,gBACP,YACA,KACoB;CACpB,MAAM,QAAQ,aAAa;CAC3B,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C"}
|
|
1
|
+
{"version":3,"file":"dev-telemetry-store.js","names":[],"sources":["../src/dev-inspector.ts","../src/dev-history-csv.ts","../src/dev-history.ts","../src/dev-dashboard-shell.ts","../src/dashboard-access.ts","../src/dev-docs.ts","../src/dashboard-extension.ts","../src/dev-dashboard.ts","../src/dev-telemetry-store.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { existsSync, statSync } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport type { BrickApp } from \"@brickkit/core\";\n\n/** Where the dashboard serves the inspector. */\nexport const INSPECTOR_PATH = \"/workflows\";\n/** The header that proves a request comes from the dashboard. */\nexport const INSPECTOR_TOKEN_HEADER = \"x-brick-inspector\";\n\nexport interface Inspector {\n readonly port: number;\n /** Every request must carry it in `INSPECTOR_TOKEN_HEADER`. */\n readonly token: string;\n stop(): void;\n}\n\n/** The built inspector, next to `src/` in the repo and next to `dist/` when published. */\nconst INSPECTOR_DIRECTORY = fileURLToPath(\n new URL(\"../inspector-dist/\", import.meta.url),\n);\n\n/** Whether a path is a regular file; any failure to find out (not a directory, name too long) says no. */\nfunction isFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * A file of the inspector's browser build. Its names carry a hash of their\n * content, so a browser may keep them for good. Anything else under `assets/`\n * is a plain 404: the page would answer with HTML. `undefined` for requests\n * outside `assets/`, which are the page's to answer.\n */\nfunction browserAsset(request: Request, client: string): Response | undefined {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return undefined;\n const { pathname } = new URL(request.url);\n if (!pathname.startsWith(`${INSPECTOR_PATH}/assets/`)) return undefined;\n const file = resolve(client, pathname.slice(INSPECTOR_PATH.length + 1));\n if (!file.startsWith(client + sep) || !isFile(file))\n return new Response(\"Not found\", { status: 404 });\n return new Response(Bun.file(file), {\n headers: { \"cache-control\": \"public, max-age=31536000, immutable\" },\n });\n}\n\n/**\n * Serve the Workflow inspector (the Workflow SDK's observability UI, built into\n * this package) for the app's world, on a loopback port of its own. The\n * dashboard proxies it at `/workflows`; it is the only caller that knows the\n * token. The UI can cancel runs and resume hooks, so nothing else may reach it,\n * and it exists only under `brick dev`.\n *\n * @param app - The loaded app, running in this process.\n * @param directory - The inspector's build; this package's own by default.\n * @returns The inspector, or `undefined` when the app runs no workflows.\n * @throws When the inspector's build is missing.\n */\nexport async function startInspector(\n app: BrickApp,\n directory = INSPECTOR_DIRECTORY,\n): Promise<Inspector | undefined> {\n const target = app.events?.workflows;\n if (!target) return undefined;\n const entry = join(directory, \"server\", \"index.js\");\n if (!existsSync(entry))\n throw new Error(\n \"The workflow inspector is not built. Build it with: bun run --filter @brickkit/cli build\",\n );\n const { createFetchHandler } = (await import(pathToFileURL(entry).href)) as {\n createFetchHandler(\n basename: string,\n host: { world: unknown },\n ): (request: Request) => Promise<Response>;\n };\n const page = createFetchHandler(INSPECTOR_PATH, { world: target.world });\n const client = join(directory, \"client\");\n const token = randomBytes(16).toString(\"hex\");\n const server = Bun.serve({\n hostname: \"127.0.0.1\",\n port: 0,\n // The UI streams a run's output and holds the connection open.\n idleTimeout: 0,\n fetch: (request) =>\n request.headers.get(INSPECTOR_TOKEN_HEADER) === token\n ? (browserAsset(request, client) ?? page(request))\n : new Response(\"Forbidden\", { status: 403 }),\n });\n return { port: server.port!, token, stop: () => void server.stop(true) };\n}\n","import type { HistoryTrace } from \"./dev-history\";\n\n// Kept apart from dev-history so the dashboard can export what it shows without\n// pulling in the database code.\n\nconst CSV_COLUMNS = [\n \"time\",\n \"method\",\n \"route\",\n \"path\",\n \"status\",\n \"outcome\",\n \"duration_ms\",\n \"service\",\n \"action\",\n \"message\",\n \"trace_id\",\n] as const;\n\nfunction csvCell(value: string | number | undefined): string {\n if (value === undefined) return \"\";\n const text = String(value);\n // Quote anything a spreadsheet could split on, and defuse formulas.\n const safe = /^[=+\\-@\\t\\r]/.test(text) ? `'${text}` : text;\n return /[\",\\n\\r]/.test(safe) ? `\"${safe.replace(/\"/g, '\"\"')}\"` : safe;\n}\n\n/** Requests as CSV with a header row, for the dashboard's export. */\nexport function tracesToCsv(traces: HistoryTrace[]): string {\n const lines = traces.map((trace) => {\n const failed = trace.status === \"error\" || (trace.httpStatus ?? 0) >= 500;\n const client = (trace.httpStatus ?? 0) >= 400;\n return [\n new Date(trace.startMs).toISOString(),\n trace.method,\n trace.route,\n trace.path,\n trace.httpStatus ?? trace.status,\n failed ? \"server\" : client ? \"client\" : \"ok\",\n trace.durationMs === undefined ? undefined : trace.durationMs.toFixed(3),\n trace.service,\n trace.action,\n trace.message,\n trace.traceId,\n ]\n .map(csvCell)\n .join(\",\");\n });\n return [CSV_COLUMNS.join(\",\"), ...lines].join(\"\\n\") + \"\\n\";\n}\n","import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { tracesToCsv } from \"./dev-history-csv\";\nimport type { SpanOutcome, TraceSummary } from \"./dev-telemetry-store\";\n\nexport { tracesToCsv };\n\nexport const DEFAULT_HISTORY_DAYS = 90;\n\nconst DAY_MS = 86_400_000;\nconst MAX_TRACES = 100_000;\nconst FLUSH_MS = 250;\nconst PRUNE_MS = 30 * 60_000;\nconst VOLUME_BUCKETS = 48;\nconst DEFAULT_LIMIT = 100;\nconst MAX_LIMIT = 500;\nconst MAX_FACET_VALUES = 30;\nconst MAX_EXPORT_ROWS = 100_000;\n\n/** A finished request without its spans; fetch the full trace by id. */\nexport interface HistoryTrace {\n traceId: string;\n name: string;\n /** \"GET /api/page/:id\" when the method and route are known, else the span name. */\n endpoint: string;\n method?: string;\n route?: string;\n path?: string;\n httpStatus?: number;\n generation: number;\n startMs: number;\n endMs?: number;\n durationMs?: number;\n status: SpanOutcome;\n truncated: boolean;\n /** The service and action that handled the request, when it ran one. */\n service?: string;\n action?: string;\n /** Why it failed, when it did. */\n message?: string;\n}\n\n/** How a request ended: a 5xx or crash, a 4xx, or neither. */\nexport type Outcome = \"ok\" | \"client\" | \"server\";\nconst OUTCOMES = new Set<string>([\"ok\", \"client\", \"server\"]);\n\n/** A filter groups values with OR; separate filters combine with AND. */\nexport interface HistoryQuery {\n from: number;\n to: number;\n endpoints?: string[];\n methods?: string[];\n services?: string[];\n outcomes?: Outcome[];\n /** Only requests at least this slow. */\n minMs?: number;\n /** Matches the endpoint or the request path. */\n query?: string;\n sort?: \"recent\" | \"slowest\";\n limit?: number;\n offset?: number;\n}\n\nexport interface VolumeBucket {\n start: number;\n ok: number;\n client: number;\n server: number;\n}\n\n/** The numbers behind the cards at the top of the log, for what matches. */\nexport interface HistorySummary {\n total: number;\n clientErrors: number;\n serverErrors: number;\n medianMs: number;\n p95Ms: number;\n}\n\nexport interface FacetValue {\n value: string;\n count: number;\n}\n\n/** What is in the range, counted for each filter as if it were not applied. */\nexport interface HistoryFacets {\n outcome: FacetValue[];\n method: FacetValue[];\n service: FacetValue[];\n endpoint: FacetValue[];\n}\n\nexport interface HistoryInfo {\n days: number;\n count: number;\n oldestMs?: number;\n}\n\ninterface Statement {\n run(...params: unknown[]): unknown;\n all(...params: unknown[]): Record<string, unknown>[];\n get(...params: unknown[]): Record<string, unknown> | undefined;\n}\n\ninterface Database {\n exec(sql: string): void;\n prepare(sql: string): Statement;\n close(): void;\n}\n\n/**\n * SQLite from whichever runtime is running: `bun:sqlite` under Bun, and\n * `node:sqlite` under Node, which is what runs Vite's dev server. Both are\n * imported by a variable name so bundlers leave them alone.\n */\nasync function openDatabase(file: string): Promise<Database> {\n if (typeof Bun !== \"undefined\") {\n const specifier = \"bun:sqlite\";\n const { Database } = (await import(specifier)) as {\n Database: new (file: string, options: { create: boolean }) => Database;\n };\n return new Database(file, { create: true });\n }\n const specifier = \"node:sqlite\";\n // Node prints an experimental-feature warning when this module loads. It is\n // stable enough for a local log, and the warning would only confuse.\n const emit = process.emitWarning;\n process.emitWarning = ((warning: unknown, ...rest: unknown[]) => {\n if (typeof warning === \"string\" && warning.includes(\"SQLite\")) return;\n return (emit as (...args: unknown[]) => void).call(\n process,\n warning,\n ...rest,\n );\n }) as typeof process.emitWarning;\n try {\n const { DatabaseSync } = (await import(specifier)) as {\n DatabaseSync: new (file: string) => Database;\n };\n return new DatabaseSync(file);\n } finally {\n process.emitWarning = emit;\n }\n}\n\nexport interface OpenHistoryOptions {\n /** The project folder; the database lives in `.brick/` inside it. */\n directory: string;\n /** How long to keep requests. Zero or less turns history off. */\n days: number;\n warn?: (message: string) => void;\n}\n\n/**\n * Open the request history, or return undefined when it is turned off or this\n * runtime has no SQLite. Never throws: the dashboard works without history.\n */\nexport async function openHistory(\n options: OpenHistoryOptions,\n): Promise<DevHistory | undefined> {\n if (!(options.days > 0)) return undefined;\n try {\n const folder = join(options.directory, \".brick\");\n mkdirSync(folder, { recursive: true });\n // Requests can hold SQL text and error details, so never let them be\n // committed by accident.\n const ignore = join(folder, \".gitignore\");\n if (!existsSync(ignore)) writeFileSync(ignore, \"*\\n\");\n const database = await openDatabase(join(folder, \"telemetry.sqlite\"));\n return new DevHistory(database, options.days);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n options.warn?.(\n `[Brick-TS] Request history is unavailable (${reason}). It needs Bun, or Node 22.5 or later. Continuing without it.`,\n );\n return undefined;\n }\n}\n\nconst text = (value: unknown): string | undefined =>\n value === null || value === undefined ? undefined : String(value);\nconst number = (value: unknown): number | undefined =>\n value === null || value === undefined ? undefined : Number(value);\n\nfunction percentile(sorted: number[], fraction: number): number {\n if (sorted.length === 0) return 0;\n const position = (sorted.length - 1) * fraction;\n const lower = Math.floor(position);\n const upper = Math.ceil(position);\n return sorted[lower] + (sorted[upper] - sorted[lower]) * (position - lower);\n}\n\nconst OUTCOME_SQL: Record<Outcome, string> = {\n server: \"(status = 'error' OR http_status >= 500)\",\n client: \"(status != 'error' AND http_status >= 400 AND http_status < 500)\",\n ok: \"(status != 'error' AND (http_status IS NULL OR http_status < 400))\",\n};\n\n/** The outcome of each row, for counting; agrees with OUTCOME_SQL. */\nconst OUTCOME_CASE = `CASE\n WHEN status = 'error' OR http_status >= 500 THEN 'server'\n WHEN http_status >= 400 AND http_status < 500 THEN 'client'\n ELSE 'ok' END`;\n\ntype Facet = \"outcome\" | \"method\" | \"service\" | \"endpoint\";\n\nconst FACET_COLUMNS: Record<Facet, string> = {\n outcome: OUTCOME_CASE,\n method: \"method\",\n service: \"service\",\n endpoint: \"endpoint\",\n};\n\n/** The WHERE clause for a query, leaving out one filter when counting its facet. */\nfunction filterSql(\n query: HistoryQuery,\n skip?: Facet,\n): { sql: string; params: unknown[] } {\n const clauses = [\"start_ms >= ?\", \"start_ms <= ?\"];\n const params: unknown[] = [query.from, query.to];\n const anyOf = (column: string, values: string[] | undefined) => {\n if (!values || values.length === 0) return;\n clauses.push(`${column} IN (${values.map(() => \"?\").join(\", \")})`);\n params.push(...values);\n };\n if (skip !== \"endpoint\") anyOf(\"endpoint\", query.endpoints);\n if (skip !== \"method\") anyOf(\"method\", query.methods);\n if (skip !== \"service\") anyOf(\"service\", query.services);\n if (skip !== \"outcome\" && query.outcomes && query.outcomes.length > 0) {\n clauses.push(\n `(${query.outcomes.map((outcome) => OUTCOME_SQL[outcome]).join(\" OR \")})`,\n );\n }\n if (query.minMs !== undefined && query.minMs > 0) {\n clauses.push(\"duration_ms >= ?\");\n params.push(query.minMs);\n }\n const needle = query.query?.trim();\n if (needle) {\n const pattern = `%${needle.replace(/[\\\\%_]/g, \"\\\\$&\")}%`;\n clauses.push(\n \"(endpoint LIKE ? ESCAPE '\\\\' OR path LIKE ? ESCAPE '\\\\' OR name LIKE ? ESCAPE '\\\\' OR action LIKE ? ESCAPE '\\\\' OR message LIKE ? ESCAPE '\\\\')\",\n );\n params.push(pattern, pattern, pattern, pattern, pattern);\n }\n return { sql: clauses.join(\" AND \"), params };\n}\n\nconst LIST_COLUMNS = `trace_id, name, endpoint, method, route, path, http_status, generation,\n start_ms, end_ms, duration_ms, status, truncated, service, action, message`;\n\nfunction toHistoryTrace(row: Record<string, unknown>): HistoryTrace {\n return {\n traceId: String(row.trace_id),\n name: String(row.name),\n endpoint: String(row.endpoint),\n method: text(row.method),\n route: text(row.route),\n path: text(row.path),\n httpStatus: number(row.http_status),\n generation: Number(row.generation),\n startMs: Number(row.start_ms),\n endMs: number(row.end_ms),\n durationMs: number(row.duration_ms),\n status: String(row.status) as SpanOutcome,\n truncated: Number(row.truncated) === 1,\n service: text(row.service),\n action: text(row.action),\n message: text(row.message),\n };\n}\n\n/**\n * Requests kept on disk between runs, for looking back over weeks\n * instead of the last few minutes. Writes are batched; reads see them.\n */\nexport class DevHistory {\n readonly days: number;\n readonly #database: Database;\n readonly #pendingTraces = new Map<string, TraceSummary>();\n #flushTimer: ReturnType<typeof setTimeout> | undefined;\n readonly #pruneTimer: ReturnType<typeof setInterval>;\n #closed = false;\n\n constructor(database: Database, days: number) {\n this.#database = database;\n this.days = days;\n database.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n PRAGMA busy_timeout = 2000;\n CREATE TABLE IF NOT EXISTS traces (\n trace_id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n endpoint TEXT NOT NULL,\n method TEXT,\n route TEXT,\n path TEXT,\n http_status INTEGER,\n generation INTEGER NOT NULL,\n start_ms INTEGER NOT NULL,\n end_ms INTEGER,\n duration_ms REAL,\n status TEXT NOT NULL,\n truncated INTEGER NOT NULL,\n spans TEXT NOT NULL,\n service TEXT,\n action TEXT,\n message TEXT\n );\n CREATE INDEX IF NOT EXISTS traces_start ON traces (start_ms);\n CREATE INDEX IF NOT EXISTS traces_endpoint ON traces (endpoint, start_ms);\n -- Earlier versions kept failures here; nothing reads them now.\n DROP TABLE IF EXISTS failures;\n `);\n this.#addMissingColumns();\n this.prune();\n this.#pruneTimer = setInterval(() => this.prune(), PRUNE_MS);\n this.#pruneTimer.unref?.();\n }\n\n /** A folder from an earlier version has the table without the newer columns. */\n #addMissingColumns(): void {\n const present = new Set(\n this.#database\n .prepare(\"PRAGMA table_info(traces)\")\n .all()\n .map((column) => String(column.name)),\n );\n for (const column of [\"service\", \"action\", \"message\"]) {\n if (!present.has(column)) {\n this.#database.exec(`ALTER TABLE traces ADD COLUMN ${column} TEXT`);\n }\n }\n }\n\n /** Queue a finished request. A later save of the same request replaces it. */\n saveTrace(trace: TraceSummary): void {\n if (this.#closed) return;\n this.#pendingTraces.set(trace.traceId, trace);\n this.#scheduleFlush();\n }\n\n #scheduleFlush(): void {\n if (this.#flushTimer) return;\n this.#flushTimer = setTimeout(() => this.flush(), FLUSH_MS);\n this.#flushTimer.unref?.();\n }\n\n /** Write queued requests now. */\n flush(): void {\n if (this.#flushTimer) {\n clearTimeout(this.#flushTimer);\n this.#flushTimer = undefined;\n }\n if (this.#closed || this.#pendingTraces.size === 0) return;\n const traces = [...this.#pendingTraces.values()];\n this.#pendingTraces.clear();\n try {\n this.#database.exec(\"BEGIN\");\n const saveTrace = this.#database.prepare(\n `INSERT OR REPLACE INTO traces (trace_id, name, endpoint, method, route, path,\n http_status, generation, start_ms, end_ms, duration_ms, status, truncated, spans,\n service, action, message)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n );\n for (const trace of traces) {\n saveTrace.run(\n trace.traceId,\n trace.name,\n trace.method && trace.route\n ? `${trace.method} ${trace.route}`\n : trace.name,\n trace.method ?? null,\n trace.route ?? null,\n trace.path ?? null,\n trace.httpStatus ?? null,\n trace.generation,\n trace.startMs,\n trace.endMs ?? null,\n trace.durationMs ?? null,\n trace.status,\n trace.truncated ? 1 : 0,\n JSON.stringify(trace.spans),\n trace.service ?? null,\n trace.action ?? null,\n trace.message ?? null,\n );\n }\n this.#database.exec(\"COMMIT\");\n } catch {\n // A failed write loses a batch of history; it must not break the app.\n try {\n this.#database.exec(\"ROLLBACK\");\n } catch {\n // Nothing was open.\n }\n }\n }\n\n /** Drop what is past retention, then the oldest beyond the size cap. */\n prune(now = Date.now()): void {\n if (this.#closed) return;\n try {\n const cutoff = now - this.days * DAY_MS;\n this.#database\n .prepare(\"DELETE FROM traces WHERE start_ms < ?\")\n .run(cutoff);\n const count = Number(\n this.#database.prepare(\"SELECT COUNT(*) AS n FROM traces\").get()?.n ??\n 0,\n );\n if (count > MAX_TRACES) {\n this.#database\n .prepare(\n \"DELETE FROM traces WHERE trace_id IN (SELECT trace_id FROM traces ORDER BY start_ms ASC LIMIT ?)\",\n )\n .run(count - MAX_TRACES);\n }\n } catch {\n // Pruning is housekeeping; try again next time.\n }\n }\n\n info(): HistoryInfo {\n this.flush();\n const row = this.#database\n .prepare(\"SELECT COUNT(*) AS n, MIN(start_ms) AS oldest FROM traces\")\n .get();\n return {\n days: this.days,\n count: Number(row?.n ?? 0),\n oldestMs: number(row?.oldest),\n };\n }\n\n /** Matching requests, without spans, and how many match in total. */\n traces(query: HistoryQuery): { total: number; traces: HistoryTrace[] } {\n this.flush();\n const { sql, params } = filterSql(query);\n const total = Number(\n this.#database\n .prepare(`SELECT COUNT(*) AS n FROM traces WHERE ${sql}`)\n .get(...params)?.n ?? 0,\n );\n const limit = Math.min(\n Math.max(query.limit ?? DEFAULT_LIMIT, 1),\n MAX_LIMIT,\n );\n const offset = Math.max(query.offset ?? 0, 0);\n const order =\n query.sort === \"slowest\"\n ? \"duration_ms DESC, start_ms DESC\"\n : \"start_ms DESC\";\n const rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${order} LIMIT ? OFFSET ?`,\n )\n .all(...params, limit, offset);\n return { total, traces: rows.map(toHistoryTrace) };\n }\n\n /** Counts for each filter over the range, ignoring that filter's own choice. */\n facets(query: HistoryQuery): HistoryFacets {\n this.flush();\n const count = (facet: Facet): FacetValue[] => {\n const { sql, params } = filterSql(query, facet);\n const column = FACET_COLUMNS[facet];\n return this.#database\n .prepare(\n `SELECT ${column} AS value, COUNT(*) AS n FROM traces\n WHERE ${sql} AND ${column} IS NOT NULL\n GROUP BY value ORDER BY n DESC, value ASC LIMIT ?`,\n )\n .all(...params, MAX_FACET_VALUES)\n .map((row) => ({ value: String(row.value), count: Number(row.n) }));\n };\n return {\n outcome: count(\"outcome\"),\n method: count(\"method\"),\n service: count(\"service\"),\n endpoint: count(\"endpoint\"),\n };\n }\n\n /** Matching requests per time bucket across the range, by outcome. */\n volume(query: HistoryQuery, buckets = VOLUME_BUCKETS): VolumeBucket[] {\n this.flush();\n const { sql, params } = filterSql(query);\n const bucketMs = Math.max(Math.ceil((query.to - query.from) / buckets), 1);\n const result: VolumeBucket[] = Array.from(\n { length: buckets },\n (_, index) => ({\n start: query.from + index * bucketMs,\n ok: 0,\n client: 0,\n server: 0,\n }),\n );\n const rows = this.#database\n .prepare(\n `SELECT CAST((start_ms - ?) / ? AS INTEGER) AS bucket, ${OUTCOME_CASE} AS outcome,\n COUNT(*) AS n\n FROM traces WHERE ${sql} GROUP BY bucket, outcome`,\n )\n .all(query.from, bucketMs, ...params);\n for (const row of rows) {\n const bucket =\n result[Math.min(Math.max(Number(row.bucket), 0), buckets - 1)];\n const outcome = String(row.outcome) as Outcome;\n if (bucket) bucket[outcome] += Number(row.n);\n }\n return result;\n }\n\n /** Every matching request, newest first, as CSV for a spreadsheet. */\n exportCsv(query: HistoryQuery): string {\n this.flush();\n const { sql, params } = filterSql(query);\n const order =\n query.sort === \"slowest\"\n ? \"duration_ms DESC, start_ms DESC\"\n : \"start_ms DESC\";\n const rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${order} LIMIT ?`,\n )\n .all(...params, MAX_EXPORT_ROWS);\n return tracesToCsv(rows.map(toHistoryTrace));\n }\n\n /** One request with all its spans. */\n trace(traceId: string): TraceSummary | undefined {\n this.flush();\n const row = this.#database\n .prepare(`SELECT ${LIST_COLUMNS}, spans FROM traces WHERE trace_id = ?`)\n .get(traceId);\n if (!row) return undefined;\n const { endpoint: _endpoint, ...trace } = toHistoryTrace(row);\n return { ...trace, spans: JSON.parse(String(row.spans)) };\n }\n\n /** How many requests match, how many failed, and how long they took. */\n summary(query: HistoryQuery): HistorySummary {\n this.flush();\n const { sql, params } = filterSql(query);\n let total = 0;\n let clientErrors = 0;\n let serverErrors = 0;\n const counts = this.#database\n .prepare(\n `SELECT ${OUTCOME_CASE} AS outcome, COUNT(*) AS n\n FROM traces WHERE ${sql} GROUP BY outcome`,\n )\n .all(...params);\n for (const row of counts) {\n const n = Number(row.n);\n total += n;\n if (row.outcome === \"client\") clientErrors = n;\n if (row.outcome === \"server\") serverErrors = n;\n }\n const durations = this.#database\n .prepare(\n `SELECT duration_ms FROM traces\n WHERE ${sql} AND duration_ms IS NOT NULL ORDER BY duration_ms`,\n )\n .all(...params)\n .map((row) => Number(row.duration_ms));\n return {\n total,\n clientErrors,\n serverErrors,\n medianMs: percentile(durations, 0.5),\n p95Ms: percentile(durations, 0.95),\n };\n }\n\n /** Write what is queued and release the database. */\n close(): void {\n if (this.#closed) return;\n this.flush();\n this.#closed = true;\n clearInterval(this.#pruneTimer);\n try {\n this.#database.close();\n } catch {\n // Already closed.\n }\n }\n}\n\n/** Query-string values the dashboard sends, parsed defensively. */\nexport function parseHistoryQuery(\n params: URLSearchParams,\n now = Date.now(),\n): HistoryQuery {\n const integer = (name: string): number | undefined => {\n const raw = params.get(name);\n if (raw === null || raw.trim() === \"\") return undefined;\n const value = Number(raw);\n return Number.isFinite(value) ? value : undefined;\n };\n const all = (name: string): string[] | undefined => {\n const values = params.getAll(name).filter((value) => value !== \"\");\n return values.length > 0 ? values : undefined;\n };\n const to = integer(\"to\") ?? now;\n return {\n to,\n from: integer(\"from\") ?? to - 7 * DAY_MS,\n endpoints: all(\"endpoint\"),\n methods: all(\"method\"),\n services: all(\"service\"),\n outcomes: all(\"outcome\")?.filter((value): value is Outcome =>\n OUTCOMES.has(value),\n ),\n minMs: integer(\"minMs\"),\n query: params.get(\"q\") || undefined,\n sort: params.get(\"sort\") === \"slowest\" ? \"slowest\" : \"recent\",\n limit: integer(\"limit\"),\n offset: integer(\"offset\"),\n };\n}\n","/**\n * The page the dashboard serves at `/`. The React app and its styles load from\n * `/assets/`; the inline script applies the saved theme before first paint. The\n * import map hands the project's own modules (its docs components and its\n * dashboard extension), bundled apart from the dashboard, the dashboard's copy\n * of React and its UI kit, so there is one of each on the page.\n *\n * `extension` describes the project's extension: `revision` changes with every\n * rebuild (the page reloads when it does), `js` and `css` say what it built.\n * `theme` is whether `/assets/brick-theme.css` has token values to apply.\n */\nexport function dashboardShell(\n options: {\n extension?: { revision: number; js: boolean; css: boolean };\n theme?: boolean;\n } = {},\n): string {\n const { extension, theme } = options;\n const version = extension ? `?v=${extension.revision}` : \"\";\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Brick dev</title>\n<link rel=\"icon\" href=\"data:,\">\n<script>\n(function () {\n try {\n var theme = localStorage.getItem(\"brick-dashboard-theme\");\n var dark = theme === \"dark\" || (theme !== \"light\" && window.matchMedia(\"(prefers-color-scheme: dark)\").matches);\n if (dark) document.documentElement.classList.add(\"dark\");\n } catch (error) {}\n})();\n</script>\n<link rel=\"stylesheet\" href=\"/assets/app.css\">\n${extension?.css ? `<link rel=\"stylesheet\" href=\"/assets/extension.css${version}\">\\n` : \"\"}${theme ? `<link rel=\"stylesheet\" href=\"/assets/brick-theme.css\" data-brick-theme>\\n` : \"\"}${extension ? `<meta name=\"brick-extension\" data-revision=\"${extension.revision}\"${extension.js ? ` data-src=\"/assets/extension.js${version}\"` : \"\"}>\\n` : \"\"}<script type=\"importmap\">\n{\"imports\":{\"react\":\"/assets/react.js\",\"react/jsx-runtime\":\"/assets/react-jsx-runtime.js\",\"react/jsx-dev-runtime\":\"/assets/react-jsx-runtime.js\",\"react-dom\":\"/assets/react-dom.js\",\"react-dom/client\":\"/assets/react-dom-client.js\",\"@brickkit/cli/dashboard\":\"/assets/kit.js\"}}\n</script>\n</head>\n<body>\n<div id=\"root\"></div>\n<script type=\"module\" src=\"/assets/app.js\"></script>\n</body>\n</html>\n`;\n}\n","import { createHash, timingSafeEqual } from \"node:crypto\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { DashboardAuth } from \"@brickkit/core\";\n\n/** What to do with a request: let it through, or answer it with this. */\nexport type Access =\n | { allowed: true }\n | {\n allowed: false;\n status: number;\n headers: Record<string, string | string[]>;\n body: string | Uint8Array;\n };\n\n/** How long the app's `authorize` may take before the request is refused. */\nexport const AUTHORIZE_TIMEOUT_MS = 5000;\n\n/** Whether `host` can only be reached from the machine it runs on. */\nexport function isLoopbackHost(host: string): boolean {\n const name = host.toLowerCase();\n return (\n name === \"localhost\" ||\n name === \"::1\" ||\n name === \"[::1]\" ||\n /^127(\\.\\d{1,3}){3}$/.test(name)\n );\n}\n\nconst NOT_COPIED = new Set([\n \"set-cookie\",\n \"content-length\",\n \"content-encoding\",\n \"transfer-encoding\",\n \"connection\",\n \"keep-alive\",\n]);\n\nconst digest = (value: string) => createHash(\"sha256\").update(value).digest();\n\n/** Whether `candidate` is one of `tokens`, in the same time whichever it is. */\nfunction isToken(candidate: string | undefined, tokens: readonly string[]) {\n if (candidate === undefined) return false;\n const given = digest(candidate);\n let match = false;\n // Every token is compared, so the time does not say which one was close.\n for (const token of tokens)\n if (timingSafeEqual(given, digest(token))) match = true;\n return match;\n}\n\n/** The secret in an `Authorization` header: a Bearer token, or a Basic password. */\nfunction credential(request: IncomingMessage): string | undefined {\n const header = request.headers.authorization;\n if (!header) return undefined;\n const space = header.indexOf(\" \");\n if (space < 0) return undefined;\n const scheme = header.slice(0, space).toLowerCase();\n const value = header.slice(space + 1).trim();\n if (scheme === \"bearer\") return value;\n if (scheme === \"basic\") {\n const decoded = Buffer.from(value, \"base64\").toString(\"utf8\");\n const colon = decoded.indexOf(\":\");\n return colon < 0 ? undefined : decoded.slice(colon + 1);\n }\n return undefined;\n}\n\n/** The request as the app's `authorize` sees it: standard, with no body. */\nfunction webRequest(request: IncomingMessage): Request {\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (value === undefined) continue;\n try {\n headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n } catch {\n // A header the platform will not take cannot matter to a check.\n }\n }\n const forwarded = request.headers[\"x-forwarded-proto\"];\n const protocol =\n (Array.isArray(forwarded) ? forwarded[0] : forwarded)\n ?.split(\",\")[0]\n ?.trim() === \"https\"\n ? \"https\"\n : \"http\";\n const host = request.headers.host ?? \"localhost\";\n let url: string;\n try {\n url = new URL(request.url ?? \"/\", `${protocol}://${host}`).href;\n } catch {\n url = `${protocol}://localhost${request.url ?? \"/\"}`;\n }\n return new Request(url, { method: request.method ?? \"GET\", headers });\n}\n\nconst refusal = (\n status: number,\n body: string,\n headers: Record<string, string> = {},\n): Access => ({\n allowed: false,\n status,\n body,\n headers: { \"content-type\": \"text/plain; charset=utf-8\", ...headers },\n});\n\n/**\n * The check for the dashboard's requests. A request passes with a valid token,\n * or when the app's `authorize` returns `true`. Anything else is answered:\n * what `authorize` returned if it returned a `Response`, else 401 (with a\n * browser sign-in prompt when tokens are in use), and 503 when `authorize`\n * threw or ran out of time, since a check that cannot answer must not let\n * anyone in.\n */\nexport function createAccess(\n auth: DashboardAuth,\n onError: (error: unknown) => void = () => {},\n timeoutMs = AUTHORIZE_TIMEOUT_MS,\n): (request: IncomingMessage) => Promise<Access> {\n const tokens =\n auth.token === undefined\n ? []\n : typeof auth.token === \"string\"\n ? [auth.token]\n : [...auth.token];\n const prompt: Record<string, string> =\n tokens.length > 0\n ? { \"www-authenticate\": 'Basic realm=\"Brick dashboard\", charset=\"UTF-8\"' }\n : {};\n return async (request) => {\n if (tokens.length > 0 && isToken(credential(request), tokens))\n return { allowed: true };\n if (!auth.authorize) return refusal(401, \"Unauthorized\", prompt);\n\n let decision: boolean | Response;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n decision = await Promise.race([\n Promise.resolve(auth.authorize(webRequest(request))),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(\"dashboard authorize timed out\")),\n timeoutMs,\n );\n }),\n ]);\n } catch (error) {\n onError(error);\n return refusal(503, \"Sign-in is unavailable.\");\n } finally {\n clearTimeout(timer);\n }\n if (decision === true) return { allowed: true };\n if (decision instanceof Response) {\n const headers: Record<string, string | string[]> = {};\n decision.headers.forEach((value, name) => {\n // The body is sent as bytes with its own length; these describe the\n // connection or an encoding already undone.\n if (!NOT_COPIED.has(name)) headers[name] = value;\n });\n const cookies = decision.headers.getSetCookie();\n if (cookies.length > 0) headers[\"set-cookie\"] = cookies;\n return {\n allowed: false,\n status: decision.status,\n headers,\n body: new Uint8Array(await decision.arrayBuffer()),\n };\n }\n return refusal(401, \"Unauthorized\", prompt);\n };\n}\n","import { watch, type FSWatcher } from \"node:fs\";\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport {\n basename,\n dirname,\n extname,\n join,\n posix,\n relative,\n resolve,\n sep,\n} from \"node:path\";\nimport type { DocumentationOptions } from \"@brickkit/core\";\nimport type { DevTelemetryStore, DocsSnapshot } from \"./dev-telemetry-store\";\n\n/*\n * Developer documentation for the dashboard's Docs tab. The folder follows\n * Fumadocs' layout (frontmatter, meta.json, folder groups), and fumadocs-core\n * builds the page tree and search. MDX is compiled here and run in the browser\n * with the dashboard's components plus the project's own.\n *\n * fumadocs-core and @mdx-js/mdx are optional peers, loaded only when an app\n * sets `documentation`, so projects without docs do not install them.\n */\n\n/** One entry of the docs sidebar. */\nexport type DocsNode =\n | { type: \"page\"; name: string; url: string; description?: string }\n | {\n type: \"folder\";\n name: string;\n index?: { name: string; url: string };\n children: DocsNode[];\n defaultOpen?: boolean;\n }\n | { type: \"separator\"; name?: string };\n\nexport interface DocsTree {\n name: string;\n children: DocsNode[];\n}\n\nexport interface DocsHeading {\n title: string;\n url: string;\n depth: number;\n}\n\n/** A page ready to run in the browser. */\nexport interface DocsPage {\n title: string;\n description?: string;\n /** The file, relative to the docs folder. */\n path: string;\n slugs: string[];\n toc: DocsHeading[];\n /** MDX compiled to a function body; see `runMdx` in the dashboard. */\n code: string;\n /** Set instead of `code` when the page does not compile. */\n error?: string;\n}\n\nexport interface DocsSearchHit {\n id: string;\n type: \"page\" | \"heading\" | \"text\";\n content: string;\n /** Route within the docs, with a `#heading` when the hit is inside a page. */\n url: string;\n}\n\nexport interface DocsInfo {\n tree: DocsTree;\n /** Whether the project supplied components of its own. */\n components: boolean;\n revision: number;\n}\n\nexport type OpenedDocs =\n | { status: \"ready\"; docs: DevDocs }\n | { status: \"missing\"; packages: string[] }\n | { status: \"error\"; message: string };\n\nconst PACKAGES = [\"fumadocs-core\", \"@mdx-js/mdx\"] as const;\nconst PAGE_EXTENSIONS = new Set([\".md\", \".mdx\"]);\nconst IMAGE_TYPES: Record<string, string> = {\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n};\nconst REFRESH_DELAY_MS = 100;\n\ninterface Fumadocs {\n loader: typeof import(\"fumadocs-core/source\").loader;\n frontmatter: typeof import(\"fumadocs-core/content/md/frontmatter\").frontmatter;\n plugins: typeof import(\"fumadocs-core/mdx-plugins\");\n createSearchAPI: typeof import(\"fumadocs-core/search/server\").createSearchAPI;\n compile: typeof import(\"@mdx-js/mdx\").compile;\n}\n\nasync function loadFumadocs(): Promise<Fumadocs | string[]> {\n try {\n const [source, matter, plugins, search, mdx] = await Promise.all([\n import(\"fumadocs-core/source\"),\n import(\"fumadocs-core/content/md/frontmatter\"),\n import(\"fumadocs-core/mdx-plugins\"),\n import(\"fumadocs-core/search/server\"),\n import(\"@mdx-js/mdx\"),\n ]);\n return {\n loader: source.loader,\n frontmatter: matter.frontmatter,\n plugins,\n createSearchAPI: search.createSearchAPI,\n compile: mdx.compile,\n };\n } catch (error) {\n // Only a missing package is the project's to fix; anything else is a bug.\n if (\n (error as { code?: string }).code === \"ERR_MODULE_NOT_FOUND\" ||\n /Cannot find (module|package)/.test(String((error as Error)?.message))\n )\n return [...PACKAGES];\n throw error;\n }\n}\n\ninterface PageFile {\n /** Relative to the docs folder, with forward slashes. */\n path: string;\n absolute: string;\n title: string;\n description?: string;\n /** The file's text after the frontmatter. */\n content: string;\n data: Record<string, unknown>;\n}\n\ninterface MetaFile {\n path: string;\n data: Record<string, unknown>;\n}\n\nconst humanize = (name: string): string => {\n const spaced = name.replace(/[-_]+/g, \" \").trim();\n return spaced.charAt(0).toUpperCase() + spaced.slice(1);\n};\n\nconst H1 = /^#\\s+(.+?)\\s*#*\\s*$/;\n\n/**\n * The first `# Heading` outside code fences: its text, and the content without\n * it. The page shows its title above the content, so a heading that only\n * repeats the title would appear twice.\n */\nfunction firstHeading(\n content: string,\n): { text: string; rest: string; leading: boolean } | undefined {\n const lines = content.split(\"\\n\");\n let fenced = false;\n let seenText = false;\n for (const [index, line] of lines.entries()) {\n if (/^\\s*(```|~~~)/.test(line)) {\n fenced = !fenced;\n seenText = true;\n } else if (!fenced) {\n const match = H1.exec(line);\n if (match) {\n const rest = [...lines.slice(0, index), ...lines.slice(index + 1)];\n // Drop the blank line that followed it as well.\n if (rest[index]?.trim() === \"\") rest.splice(index, 1);\n return { text: match[1]!, rest: rest.join(\"\\n\"), leading: !seenText };\n }\n if (line.trim() !== \"\") seenText = true;\n }\n }\n return undefined;\n}\n\nasync function scan(\n root: string,\n fumadocs: Fumadocs,\n warn: (message: string) => void,\n): Promise<{ pages: PageFile[]; metas: MetaFile[] }> {\n const pages: PageFile[] = [];\n const metas: MetaFile[] = [];\n async function visit(directory: string): Promise<void> {\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n const absolute = join(directory, entry.name);\n const path = relative(root, absolute).split(sep).join(\"/\");\n if (entry.isDirectory()) {\n await visit(absolute);\n } else if (entry.name === \"meta.json\") {\n try {\n const data = JSON.parse(await readFile(absolute, \"utf8\"));\n if (data && typeof data === \"object\") metas.push({ path, data });\n } catch (error) {\n warn(`[Brick-TS] Skipping docs ${path}: ${errorMessage(error)}`);\n }\n } else if (PAGE_EXTENSIONS.has(extname(entry.name))) {\n const text = await readFile(absolute, \"utf8\");\n let data: Record<string, unknown> = {};\n let content = text;\n try {\n const parsed = fumadocs.frontmatter(text);\n data = parsed.data as Record<string, unknown>;\n content = parsed.content;\n } catch (error) {\n warn(\n `[Brick-TS] Ignoring the frontmatter of docs ${path}: ${errorMessage(error)}`,\n );\n }\n const name = basename(entry.name, extname(entry.name));\n const heading = firstHeading(content);\n const given =\n typeof data.title === \"string\" && data.title ? data.title : undefined;\n const title =\n given ??\n heading?.text ??\n humanize(name === \"index\" ? basename(dirname(path)) || \"Home\" : name);\n // A title taken from the heading, or a leading heading that repeats the\n // frontmatter title, is shown once, above the content.\n if (heading && (!given || (heading.leading && heading.text === given)))\n content = heading.rest;\n pages.push({\n path,\n absolute,\n title,\n description:\n typeof data.description === \"string\" ? data.description : undefined,\n content,\n data,\n });\n }\n }\n }\n await visit(root);\n return { pages, metas };\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype MdastNode = {\n type: string;\n url?: string;\n name?: string | null;\n attributes?: { type: string; name?: string; value?: unknown }[];\n children?: MdastNode[];\n};\n\nfunction walk(node: MdastNode, visit: (node: MdastNode) => void): void {\n visit(node);\n for (const child of node.children ?? []) walk(child, visit);\n}\n\n/** Ways a link inside a page can point at another page or a local image. */\nfunction resolveInside(from: string, href: string): string | undefined {\n if (/^[a-z][a-z\\d+.-]*:/i.test(href) || href.startsWith(\"#\"))\n return undefined;\n if (href.startsWith(\"/\")) return undefined;\n const [target] = href.split(/[?#]/);\n if (!target) return undefined;\n const resolved = posix.normalize(posix.join(posix.dirname(from), target));\n return resolved.startsWith(\"../\") ? undefined : resolved;\n}\n\n/**\n * The page tree and compiled pages of one docs folder. It watches the folder,\n * so edits show in the dashboard as they are saved.\n */\nexport class DevDocs {\n readonly #root: string;\n readonly #documentation: DocumentationOptions;\n /** Relative paths in `documentation` start here: the app entry's folder. */\n readonly #base: string;\n readonly #fumadocs: Fumadocs;\n readonly #warn: (message: string) => void;\n readonly #listeners = new Set<() => void>();\n readonly #watchers: FSWatcher[] = [];\n #loader: Source | undefined;\n #pages = new Map<string, PageFile>();\n #byPath = new Map<string, string>();\n #compiled = new Map<string, DocsPage>();\n #search:\n | Promise<{ search(query: string): Promise<DocsSearchHit[]> }>\n | undefined;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #refreshing: Promise<void> = Promise.resolve();\n #closed = false;\n #title = \"Docs\";\n revision = 0;\n\n constructor(\n base: string,\n documentation: DocumentationOptions,\n fumadocs: Fumadocs,\n warn: (message: string) => void,\n ) {\n this.#base = base;\n this.#documentation = documentation;\n this.#root = resolve(base, documentation.dir);\n this.#fumadocs = fumadocs;\n this.#warn = warn;\n }\n\n /** Read the folder again and tell listeners. */\n async refresh(): Promise<void> {\n // Refreshes run one at a time, so a slow scan cannot overwrite a newer one.\n this.#refreshing = this.#refreshing.then(() => this.#scan());\n await this.#refreshing;\n }\n\n async #scan(): Promise<void> {\n const { pages, metas } = await scan(this.#root, this.#fumadocs, this.#warn);\n if (this.#closed) return;\n const source = this.#fumadocs.loader({\n baseUrl: \"/\",\n source: {\n files: [\n ...pages.map((page) => ({\n type: \"page\" as const,\n path: page.path,\n data: {\n ...page.data,\n title: page.title,\n description: page.description,\n },\n })),\n ...metas.map((meta) => ({\n type: \"meta\" as const,\n path: meta.path,\n data: meta.data,\n })),\n ],\n },\n });\n this.#loader = source as unknown as Source;\n this.#pages = new Map();\n this.#byPath = new Map();\n for (const page of this.#loader.getPages()) {\n const slug = page.slugs.join(\"/\");\n const file = pages.find((candidate) => candidate.path === page.path);\n if (!file) continue;\n this.#pages.set(slug, file);\n this.#byPath.set(file.path, slug);\n }\n this.#compiled.clear();\n this.#search = undefined;\n const tree = this.#loader.getPageTree();\n this.#title = typeof tree.name === \"string\" ? tree.name : \"Docs\";\n this.revision++;\n for (const listener of this.#listeners) listener();\n }\n\n /** Start watching the folder, and the project's components module. */\n watch(): void {\n const changed = () => {\n clearTimeout(this.#timer);\n this.#timer = setTimeout(() => {\n void this.refresh().catch((error) =>\n this.#warn(`[Brick-TS] Docs: ${errorMessage(error)}`),\n );\n }, REFRESH_DELAY_MS);\n };\n const folders = [this.#root];\n if (this.#documentation.components)\n folders.push(dirname(this.#componentsPath()!));\n for (const [index, folder] of folders.entries()) {\n try {\n // Recursive for the docs; the components module's folder is the\n // project's own source, where only its direct files matter.\n this.#watchers.push(\n watch(folder, { recursive: index === 0 }, () => changed()),\n );\n } catch {\n try {\n this.#watchers.push(watch(folder, () => changed()));\n } catch {\n // A folder that cannot be watched still works; it just needs a reload.\n }\n }\n }\n }\n\n onChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n snapshot(): DocsSnapshot {\n return {\n revision: this.revision,\n status: \"ready\",\n title: this.#title,\n components: Boolean(this.#documentation.components),\n };\n }\n\n info(): DocsInfo {\n return {\n tree: simplify(this.#loader?.getPageTree()),\n components: Boolean(this.#documentation.components),\n revision: this.revision,\n };\n }\n\n /** Compile one page; undefined when there is no such page. */\n async page(slugs: string[]): Promise<DocsPage | undefined> {\n const key = slugs.join(\"/\");\n const file = this.#pages.get(key);\n if (!file) return undefined;\n const cached = this.#compiled.get(key);\n if (cached) return cached;\n const page = await this.#compile(file, slugs);\n // A refresh while compiling clears the cache; do not put stale output back.\n if (this.#pages.get(key) === file) this.#compiled.set(key, page);\n return page;\n }\n\n async #compile(file: PageFile, slugs: string[]): Promise<DocsPage> {\n const { plugins, compile } = this.#fumadocs;\n const base = {\n title: file.title,\n description: file.description,\n path: file.path,\n slugs,\n };\n try {\n const result = await compile(\n { path: file.absolute, value: file.content },\n {\n outputFormat: \"function-body\",\n development: false,\n remarkPlugins: [\n plugins.remarkGfm,\n plugins.remarkHeading,\n plugins.remarkCodeTab,\n plugins.remarkNpm,\n plugins.remarkAdmonition,\n () => (tree: MdastNode) => this.#rewriteLinks(tree, file.path),\n ],\n rehypePlugins: [plugins.rehypeCode],\n },\n );\n const toc = (result.data.toc ?? []) as {\n title: unknown;\n url: string;\n depth: number;\n }[];\n return {\n ...base,\n toc: toc.map((item) => ({\n title: plainText(item.title),\n url: item.url,\n depth: item.depth,\n })),\n code: String(result),\n };\n } catch (error) {\n return { ...base, toc: [], code: \"\", error: errorMessage(error) };\n }\n }\n\n /**\n * Links to other pages become dashboard routes, and local images are served\n * from the docs folder, so a folder reads the same here as on a docs site.\n * This covers markdown links and the `href` of components such as `<Card>`.\n */\n #rewriteLinks(tree: MdastNode, from: string): void {\n const file = (resolved: string) =>\n `/api/docs/files/${resolved.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n walk(tree, (node) => {\n if (node.type === \"link\" && node.url !== undefined) {\n node.url = this.#route(from, node.url) ?? node.url;\n } else if (node.type === \"image\" && node.url !== undefined) {\n const resolved = resolveInside(from, node.url);\n if (resolved !== undefined) node.url = file(resolved);\n } else if (\n node.type === \"mdxJsxFlowElement\" ||\n node.type === \"mdxJsxTextElement\"\n ) {\n for (const attribute of node.attributes ?? []) {\n if (attribute.type !== \"mdxJsxAttribute\") continue;\n if (typeof attribute.value !== \"string\") continue;\n if (attribute.name === \"href\")\n attribute.value =\n this.#route(from, attribute.value) ?? attribute.value;\n else if (attribute.name === \"src\" && node.name === \"img\") {\n const resolved = resolveInside(from, attribute.value);\n if (resolved !== undefined) attribute.value = file(resolved);\n }\n }\n }\n });\n }\n\n /**\n * The dashboard route for a link to a page of these docs, or undefined for\n * anything else (other sites, in-page anchors, files). A link to a page that\n * does not exist still becomes a route, so it says \"No such page\" here\n * instead of leaving the dashboard.\n */\n #route(from: string, href: string): string | undefined {\n const hashAt = href.indexOf(\"#\");\n const hash = hashAt >= 0 ? href.slice(hashAt) : \"\";\n const target =\n (hashAt >= 0 ? href.slice(0, hashAt) : href).split(\"?\")[0] ?? \"\";\n const route = (slug: string) => `#/docs${slug ? `/${slug}` : \"\"}${hash}`;\n if (/^[a-z][a-z\\d+.-]*:/i.test(href) || href.startsWith(\"#\") || !target)\n return undefined;\n if (target.startsWith(\"/\")) {\n // A docs site links by address (/guide/setup); so can these pages.\n const slug = target.replace(/^\\/+|\\/+$/g, \"\");\n return this.#pages.has(slug) ? route(slug) : undefined;\n }\n const resolved = resolveInside(from, target);\n if (resolved === undefined) return undefined;\n const known = this.#byPath.get(resolved);\n if (known !== undefined) return route(known);\n if (!PAGE_EXTENSIONS.has(extname(resolved))) return undefined;\n const guess = resolved\n .slice(0, -extname(resolved).length)\n .replace(/(^|\\/)index$/, \"\");\n return route(guess);\n }\n\n async search(query: string): Promise<DocsSearchHit[]> {\n if (!query.trim()) return [];\n this.#search ??= this.#buildSearch();\n return (await this.#search).search(query);\n }\n\n async #buildSearch() {\n const { plugins, createSearchAPI } = this.#fumadocs;\n const indexes = [...this.#pages.entries()].map(([slug, file]) => ({\n id: file.path,\n title: file.title,\n description: file.description,\n url: `/${slug}`,\n structuredData: plugins.structure(file.content),\n }));\n const api = createSearchAPI(\"advanced\", { indexes });\n return {\n async search(query: string) {\n return (await api.search(query)) as DocsSearchHit[];\n },\n };\n }\n\n /** A file from the docs folder that a page can show, such as an image. */\n async file(\n relativePath: string,\n ): Promise<{ body: Uint8Array; type: string } | undefined> {\n const type = IMAGE_TYPES[extname(relativePath).toLowerCase()];\n if (!type) return undefined;\n const absolute = resolve(this.#root, relativePath);\n // Stay inside the docs folder, whatever the path says.\n if (absolute !== this.#root && !absolute.startsWith(this.#root + sep))\n return undefined;\n try {\n if (!(await stat(absolute)).isFile()) return undefined;\n return { body: new Uint8Array(await readFile(absolute)), type };\n } catch {\n return undefined;\n }\n }\n\n #componentsPath(): string | undefined {\n const { components } = this.#documentation;\n return components ? resolve(this.#base, components) : undefined;\n }\n\n /** The project's components as one browser module; undefined when it has none. */\n async components(): Promise<string | undefined> {\n const entry = this.#componentsPath();\n return entry ? bundleComponents(entry) : undefined;\n }\n\n close(): void {\n this.#closed = true;\n clearTimeout(this.#timer);\n for (const watcher of this.#watchers) watcher.close();\n this.#watchers.length = 0;\n this.#listeners.clear();\n }\n}\n\n// What the dashboard supplies to the project's components and its extension\n// itself, so there is one copy of React and of the UI kit on the page. See the\n// import map in the page shell.\nconst SHARED = [\n \"react\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n \"react-dom\",\n \"react-dom/client\",\n \"@brickkit/cli/dashboard\",\n];\n\n/** Bundle a module of React components for the dashboard to import. */\nexport async function bundleComponents(entry: string): Promise<string> {\n if (typeof Bun !== \"undefined\") {\n const result = await Bun.build({\n entrypoints: [entry],\n target: \"browser\",\n format: \"esm\",\n external: SHARED,\n minify: false,\n // Report what went wrong, not only that something did.\n throw: false,\n });\n if (!result.success)\n throw new Error(result.logs.map((log) => log.message).join(\"\\n\"));\n // A CSS import adds a stylesheet output; the module is the entry point.\n const output =\n result.outputs.find((item) => item.kind === \"entry-point\") ??\n result.outputs[0]!;\n return output.text();\n }\n // Under Node the dev server's own bundler does the work. The name is not\n // written as a literal so the CLI's Bun bundle, which never gets here,\n // stays free of a Vite import.\n const bundler = \"vite\";\n const { build } = (await import(bundler)) as typeof import(\"vite\");\n const output = await build({\n configFile: false,\n logLevel: \"silent\",\n root: dirname(entry),\n oxc: { jsx: { runtime: \"automatic\" } },\n esbuild: { jsx: \"automatic\" },\n define: { \"process.env.NODE_ENV\": '\"development\"' },\n build: {\n write: false,\n minify: false,\n lib: { entry, formats: [\"es\"], fileName: \"components\" },\n rollupOptions: { external: SHARED },\n },\n } as never);\n const bundles = Array.isArray(output) ? output : [output];\n for (const bundle of bundles) {\n const chunk = (\"output\" in bundle ? bundle.output : []).find(\n (item) => item.type === \"chunk\" && item.isEntry,\n );\n if (chunk && \"code\" in chunk) return chunk.code;\n }\n throw new Error(\"Brick: the docs components module produced no output.\");\n}\n\n/** Flatten what MDX gives for a heading to text. */\nfunction plainText(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.map(plainText).join(\"\");\n if (value && typeof value === \"object\") {\n const node = value as {\n props?: { children?: unknown };\n children?: unknown;\n value?: unknown;\n };\n if (typeof node.value === \"string\") return node.value;\n return plainText(node.props?.children ?? node.children);\n }\n return \"\";\n}\n\ninterface RawNode {\n type: string;\n name?: unknown;\n url?: string;\n description?: unknown;\n index?: RawNode;\n children?: RawNode[];\n defaultOpen?: boolean;\n}\ntype RawTree = { name?: unknown; children: RawNode[] };\n\n/** What this module uses of a fumadocs-core loader. */\ninterface Source {\n getPages(): { slugs: string[]; path: string }[];\n getPageTree(): RawTree;\n}\n\n/** The page tree as plain data for the dashboard; icons and links are left out. */\nfunction simplify(tree: RawTree | undefined): DocsTree {\n const text = (value: unknown): string =>\n typeof value === \"string\" ? value : plainText(value);\n const convert = (node: RawNode): DocsNode | undefined => {\n if (node.type === \"page\" && node.url !== undefined)\n return {\n type: \"page\",\n name: text(node.name),\n url: node.url,\n ...(typeof node.description === \"string\"\n ? { description: node.description }\n : {}),\n };\n if (node.type === \"separator\")\n return {\n type: \"separator\",\n ...(node.name ? { name: text(node.name) } : {}),\n };\n if (node.type === \"folder\")\n return {\n type: \"folder\",\n name: text(node.name),\n ...(node.index?.url !== undefined\n ? { index: { name: text(node.index.name), url: node.index.url } }\n : {}),\n children: (node.children ?? []).flatMap(\n (child) => convert(child) ?? [],\n ),\n ...(node.defaultOpen ? { defaultOpen: true } : {}),\n };\n return undefined;\n };\n return {\n name: text(tree?.name) || \"Docs\",\n children: (tree?.children ?? []).flatMap((child) => convert(child) ?? []),\n };\n}\n\n/** Open a docs folder; says what is missing when it cannot be shown. */\nexport async function openDocs(options: {\n /** Where relative paths in `documentation` start: the app entry's folder. */\n base: string;\n documentation: DocumentationOptions;\n warn: (message: string) => void;\n}): Promise<OpenedDocs> {\n const fumadocs = await loadFumadocs();\n if (Array.isArray(fumadocs)) return { status: \"missing\", packages: fumadocs };\n const docs = new DevDocs(\n options.base,\n options.documentation,\n fumadocs,\n options.warn,\n );\n try {\n await docs.refresh();\n } catch (error) {\n docs.close();\n const root = resolve(options.base, options.documentation.dir);\n return {\n status: \"error\",\n message:\n (error as { code?: string }).code === \"ENOENT\"\n ? `The docs folder ${root} does not exist.`\n : errorMessage(error),\n };\n }\n docs.watch();\n return { status: \"ready\", docs };\n}\n\n/**\n * The docs of whichever app is running: opened when the app says where they\n * are, replaced when that changes, and closed when it stops asking for them.\n */\nexport class DocsHost {\n readonly #store: DevTelemetryStore;\n readonly #warn: (message: string) => void;\n #docs: DevDocs | undefined;\n #stopListening: (() => void) | undefined;\n #key: string | undefined;\n #pending: Promise<void> = Promise.resolve();\n\n constructor(store: DevTelemetryStore, warn: (message: string) => void) {\n this.#store = store;\n this.#warn = warn;\n }\n\n get current(): DevDocs | undefined {\n return this.#docs;\n }\n\n /**\n * Follow the app's `documentation`. Relative paths in it start at `base`, the\n * folder of the app entry, as they read in the file that sets them.\n */\n configure(\n base: string,\n documentation: DocumentationOptions | undefined,\n ): Promise<void> {\n this.#pending = this.#pending.then(() =>\n this.#configure(base, documentation),\n );\n return this.#pending;\n }\n\n async #configure(\n base: string,\n documentation: DocumentationOptions | undefined,\n ): Promise<void> {\n const key = JSON.stringify([base, documentation ?? null]);\n if (key === this.#key) return;\n this.#key = key;\n this.#release();\n if (!documentation) {\n this.#store.setDocs(null);\n return;\n }\n const opened = await openDocs({\n base,\n documentation,\n warn: this.#warn,\n });\n if (opened.status !== \"ready\") {\n const message =\n opened.status === \"missing\"\n ? `The docs need ${opened.packages.join(\" and \")}. Install with: bun add -d ${opened.packages.join(\" \")}`\n : opened.message;\n this.#warn(`[Brick-TS] Docs are off. ${message}`);\n this.#store.setDocs({\n revision: 1,\n status: opened.status,\n title: \"Docs\",\n components: false,\n message,\n ...(opened.status === \"missing\" ? { packages: opened.packages } : {}),\n });\n return;\n }\n this.#docs = opened.docs;\n this.#stopListening = opened.docs.onChange(() =>\n this.#store.setDocs(opened.docs.snapshot()),\n );\n this.#store.setDocs(opened.docs.snapshot());\n }\n\n #release(): void {\n this.#stopListening?.();\n this.#stopListening = undefined;\n this.#docs?.close();\n this.#docs = undefined;\n }\n\n close(): void {\n this.#key = undefined;\n this.#release();\n }\n}\n","import { existsSync, watch, type FSWatcher } from \"node:fs\";\nimport { mkdir, readdir, readFile, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { bundleComponents } from \"./dev-docs\";\n\n/*\n * The dashboard's extension: one module of the project's own, built with the\n * dashboard's React and UI kit left external (the page's import map hands it\n * the dashboard's copies), and its Tailwind classes compiled against the\n * dashboard's theme.css. Plus the theme, which needs no code at all.\n */\n\n/** Token values for the dashboard's light and dark themes, its radius and fonts. */\nexport interface DashboardTheme {\n /** Colour tokens in light mode, by name: `{ primary: \"oklch(0.55 0.2 260)\" }`. */\n light?: Record<string, string>;\n /** Colour tokens in dark mode. */\n dark?: Record<string, string>;\n /** The base corner radius, such as `\"0.5rem\"`. */\n radius?: string;\n /** CSS font stacks. The page must be able to load the font. */\n fonts?: { sans?: string; mono?: string };\n}\n\n/** What `dashboard` accepts wherever the dashboard starts or is built. */\nexport interface DashboardExtensionOptions {\n /**\n * A module whose default export is `defineDashboard({ ... })`, or the\n * `dashboard` folder `brick build` wrote it to.\n */\n extension?: string;\n theme?: DashboardTheme;\n}\n\n/** The colour tokens of `dashboard/theme.css`; a test keeps the two in step. */\nexport const THEME_TOKENS = [\n \"background\",\n \"foreground\",\n \"card\",\n \"card-foreground\",\n \"popover\",\n \"popover-foreground\",\n \"primary\",\n \"primary-foreground\",\n \"secondary\",\n \"secondary-foreground\",\n \"muted\",\n \"muted-foreground\",\n \"accent\",\n \"accent-foreground\",\n \"destructive\",\n \"destructive-foreground\",\n \"positive\",\n \"border\",\n \"input\",\n \"ring\",\n \"chart-1\",\n \"chart-2\",\n \"chart-3\",\n \"chart-4\",\n \"chart-5\",\n \"span-request\",\n \"span-action\",\n \"span-rpc\",\n \"span-sql\",\n \"span-event\",\n \"span-other\",\n] as const;\n\nconst THEME_KEYS = new Set([\"light\", \"dark\", \"radius\", \"fonts\"]);\nconst FONT_KEYS = new Set([\"sans\", \"mono\"]);\nconst TOKENS = new Set<string>(THEME_TOKENS);\n\n/** A value that cannot close the rule it sits in. */\nfunction cssValue(where: string, value: unknown): string {\n if (typeof value !== \"string\" || !value.trim() || /[;{}<>\\\\]/.test(value))\n throw new Error(\n `Brick: dashboard.theme.${where} must be a CSS value without ; { } < > or \\\\.`,\n );\n return value.trim();\n}\n\n/**\n * The stylesheet for a theme, loaded after the dashboard's own; empty when the\n * theme sets nothing. Throws on a token name theme.css does not have.\n */\nexport function themeCss(theme: DashboardTheme | undefined): string {\n if (!theme) return \"\";\n for (const key of Object.keys(theme))\n if (!THEME_KEYS.has(key))\n throw new Error(\n `Brick: dashboard.theme has no \"${key}\". It takes light, dark, radius and fonts.`,\n );\n const rules: string[] = [];\n const root: string[] = [];\n if (theme.radius !== undefined)\n root.push(`--radius: ${cssValue(\"radius\", theme.radius)};`);\n for (const [name, value] of Object.entries(theme.fonts ?? {})) {\n if (!FONT_KEYS.has(name))\n throw new Error(\n `Brick: dashboard.theme.fonts has no \"${name}\". It takes sans and mono.`,\n );\n root.push(`--font-${name}: ${cssValue(`fonts.${name}`, value)};`);\n }\n if (root.length) rules.push(`:root {\\n ${root.join(\"\\n \")}\\n}`);\n // theme.css sets light on :root and dark on .dark, both on <html>; these\n // selectors win over both, and each applies only in its own mode.\n for (const [mode, selector] of [\n [\"light\", \":root:not(.dark)\"],\n [\"dark\", \":root.dark\"],\n ] as const) {\n const tokens = theme[mode];\n if (!tokens) continue;\n const lines = Object.entries(tokens).map(([name, value]) => {\n if (!TOKENS.has(name))\n throw new Error(\n `Brick: dashboard.theme.${mode} has no token \"${name}\". Tokens: ${THEME_TOKENS.join(\", \")}.`,\n );\n return `--${name}: ${cssValue(`${mode}.${name}`, value)};`;\n });\n if (lines.length) rules.push(`${selector} {\\n ${lines.join(\"\\n \")}\\n}`);\n }\n return rules.length ? `${rules.join(\"\\n\")}\\n` : \"\";\n}\n\n/** The built React app, next to `src/` in the repo and next to `dist/` when published. */\nexport function assetsDirectory(): string | undefined {\n for (const relative of [\"../dashboard-dist/\", \"../../dashboard-dist/\"]) {\n const directory = fileURLToPath(new URL(relative, import.meta.url));\n if (existsSync(join(directory, \"app.js\"))) return directory;\n }\n return undefined;\n}\n\nexport interface BuiltExtension {\n js: string;\n /** The extension's own Tailwind classes; empty when it uses none. */\n css: string;\n /** A `brick build` folder's `extension-N.js` files, which its loader imports. */\n parts?: Record<string, string>;\n}\n\nlet warnedTailwind = false;\n\n/**\n * Tailwind for the classes in the extension's bundle, compiled against the\n * dashboard's theme.css so `bg-primary` and the rest match. Only utilities are\n * emitted: the dashboard's stylesheet already has the base styles and tokens.\n * Tailwind is an optional peer, found from the project first.\n */\nasync function extensionCss(\n entry: string,\n js: string,\n warn: (message: string) => void,\n): Promise<string> {\n let tailwind: string | undefined;\n let main: string | undefined;\n for (const from of [entry, fileURLToPath(import.meta.url)]) {\n try {\n const require = createRequire(from);\n tailwind = require.resolve(\"tailwindcss/package.json\");\n main = require.resolve(\"tailwindcss\");\n break;\n } catch {\n // Not installed there.\n }\n }\n const assets = assetsDirectory();\n const themeFile = assets\n ? join(assets, \"theme.css\")\n : fileURLToPath(new URL(\"../dashboard/theme.css\", import.meta.url));\n if (!tailwind || !main) {\n if (!warnedTailwind)\n warn(\n \"[Brick-TS] tailwindcss is not installed, so the dashboard extension's own Tailwind classes are not compiled. The UI kit is styled either way.\",\n );\n warnedTailwind = true;\n return \"\";\n }\n const root = dirname(tailwind);\n const { compile } = (await import(\n pathToFileURL(main).href\n )) as typeof import(\"tailwindcss\");\n const compiler = await compile(\n `@layer theme, base, components, utilities;\n@import \"tailwindcss/theme.css\" theme(reference inline);\n@import \"tailwindcss/utilities.css\" layer(utilities);\n@reference \"brick/theme.css\";\n`,\n {\n base: root,\n async loadStylesheet(id) {\n const path =\n id === \"brick/theme.css\"\n ? themeFile\n : join(root, id.replace(/^tailwindcss\\//, \"\"));\n return {\n path,\n base: dirname(path),\n content: await readFile(path, \"utf8\"),\n };\n },\n },\n );\n // Every word in the bundle is a candidate; Tailwind ignores what is not a class.\n const candidates = new Set(js.split(/[\\s\"'`]+/).filter(Boolean));\n const css = compiler.build([...candidates]);\n return /\\{/.test(css) ? css : \"\";\n}\n\n/** Bundle the extension and its styles for the dashboard page. */\nexport async function buildDashboardExtension(\n entry: string,\n options: { warn?: (message: string) => void } = {},\n): Promise<BuiltExtension> {\n const js = await bundleComponents(entry);\n return {\n js,\n css: await extensionCss(\n entry,\n js,\n options.warn ?? ((message) => console.warn(message)),\n ),\n };\n}\n\n/**\n * Write the app's extension and its plugins' into `outdir`, where `brick start`\n * can serve them: the app's alone as it is, or with plugins each part apart\n * and `extension.js` loading them, as `brick dev` serves them. Returns false\n * when there is none to write. A plugin's that fails to build throws.\n */\nexport async function writeDashboardExtension(\n entry: string | undefined,\n plugins: readonly PluginDashboard[],\n outdir: string,\n): Promise<boolean> {\n const parts = [\n ...(entry ? [{ name: \"app\", path: entry, plugin: false }] : []),\n ...[...pluginDashboards(plugins)].map(([path, name]) => ({\n name,\n path,\n plugin: true,\n })),\n ];\n if (!parts.length) return false;\n const built = await Promise.all(\n parts.map((part) =>\n buildDashboardExtension(part.path).catch((error: unknown) => {\n if (!part.plugin) throw error;\n throw new Error(\n `Brick compiler: the dashboard extension of plugin ${part.name} failed to build: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }),\n ),\n );\n await mkdir(outdir, { recursive: true });\n if (parts.length === 1 && entry) {\n await writeFile(join(outdir, \"extension.js\"), built[0]!.js);\n await writeFile(join(outdir, \"extension.css\"), built[0]!.css);\n return true;\n }\n for (const [index, part] of built.entries())\n await writeFile(join(outdir, `extension-${index}.js`), part.js);\n await writeFile(\n join(outdir, \"extension.js\"),\n extensionLoader(\n parts.map((part, index) => ({\n name: part.name,\n src: `./extension-${index}.js`,\n plugin: part.plugin,\n })),\n ),\n );\n await writeFile(\n join(outdir, \"extension.css\"),\n built.map((part) => part.css).join(\"\"),\n );\n return true;\n}\n\n/**\n * The extension as the dashboard serves it. From source it is built here, and\n * rebuilt as its folder changes when watching; from a `brick build` folder it\n * is read as it is. A failed build keeps the error to show on the page.\n */\nexport class DashboardExtensionHost {\n readonly #path: string;\n readonly #warn: (message: string) => void;\n readonly #listeners = new Set<() => void>();\n #watcher: FSWatcher | undefined;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #pending: Promise<void> = Promise.resolve();\n revision = 0;\n built: BuiltExtension | undefined;\n error: string | undefined;\n\n constructor(path: string, warn: (message: string) => void) {\n this.#path = resolve(path);\n this.#warn = warn;\n }\n\n load(): Promise<void> {\n this.#pending = this.#pending.then(async () => {\n const before = JSON.stringify([this.built, this.error]);\n try {\n const prebuilt = join(this.#path, \"extension.js\");\n if (existsSync(prebuilt)) {\n const css = join(this.#path, \"extension.css\");\n const parts: Record<string, string> = {};\n for (const name of await readdir(this.#path))\n if (/^extension-\\d+\\.js$/.test(name))\n parts[name] = await readFile(join(this.#path, name), \"utf8\");\n this.built = {\n js: await readFile(prebuilt, \"utf8\"),\n css: existsSync(css) ? await readFile(css, \"utf8\") : \"\",\n parts,\n };\n } else {\n if (!existsSync(this.#path))\n throw new Error(\n `Brick: the dashboard extension ${this.#path} does not exist.`,\n );\n this.built = await buildDashboardExtension(this.#path, {\n warn: this.#warn,\n });\n }\n this.error = undefined;\n } catch (error) {\n this.built = undefined;\n this.error = error instanceof Error ? error.message : String(error);\n this.#warn(`[Brick-TS] Dashboard extension: ${this.error}`);\n }\n // The folder may hold the app too; its changes leave the bundle as it was.\n if (JSON.stringify([this.built, this.error]) === before) return;\n this.revision++;\n for (const listener of this.#listeners) listener();\n });\n return this.#pending;\n }\n\n /** Rebuild when a file in the extension's folder changes. */\n watch(): void {\n try {\n this.#watcher = watch(\n dirname(this.#path),\n { recursive: true },\n (_event, file) => {\n if (file && /(^|[\\\\/])(node_modules|\\.)/.test(file)) return;\n clearTimeout(this.#timer);\n this.#timer = setTimeout(() => void this.load(), 100);\n },\n );\n } catch {\n // A folder that cannot be watched still works; it needs a restart.\n }\n }\n\n onChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n close(): void {\n clearTimeout(this.#timer);\n this.#watcher?.close();\n this.#listeners.clear();\n }\n}\n\n/** A plugin's dashboard extension, as `app.definition.plugins` lists it. */\nexport interface PluginDashboard {\n name: string;\n dashboard?: string;\n}\n\n/** The plugins' extensions by path, each once, in install order. */\nfunction pluginDashboards(\n plugins: readonly PluginDashboard[],\n): Map<string, string> {\n const wanted = new Map<string, string>();\n for (const plugin of plugins)\n if (plugin.dashboard && !wanted.has(resolve(plugin.dashboard)))\n wanted.set(resolve(plugin.dashboard), plugin.name);\n return wanted;\n}\n\n/**\n * The module the page loads when several extensions take part: it imports\n * each one apart, so one that throws leaves the others, and merges them. The\n * app's own comes first and keeps its slots; pages whose id is taken are\n * skipped; roots nest in order; a plugin's pages without a place go under a\n * section named after it.\n */\nexport function extensionLoader(\n parts: readonly { name: string; src: string; plugin: boolean }[],\n): string {\n return `const parts = ${JSON.stringify(parts)};\nconst loaded = await Promise.allSettled(parts.map((part) => import(part.src)));\nconst merged = { pages: [], sidebar: [], slots: {} };\nconst roots = [];\nloaded.forEach((result, index) => {\n const { name, plugin } = parts[index];\n const extension = result.status === \"fulfilled\" ? result.value.default : undefined;\n if (!extension || typeof extension !== \"object\") {\n console.error(\"[Brick dashboard] Extension \" + name + \" failed to load:\", result.status === \"rejected\" ? result.reason : \"it must default-export defineDashboard({ ... })\");\n return;\n }\n for (const page of extension.pages ?? []) {\n if (merged.pages.some((item) => item.id === page.id)) {\n console.error(\"[Brick dashboard] Extension \" + name + \": page id \" + page.id + \" is taken; skipped.\");\n continue;\n }\n merged.pages.push(plugin && !page.after && !page.section ? { ...page, section: name } : page);\n }\n merged.sidebar.push(...(extension.sidebar ?? []));\n for (const [slot, value] of Object.entries(extension.slots ?? {})) {\n if (slot === \"request.drawer.tabs\") merged.slots[slot] = [...(merged.slots[slot] ?? []), ...value];\n else if (!(slot in merged.slots)) merged.slots[slot] = value;\n }\n if (extension.root) roots.push(extension.root);\n});\nif (roots.length) {\n const { createElement } = await import(\"react\");\n merged.root = ({ children }) => roots.reduceRight((inner, Root) => createElement(Root, null, inner), children);\n}\nexport default merged;\n`;\n}\n\n/**\n * The app's extension and those of its plugins, served as one. With only the\n * app's, it is served as it is; with plugins, each is built apart (a failed\n * build leaves the others) and `extension.js` loads them all.\n */\nexport class DashboardExtensions {\n readonly #warn: (message: string) => void;\n readonly #listeners = new Set<() => void>();\n readonly #parts: {\n name: string;\n path: string;\n host: DashboardExtensionHost;\n }[] = [];\n readonly #own: boolean;\n revision = 0;\n\n constructor(path: string | undefined, warn: (message: string) => void) {\n this.#warn = warn;\n this.#own = path !== undefined;\n if (path) this.#add(\"app\", path);\n }\n\n #add(name: string, path: string) {\n const host = new DashboardExtensionHost(path, this.#warn);\n host.onChange(() => this.#changed());\n this.#parts.push({ name, path: resolve(path), host });\n return host;\n }\n\n #changed() {\n this.revision++;\n for (const listener of this.#listeners) listener();\n }\n\n /** Whether any extension takes part. */\n get active(): boolean {\n return this.#parts.length > 0;\n }\n\n get built(): BuiltExtension | undefined {\n const built = this.#parts.filter((part) => part.host.built);\n if (!built.length) return undefined;\n if (this.#own && this.#parts.length === 1) return built[0]!.host.built;\n return {\n js: extensionLoader(\n this.#parts.flatMap((part, index) =>\n part.host.built\n ? [\n {\n name: part.name,\n src: `./extension-${index}.js?v=${this.revision}`,\n plugin: !(this.#own && index === 0),\n },\n ]\n : [],\n ),\n ),\n css: built.map((part) => part.host.built!.css).join(\"\"),\n };\n }\n\n get error(): string | undefined {\n const errors = this.#parts.flatMap((part) =>\n part.host.error\n ? [\n this.#own && this.#parts.length === 1\n ? part.host.error\n : `${part.name}: ${part.host.error}`,\n ]\n : [],\n );\n return errors.length ? errors.join(\"\\n\") : undefined;\n }\n\n /** A file under `/assets/` this serves, or undefined. */\n asset(name: string): string | undefined {\n if (name === \"extension.js\") return this.built?.js;\n if (name === \"extension.css\") return this.built?.css;\n const match = /^extension-(\\d+)\\.js$/.exec(name);\n if (!match) return undefined;\n // The app's alone: a `brick build` folder, whose loader imports its own parts.\n if (this.#own && this.#parts.length === 1)\n return this.#parts[0]!.host.built?.parts?.[name];\n return this.#parts[Number(match[1])]?.host.built?.js;\n }\n\n /** Follow the app's plugins: build the extensions they ship, drop the rest. */\n async setPlugins(plugins: readonly PluginDashboard[]): Promise<void> {\n // A `brick build` folder already holds its plugins' extensions.\n if (this.#own && existsSync(join(this.#parts[0]!.path, \"extension.js\")))\n return;\n const wanted = pluginDashboards(plugins);\n const start = this.#own ? 1 : 0;\n const current = this.#parts.slice(start);\n if (\n current.length === wanted.size &&\n current.every((part) => wanted.get(part.path) === part.name)\n )\n return;\n for (const part of current) part.host.close();\n this.#parts.splice(start);\n const loads = [...wanted].map(([path, name]) =>\n this.#add(name, path).load(),\n );\n await Promise.all(loads);\n this.#changed();\n }\n\n load(): Promise<void> {\n return Promise.all(this.#parts.map((part) => part.host.load())).then(\n () => undefined,\n );\n }\n\n /** Rebuild the app's own as its folder changes; plugins' are packages. */\n watch(): void {\n if (this.#own) this.#parts[0]!.host.watch();\n }\n\n onChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n close(): void {\n for (const part of this.#parts) part.host.close();\n this.#listeners.clear();\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport {\n createServer,\n type IncomingMessage,\n type ServerResponse,\n} from \"node:http\";\nimport { extname, join } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { DevDocs } from \"./dev-docs\";\nimport { INSPECTOR_PATH, INSPECTOR_TOKEN_HEADER } from \"./dev-inspector\";\nimport { parseHistoryQuery, type DevHistory } from \"./dev-history\";\nimport type { TelemetryRecord } from \"./dev-telemetry\";\nimport type {\n DevTelemetryEvent,\n DevTelemetryStore,\n} from \"./dev-telemetry-store\";\nimport { dashboardShell } from \"./dev-dashboard-shell\";\nimport type { DashboardAuth } from \"@brickkit/core\";\nimport { createAccess, isLoopbackHost } from \"./dashboard-access\";\nimport {\n assetsDirectory,\n DashboardExtensions,\n type PluginDashboard,\n themeCss,\n type DashboardExtensionOptions,\n} from \"./dashboard-extension\";\n\nexport const DEFAULT_DASHBOARD_PORT = 9400;\nconst KEEPALIVE_MS = 15_000;\nconst MAX_INGEST_BYTES = 5 * 1024 * 1024;\nconst MAX_PROXY_BYTES = 10 * 1024 * 1024;\n// Request headers that describe one hop or the dashboard's own page, and\n// response headers that fetch has already applied or that mean nothing here.\nconst NOT_FORWARDED = new Set([\n \"host\",\n \"connection\",\n \"keep-alive\",\n \"proxy-connection\",\n \"transfer-encoding\",\n \"te\",\n \"trailer\",\n \"upgrade\",\n \"content-length\",\n \"accept-encoding\",\n \"origin\",\n \"referer\",\n \"cookie\",\n]);\nconst NOT_RETURNED = new Set([\n \"connection\",\n \"keep-alive\",\n \"transfer-encoding\",\n \"content-length\",\n \"content-encoding\",\n \"set-cookie\",\n]);\n\n/**\n * What a production dashboard may show: the shell and its assets, the live\n * state and its event stream, and stored history. Nothing that changes the app\n * or reaches into it (restart, the API proxy, ingest) and nothing from the\n * project's source (documentation, OpenAPI documents). With an extension, the\n * `/app` proxy its pages read the app through.\n */\nconst isMonitoringRoute = (\n method: string | undefined,\n pathname: string,\n extension: boolean,\n) =>\n (extension && isAppRoute(pathname)) ||\n (method === \"GET\" &&\n (pathname === \"/\" ||\n pathname.startsWith(\"/assets/\") ||\n pathname === \"/api/state\" ||\n pathname === \"/api/events\" ||\n pathname.startsWith(\"/api/history\")));\n\n/** `/app/*` reaches the app itself, for the extension's `useAppFetch`. */\nconst APP_PATH = \"/app\";\nconst isAppRoute = (pathname: string) =>\n pathname === APP_PATH || pathname.startsWith(`${APP_PATH}/`);\n\nconst PRODUCTION_HEADERS = {\n \"x-content-type-options\": \"nosniff\",\n \"x-frame-options\": \"DENY\",\n \"referrer-policy\": \"no-referrer\",\n \"cross-origin-opener-policy\": \"same-origin\",\n \"cross-origin-resource-policy\": \"same-origin\",\n // Requests and logs are private: nothing caches them on the way.\n \"cache-control\": \"no-store\",\n \"content-security-policy\":\n \"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'\",\n};\n\n/** How long `/_health` waits for the app before calling it down. */\nconst PROBE_TIMEOUT_MS = 3000;\n\nexport interface DevDashboardOptions {\n port: number;\n /**\n * The address to listen on; loopback by default. Any other address needs\n * `auth`, and the server refuses to start without it.\n */\n host?: string;\n /**\n * `\"production\"` is the read-only monitoring dashboard of `brick start`: it\n * serves only what `isMonitoringRoute` lists, with security headers, and\n * tells its page to hide the tabs that need a developer's machine.\n */\n mode?: \"dev\" | \"production\";\n /** Who may use the dashboard, checked before anything but `/_health`. */\n auth?: DashboardAuth;\n /** Whether the app answers; `/_health` reports it, for uptime monitors. */\n probe?: () => Promise<boolean>;\n store: DevTelemetryStore;\n /** Requests kept on disk; omit to serve live data only. The page hides its History view. */\n history?: DevHistory;\n /** The app's developer documentation, when it has any, as of this request. */\n docs?: () => DevDocs | undefined;\n /** Omit when the host cannot restart the application; the page hides its button. */\n restart?: () => void;\n /**\n * The project's extension and theme. In dev mode the extension is rebuilt as\n * its folder changes, and the page reloads; production serves it as built.\n */\n dashboard?: DashboardExtensionOptions;\n /**\n * The app's plugins, whose extensions are built and served before the\n * dashboard listens. Dev learns them later, with `setPluginExtensions`.\n */\n plugins?: readonly PluginDashboard[];\n /** Where `/app/*` goes; the app the store's API documents name otherwise. */\n appUrl?: string;\n}\n\nexport interface DevDashboard {\n readonly port: number;\n /** Build and serve the dashboard extensions the app's plugins ship. */\n setPluginExtensions(plugins: readonly PluginDashboard[]): Promise<void>;\n stop(): void;\n}\n\n/**\n * Serve the dashboard, on loopback unless told otherwise. On loopback requests\n * must name a local host (blocks DNS rebinding), and restart requires a header\n * that cross-origin pages cannot send without a preflight. Elsewhere `auth` is\n * required and decides who gets in. Uses node:http, so it runs under Bun and\n * under Node (Vite's dev server runs under Node).\n */\nexport function startDevDashboard(\n options: DevDashboardOptions,\n): Promise<DevDashboard> {\n const host = options.host ?? \"127.0.0.1\";\n const loopback = isLoopbackHost(host);\n const production = options.mode === \"production\";\n if (!loopback && !options.auth) {\n return Promise.reject(\n new Error(\n `Brick: the dashboard would listen on ${host}, where others can reach it, so it needs access control. Set dashboard.auth with a token or an authorize function.`,\n ),\n );\n }\n let theme: string;\n try {\n theme = themeCss(options.dashboard?.theme);\n } catch (error) {\n return Promise.reject(error);\n }\n // In dev, plugins' extensions can join later (`setPluginExtensions`).\n const extension =\n options.dashboard?.extension ||\n !production ||\n options.plugins?.some((plugin) => plugin.dashboard)\n ? new DashboardExtensions(options.dashboard?.extension, (message) =>\n console.warn(message),\n )\n : undefined;\n const access = options.auth\n ? createAccess(options.auth, (error) =>\n console.error(\"[Brick-TS] The dashboard sign-in check failed:\", error),\n )\n : undefined;\n let allowedHosts = new Set<string>();\n const server = createServer((request, response) => {\n respond(request, response).catch((error: unknown) => {\n console.error(\"[Brick-TS] The dashboard failed to answer:\", error);\n if (response.headersSent) response.end();\n else send(response, 500, \"Server error\");\n });\n });\n\n async function respond(\n request: IncomingMessage,\n response: ServerResponse,\n ): Promise<void> {\n if (production)\n for (const [name, value] of Object.entries(PRODUCTION_HEADERS))\n response.setHeader(name, value);\n if (loopback && !allowedHosts.has(request.headers.host ?? \"\")) {\n send(response, 403, \"Forbidden\");\n return;\n }\n const url = new URL(request.url ?? \"/\", \"http://127.0.0.1\");\n const { pathname } = url;\n // The one route open to everyone: uptime monitors cannot sign in.\n if (\n pathname === \"/_health\" &&\n (request.method === \"GET\" || request.method === \"HEAD\")\n ) {\n await health(response);\n return;\n }\n if (access) {\n const decision = await access(request);\n if (!decision.allowed) {\n send(response, decision.status, decision.body, decision.headers);\n return;\n }\n }\n if (\n production &&\n !isMonitoringRoute(request.method, pathname, Boolean(extension?.active))\n ) {\n send(response, 404, \"Not found\");\n return;\n }\n handle(request, response, url);\n }\n\n /** 200 while the app answers its own health check, 503 when it does not. */\n async function health(response: ServerResponse): Promise<void> {\n const probe = options.probe;\n let up = true;\n if (probe) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n up = await Promise.race([\n probe().catch(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), PROBE_TIMEOUT_MS);\n }),\n ]);\n clearTimeout(timer);\n }\n send(\n response,\n up ? 200 : 503,\n JSON.stringify({\n status: up ? \"ok\" : \"degraded\",\n ...(probe ? { app: up ? \"up\" : \"down\" } : {}),\n }),\n { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" },\n );\n }\n\n function handle(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ): void {\n const { pathname } = url;\n if (request.method === \"GET\" && pathname === \"/\") {\n send(\n response,\n 200,\n dashboardShell({\n extension: extension?.active\n ? {\n revision: extension.revision,\n js: Boolean(extension.built),\n css: Boolean(extension.built?.css),\n }\n : undefined,\n theme: theme !== \"\",\n }),\n {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n },\n );\n return;\n }\n if (request.method === \"GET\" && pathname.startsWith(\"/assets/\")) {\n const name = pathname.slice(\"/assets/\".length);\n // The project's own files, kept in memory beside the dashboard's.\n const own = name === \"brick-theme.css\" ? theme : extension?.asset(name);\n if (own !== undefined)\n send(response, 200, own, {\n \"content-type\": ASSET_TYPES[extname(name)]!,\n \"cache-control\": \"no-store\",\n });\n else serveAsset(response, name);\n return;\n }\n if (isAppRoute(pathname)) {\n void app(request, response, url);\n return;\n }\n if (request.method === \"GET\" && pathname === \"/api/state\") {\n send(response, 200, JSON.stringify(snapshot()), {\n \"content-type\": \"application/json\",\n });\n return;\n }\n if (request.method === \"GET\" && pathname === \"/api/events\") {\n eventStream(request, response);\n return;\n }\n if (\n request.method === \"GET\" &&\n pathname.startsWith(\"/api/history\") &&\n options.history\n ) {\n history(options.history, pathname, url.searchParams, response);\n return;\n }\n if (request.method === \"GET\" && pathname.startsWith(\"/api/docs\")) {\n void docsRoute(response, pathname, url.searchParams);\n return;\n }\n if (request.method === \"GET\" && pathname === \"/api/openapi\") {\n send(response, 200, JSON.stringify(options.store.apiDocuments()), {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n });\n return;\n }\n if (pathname === \"/api/proxy\") {\n void proxy(request, response, url);\n return;\n }\n if (\n pathname === INSPECTOR_PATH ||\n pathname.startsWith(`${INSPECTOR_PATH}/`)\n ) {\n // Only the dashboard may frame it: framed by another site, a click could\n // land on Cancel or Replay. The rest of the dashboard may be embedded.\n response.setHeader(\"content-security-policy\", \"frame-ancestors 'self'\");\n response.setHeader(\"x-frame-options\", \"SAMEORIGIN\");\n void inspector(request, response, url);\n return;\n }\n if (request.method === \"POST\" && pathname === \"/api/ingest\") {\n ingest(request, response);\n return;\n }\n if (\n request.method === \"POST\" &&\n pathname === \"/api/restart\" &&\n options.restart\n ) {\n if (request.headers[\"x-brick-dashboard\"] !== \"1\") {\n send(response, 403, \"Forbidden\");\n return;\n }\n options.restart();\n send(response, 202, \"\");\n return;\n }\n send(response, 404, \"Not found\");\n }\n\n function snapshot() {\n return {\n ...options.store.snapshot(),\n canRestart: Boolean(options.restart),\n historyDays: options.history?.days ?? 0,\n mode: production ? \"production\" : \"dev\",\n extension: extension?.active\n ? { revision: extension.revision, error: extension.error }\n : null,\n };\n }\n\n /**\n * Accept telemetry from an application process that cannot share memory with\n * the dashboard, such as a dev server worker: span batches, and a notice when\n * the app loads.\n */\n function ingest(request: IncomingMessage, response: ServerResponse) {\n if (request.headers[\"x-brick-dashboard\"] !== \"1\") {\n send(response, 403, \"Forbidden\");\n return;\n }\n let body = \"\";\n let rejected = false;\n request.setEncoding(\"utf8\");\n request.on(\"data\", (chunk: string) => {\n if (rejected) return;\n body += chunk;\n if (body.length > MAX_INGEST_BYTES) {\n rejected = true;\n send(response, 413, \"Payload too large\");\n request.destroy();\n }\n });\n request.on(\"end\", () => {\n if (rejected) return;\n try {\n const payload = JSON.parse(body) as {\n records?: TelemetryRecord[];\n worker?: string;\n };\n if (Array.isArray(payload.records)) {\n options.store.ingest(payload.records, options.store.latestGeneration);\n }\n if (typeof payload.worker === \"string\") {\n options.store.startGeneration(payload.worker);\n }\n send(response, 204, \"\");\n } catch {\n send(response, 400, \"Bad request\");\n }\n });\n }\n\n /** The Docs tab's data: tree, compiled pages, search, images, components. */\n async function docsRoute(\n response: ServerResponse,\n pathname: string,\n params: URLSearchParams,\n ): Promise<void> {\n const docs = options.docs?.();\n if (!docs) {\n send(response, 404, \"The app has no documentation.\");\n return;\n }\n const json = (body: unknown) =>\n send(response, 200, JSON.stringify(body), {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n });\n try {\n if (pathname === \"/api/docs\") return json(docs.info());\n if (pathname === \"/api/docs/search\")\n return json(await docs.search(params.get(\"q\") ?? \"\"));\n if (pathname === \"/api/docs/components.js\") {\n const code = await docs.components();\n if (code === undefined) return send(response, 404, \"No components.\");\n return send(response, 200, code, {\n \"content-type\": \"text/javascript; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n }\n const pagePrefix = \"/api/docs/page\";\n if (pathname === pagePrefix || pathname.startsWith(`${pagePrefix}/`)) {\n const slugs = pathname\n .slice(pagePrefix.length)\n .split(\"/\")\n .filter(Boolean)\n .map(decodeURIComponent);\n const page = await docs.page(slugs);\n return page ? json(page) : send(response, 404, \"No such page.\");\n }\n const filePrefix = \"/api/docs/files/\";\n if (pathname.startsWith(filePrefix)) {\n const file = await docs.file(\n pathname\n .slice(filePrefix.length)\n .split(\"/\")\n .map(decodeURIComponent)\n .join(\"/\"),\n );\n if (!file) return send(response, 404, \"No such file.\");\n return send(response, 200, file.body, {\n \"content-type\": file.type,\n \"cache-control\": \"no-store\",\n // An image in a page; a document opened directly cannot run scripts.\n \"content-security-policy\": \"sandbox\",\n });\n }\n send(response, 404, \"Not found\");\n } catch (error) {\n send(\n response,\n error instanceof URIError ? 400 : 500,\n error instanceof Error ? error.message : String(error),\n );\n }\n }\n\n /**\n * Send a request on to the app for the APIs view, which cannot call the app\n * directly: it is another origin. Only the dashboard's own page may use this,\n * and only to reach the app being shown. The address to call is `?url=`; a\n * `?cookie=` is the cookie parameters the reader typed into Try it, and the\n * only cookie the app is sent (the dashboard's own are never forwarded).\n */\n /**\n * Pass a request to the workflow inspector, which the app serves on a port of\n * its own, and stream its answer back (it follows a run's output as it\n * grows). Anyone who can open the dashboard may look, but a change must come\n * from the dashboard's own page: the inspector can cancel runs and resume\n * hooks, and a page on another site could otherwise post to it.\n */\n async function inspector(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ): Promise<void> {\n const target = options.store.inspectorTarget();\n if (!target) {\n send(\n response,\n 503,\n \"The workflow inspector is not running. The app may be restarting, or it may run no workflows.\",\n { \"content-type\": \"text/plain; charset=utf-8\" },\n );\n return;\n }\n const bodyless = request.method === \"GET\" || request.method === \"HEAD\";\n const site = request.headers[\"sec-fetch-site\"];\n const origin = request.headers.origin;\n if (\n !bodyless &&\n ((site !== undefined && site !== \"same-origin\") ||\n (origin !== undefined && origin !== `http://${request.headers.host}`))\n ) {\n send(response, 403, \"Forbidden\");\n return;\n }\n await forward(\n request,\n response,\n `http://127.0.0.1:${target.port}${url.pathname}${url.search}`,\n (headers) => headers.set(INSPECTOR_TOKEN_HEADER, target.token),\n \"Could not reach the workflow inspector.\",\n );\n }\n\n /**\n * Pass `/app/*` to the app, so the extension's pages read it from the\n * dashboard's own origin. Only the dashboard's page may use it, as with the\n * API proxy. A credential for the dashboard itself is not passed on.\n */\n async function app(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ): Promise<void> {\n const site = request.headers[\"sec-fetch-site\"];\n const origin = request.headers.origin;\n if (\n (site !== undefined && site !== \"same-origin\") ||\n (origin !== undefined && origin !== `http://${request.headers.host}`)\n ) {\n send(response, 403, \"Forbidden\");\n return;\n }\n const appUrl = options.appUrl ?? options.store.apiSnapshot()?.appUrl;\n if (!appUrl) {\n send(response, 503, \"The app is not running yet.\");\n return;\n }\n // Framed by an extension's iframe page, and by nothing else.\n response.setHeader(\"content-security-policy\", \"frame-ancestors 'self'\");\n response.setHeader(\"x-frame-options\", \"SAMEORIGIN\");\n await forward(\n request,\n response,\n `${new URL(appUrl).origin}${url.pathname.slice(APP_PATH.length) || \"/\"}${url.search}`,\n (headers) => {\n if (access) headers.delete(\"authorization\");\n },\n \"Could not reach the app.\",\n );\n }\n\n /** Send the request on to `target` and stream its answer back. */\n async function forward(\n request: IncomingMessage,\n response: ServerResponse,\n target: string,\n adjust: (headers: Headers) => void,\n unreachable: string,\n ): Promise<void> {\n const bodyless = request.method === \"GET\" || request.method === \"HEAD\";\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (value === undefined || NOT_FORWARDED.has(name)) continue;\n if (name.startsWith(\"sec-\")) continue;\n headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n }\n adjust(headers);\n const abort = new AbortController();\n response.on(\"close\", () => abort.abort());\n try {\n const upstream = await fetch(target, {\n method: request.method,\n headers,\n redirect: \"manual\",\n signal: abort.signal,\n ...(bodyless\n ? {}\n : {\n body: Readable.toWeb(request) as unknown as BodyInit,\n duplex: \"half\",\n }),\n } as RequestInit);\n const returned: Record<string, string> = {};\n upstream.headers.forEach((value, name) => {\n if (!NOT_RETURNED.has(name)) returned[name] = value;\n });\n response.writeHead(upstream.status, returned);\n if (!upstream.body || request.method === \"HEAD\") {\n response.end();\n return;\n }\n await pipeline(Readable.fromWeb(upstream.body as never), response);\n } catch {\n if (response.headersSent) response.destroy();\n else send(response, 502, unreachable);\n }\n }\n\n async function proxy(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ): Promise<void> {\n const site = request.headers[\"sec-fetch-site\"];\n const origin = request.headers.origin;\n if (\n (site !== undefined && site !== \"same-origin\") ||\n (origin !== undefined && origin !== `http://${request.headers.host}`)\n ) {\n send(response, 403, \"Forbidden\");\n return;\n }\n let target: URL | undefined;\n try {\n target = new URL(url.searchParams.get(\"url\") ?? \"\");\n } catch {\n // Not an address; refused below.\n }\n const appUrl = options.store.apiSnapshot()?.appUrl;\n if (!target || !appUrl || target.origin !== new URL(appUrl).origin) {\n send(\n response,\n 403,\n \"Only the app shown in the dashboard can be reached.\",\n );\n return;\n }\n const body = await readBytes(request, MAX_PROXY_BYTES);\n if (!body) {\n send(response, 413, \"Payload too large\");\n return;\n }\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (value === undefined || NOT_FORWARDED.has(name)) continue;\n if (name.startsWith(\"sec-\")) continue;\n headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n }\n const cookie = url.searchParams.get(\"cookie\");\n if (cookie) headers.set(\"cookie\", cookie);\n const bodyless = request.method === \"GET\" || request.method === \"HEAD\";\n try {\n const upstream = await fetch(target, {\n method: request.method,\n headers,\n body: bodyless ? undefined : (body as BodyInit),\n redirect: \"manual\",\n });\n const returned: Record<string, string> = {};\n upstream.headers.forEach((value, name) => {\n if (!NOT_RETURNED.has(name)) returned[name] = value;\n });\n send(\n response,\n upstream.status,\n new Uint8Array(await upstream.arrayBuffer()),\n returned,\n );\n } catch {\n send(response, 502, \"Could not reach the app.\");\n }\n }\n\n function eventStream(request: IncomingMessage, response: ServerResponse) {\n response.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n // So a proxy in front passes events on as they come.\n \"x-accel-buffering\": \"no\",\n });\n const write = (chunk: string) => {\n if (response.writableEnded || response.destroyed) return;\n response.write(chunk);\n };\n write(`event: snapshot\\ndata: ${JSON.stringify(snapshot())}\\n\\n`);\n const unsubscribe = options.store.subscribe((event: DevTelemetryEvent) =>\n write(`event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`),\n );\n // A rebuilt extension: the page reloads to run it.\n const unwatch = extension?.onChange(() =>\n write(\n `event: extension\\ndata: ${JSON.stringify(snapshot().extension)}\\n\\n`,\n ),\n );\n const keepalive = setInterval(() => write(\": keepalive\\n\\n\"), KEEPALIVE_MS);\n request.on(\"close\", () => {\n clearInterval(keepalive);\n unsubscribe();\n unwatch?.();\n });\n }\n\n // The first build finishes before the page can be asked for; a failed one\n // is shown on the page, and does not stop the dashboard.\n const ready = extension\n ? Promise.all([\n extension.load(),\n options.plugins && extension.setPlugins(options.plugins),\n ])\n : Promise.resolve();\n return ready.then(() => listen());\n\n function listen(): Promise<DevDashboard> {\n return new Promise((resolve, reject) => {\n server.once(\"error\", (error) => {\n extension?.close();\n reject(\n new Error(\n production\n ? `Brick: dashboard port ${options.port} is unavailable. Set dashboard.port in brick() to another.`\n : `Brick: dashboard port ${options.port} is unavailable. Use --dashboard-port <number> or --no-dashboard.`,\n { cause: error },\n ),\n );\n });\n server.listen(options.port, host, () => {\n const address = server.address();\n const port =\n typeof address === \"object\" && address !== null\n ? address.port\n : options.port;\n allowedHosts = new Set([\n `127.0.0.1:${port}`,\n `localhost:${port}`,\n `[::1]:${port}`,\n ]);\n if (!production) extension?.watch();\n resolve({\n port,\n setPluginExtensions: (plugins) =>\n extension?.setPlugins(plugins) ?? Promise.resolve(),\n stop() {\n extension?.close();\n server.close();\n server.closeAllConnections();\n },\n });\n });\n });\n }\n}\n\n/** The whole request body, or undefined when it is larger than `limit`. */\nfunction readBytes(\n request: IncomingMessage,\n limit: number,\n): Promise<Uint8Array | undefined> {\n return new Promise((resolve) => {\n const chunks: Buffer[] = [];\n let size = 0;\n request.on(\"data\", (chunk: Buffer) => {\n size += chunk.length;\n if (size > limit) {\n resolve(undefined);\n request.destroy();\n return;\n }\n chunks.push(chunk);\n });\n request.on(\"end\", () => resolve(new Uint8Array(Buffer.concat(chunks))));\n request.on(\"error\", () => resolve(undefined));\n });\n}\n\nfunction history(\n store: DevHistory,\n pathname: string,\n params: URLSearchParams,\n response: ServerResponse,\n): void {\n const json = (body: unknown) =>\n send(response, 200, JSON.stringify(body), {\n \"content-type\": \"application/json\",\n });\n try {\n if (pathname === \"/api/history\") return json(store.info());\n if (pathname === \"/api/history/summary\") {\n return json(store.summary(parseHistoryQuery(params)));\n }\n if (pathname === \"/api/history/traces\") {\n return json(store.traces(parseHistoryQuery(params)));\n }\n if (pathname === \"/api/history/facets\") {\n return json(store.facets(parseHistoryQuery(params)));\n }\n if (pathname === \"/api/history/volume\") {\n return json(store.volume(parseHistoryQuery(params)));\n }\n if (pathname === \"/api/history/export\") {\n return send(response, 200, store.exportCsv(parseHistoryQuery(params)), {\n \"content-type\": \"text/csv; charset=utf-8\",\n \"content-disposition\": 'attachment; filename=\"brick-requests.csv\"',\n \"cache-control\": \"no-store\",\n });\n }\n const prefix = \"/api/history/traces/\";\n if (pathname.startsWith(prefix)) {\n const trace = store.trace(\n decodeURIComponent(pathname.slice(prefix.length)),\n );\n if (trace) return json(trace);\n }\n send(response, 404, \"Not found\");\n } catch {\n send(response, 500, \"History query failed\");\n }\n}\n\nconst ASSET_TYPES: Record<string, string> = {\n \".js\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".woff2\": \"font/woff2\",\n};\n\nfunction serveAsset(response: ServerResponse, name: string): void {\n // Plain file names only: no separators, so a request cannot leave the folder.\n if (!/^[\\w.-]+$/.test(name) || name.startsWith(\".\")) {\n send(response, 404, \"Not found\");\n return;\n }\n const directory = assetsDirectory();\n if (!directory) {\n send(\n response,\n 503,\n \"Dashboard assets are missing. Build them with: bun run --filter @brickkit/cli build\",\n );\n return;\n }\n readFile(join(directory, name)).then(\n (body) =>\n send(response, 200, body, {\n \"content-type\":\n ASSET_TYPES[extname(name)] ?? \"application/octet-stream\",\n \"cache-control\": \"no-store\",\n }),\n () => send(response, 404, \"Not found\"),\n );\n}\n\nfunction send(\n response: ServerResponse,\n status: number,\n body: string | Uint8Array,\n headers: Record<string, string | string[]> = {\n \"content-type\": \"text/plain; charset=utf-8\",\n },\n): void {\n response.writeHead(status, headers);\n response.end(body);\n}\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { ApiDocument, ArchitectureSchema } from \"@brickkit/core\";\nimport type { DevHistory } from \"./dev-history\";\nimport type {\n SerializedError,\n SpanEndRecord,\n SpanEventRecord,\n SpanStartRecord,\n TelemetryRecord,\n WorkerErrorPhase,\n} from \"./dev-telemetry\";\n\nexport type SpanOutcome = \"running\" | \"ok\" | \"error\" | \"interrupted\";\n\nexport interface TraceSpan {\n spanId: string;\n parentSpanId?: string;\n name: string;\n startMs: number;\n endMs?: number;\n status: SpanOutcome;\n statusMessage?: string;\n attributes: Attributes;\n events: SpanEventRecord[];\n}\n\nexport interface TraceSummary {\n traceId: string;\n name: string;\n method?: string;\n route?: string;\n /** The request's actual path, which differs from a wildcard route template. */\n path?: string;\n httpStatus?: number;\n generation: number;\n startMs: number;\n endMs?: number;\n durationMs?: number;\n status: SpanOutcome;\n truncated: boolean;\n /** The service and action that handled the request, when it ran one. */\n service?: string;\n action?: string;\n /** Why it failed, when it did. */\n message?: string;\n /** The request used a v0.10 path that `brick({ legacyRoutes: true })` still serves. */\n legacyRoute?: boolean;\n spans: TraceSpan[];\n}\n\nexport interface FailureSummary {\n id: number;\n at: number;\n phase: \"request\" | WorkerErrorPhase;\n code: string;\n message: string;\n status?: number;\n stack?: string;\n traceId?: string;\n route?: string;\n service?: string;\n action?: string;\n generation: number;\n}\n\nexport type ReloadKind = \"started\" | \"restarting\" | \"exited\" | \"contract-ready\";\n\nexport interface ReloadSummary {\n id: number;\n at: number;\n kind: ReloadKind;\n generation: number;\n detail?: string;\n}\n\n/** Services, actions, and routes of the application as last started. */\nexport interface ArchitectureSnapshot {\n generation: number;\n schema: ArchitectureSchema;\n}\n\n/** The OpenAPI documents the app offers, for the dashboard's APIs view. */\nexport interface ApiSnapshot {\n /** Changes each time the documents are replaced, so views know to reload. */\n revision: number;\n /** Where the app listens; Try it in the APIs view sends requests here. */\n appUrl?: string;\n /** Names of the documents, in order. */\n titles: string[];\n}\n\n/** What the dashboard knows about the app's developer documentation. */\nexport interface DocsSnapshot {\n /** Changes whenever the pages change, so the Docs tab reloads. */\n revision: number;\n status: \"ready\" | \"missing\" | \"error\";\n title: string;\n /** Whether the project supplied components of its own. */\n components: boolean;\n /** Why the docs cannot be shown, when `status` is not ready. */\n message?: string;\n /** Packages to install, when `status` is \"missing\". */\n packages?: string[];\n}\n\nexport type DevTelemetryEvent =\n | { type: \"trace\"; trace: TraceSummary }\n | { type: \"failure\"; failure: FailureSummary }\n | { type: \"reload\"; reload: ReloadSummary }\n | { type: \"architecture\"; architecture: ArchitectureSnapshot }\n | { type: \"api\"; api: ApiSnapshot }\n | { type: \"docs\"; docs: DocsSnapshot | null }\n | { type: \"inspector\"; inspector: boolean };\n\nexport interface DevTelemetrySnapshot {\n traces: TraceSummary[];\n failures: FailureSummary[];\n reloads: ReloadSummary[];\n architecture: ArchitectureSnapshot | null;\n api: ApiSnapshot | null;\n /** Null when the app has no `documentation`. */\n docs: DocsSnapshot | null;\n /** Whether the app serves the workflow inspector the dashboard can show. */\n inspector: boolean;\n}\n\nconst LIMITS = { traces: 200, spansPerTrace: 500, failures: 200, reloads: 100 };\n\nconst WORKER_FAILURE_CODES: Record<WorkerErrorPhase, string> = {\n startup: \"STARTUP_FAILED\",\n uncaught: \"UNCAUGHT_EXCEPTION\",\n \"unhandled-rejection\": \"UNHANDLED_REJECTION\",\n};\n\ninterface TraceEntry {\n traceId: string;\n generation: number;\n spans: Map<string, TraceSpan>;\n rootSpanId?: string;\n name: string;\n method?: string;\n route?: string;\n path?: string;\n httpStatus?: number;\n startMs: number;\n endMs?: number;\n status: SpanOutcome;\n failureRecorded: boolean;\n truncated: boolean;\n message?: string;\n}\n\n/**\n * Supervisor-side history of requests, failures, and reloads. It lives in the\n * parent process, so it survives application restarts.\n */\nexport class DevTelemetryStore {\n readonly #traces = new Map<string, TraceEntry>();\n readonly #failures: FailureSummary[] = [];\n readonly #reloads: ReloadSummary[] = [];\n readonly #listeners = new Set<(event: DevTelemetryEvent) => void>();\n readonly #history: DevHistory | undefined;\n #architecture: ArchitectureSnapshot | null = null;\n #api: ApiSnapshot | null = null;\n #docs: DocsSnapshot | null = null;\n #inspector: { port: number; token: string } | undefined;\n #apiDocuments: ApiDocument[] = [];\n #sequence = 0;\n #generation = 0;\n\n /** Finished requests and failures are also kept in `history`, when given. */\n constructor(options: { history?: DevHistory } = {}) {\n this.#history = options.history;\n }\n\n /** Replace the architecture with the one from the latest successful start. */\n setArchitecture(schema: ArchitectureSchema, generation: number): void {\n this.#architecture = { generation, schema };\n this.#emit({ type: \"architecture\", architecture: this.#architecture });\n }\n\n ingest(records: TelemetryRecord[], generation: number): void {\n const touched = new Set<TraceEntry>();\n for (const record of records) {\n const timeMs = record.phase === \"start\" ? record.startMs : record.endMs;\n const entry = this.#entry(record.traceId, generation, timeMs);\n touched.add(entry);\n if (record.phase === \"start\") this.#start(entry, record);\n else this.#end(entry, record);\n }\n for (const entry of touched) {\n const trace = summarize(entry);\n this.#emit({ type: \"trace\", trace });\n // A request cut off by a restart is not a result worth keeping, and one\n // still running will be saved when it finishes.\n if (entry.status === \"ok\" || entry.status === \"error\") {\n this.#history?.saveTrace(trace);\n }\n }\n }\n\n recordWorkerError(\n phase: WorkerErrorPhase,\n error: SerializedError,\n generation: number,\n ): void {\n this.#pushFailure({\n phase,\n code: WORKER_FAILURE_CODES[phase],\n message: error.message,\n stack: error.stack,\n generation,\n });\n }\n\n recordReload(reload: Omit<ReloadSummary, \"id\" | \"at\">): void {\n const summary: ReloadSummary = {\n id: ++this.#sequence,\n at: Date.now(),\n ...reload,\n };\n this.#reloads.unshift(summary);\n if (this.#reloads.length > LIMITS.reloads) {\n this.#reloads.length = LIMITS.reloads;\n }\n this.#emit({ type: \"reload\", reload: summary });\n }\n\n /** Newest generation; spans reported without a process identity belong to it. */\n get latestGeneration(): number {\n return this.#generation;\n }\n\n /** Begin a generation when an application process loads, and record the reload. */\n startGeneration(detail: string): number {\n this.#generation += 1;\n this.recordReload({\n kind: \"started\",\n generation: this.#generation,\n detail,\n });\n return this.#generation;\n }\n\n /** Mark requests still running in a process that has exited as interrupted. */\n interruptGeneration(generation: number): void {\n const now = Date.now();\n for (const entry of this.#traces.values()) {\n if (entry.generation !== generation || entry.status !== \"running\")\n continue;\n entry.status = \"interrupted\";\n entry.endMs = now;\n for (const span of entry.spans.values()) {\n if (span.status !== \"running\") continue;\n span.status = \"interrupted\";\n span.endMs = now;\n }\n this.#emit({ type: \"trace\", trace: summarize(entry) });\n }\n }\n\n /** Replace the OpenAPI documents with the ones from the latest start. */\n setApiDocuments(documents: ApiDocument[], appUrl?: string): void {\n this.#apiDocuments = documents;\n this.#api = {\n revision: (this.#api?.revision ?? 0) + 1,\n ...(appUrl ? { appUrl } : {}),\n titles: documents.map((item) => item.title),\n };\n this.#emit({ type: \"api\", api: this.#api });\n }\n\n /** Set what the Docs tab shows; null when the app has no documentation. */\n setDocs(docs: DocsSnapshot | null): void {\n this.#docs = docs;\n this.#emit({ type: \"docs\", docs });\n }\n\n /**\n * Set where the app serves its workflow inspector, or `undefined` when it\n * stops. The address stays here: the snapshot says only whether there is one.\n */\n setInspector(target: { port: number; token: string } | undefined): void {\n this.#inspector = target;\n this.#emit({ type: \"inspector\", inspector: Boolean(target) });\n }\n\n /** Where the dashboard proxies the workflow inspector, when the app serves one. */\n inspectorTarget(): { port: number; token: string } | undefined {\n return this.#inspector;\n }\n\n /** What the APIs view knows about the documents, without the documents. */\n apiSnapshot(): ApiSnapshot | null {\n return this.#api;\n }\n\n /** The documents themselves; the snapshot carries only their names. */\n apiDocuments(): ApiDocument[] {\n return this.#apiDocuments;\n }\n\n snapshot(): DevTelemetrySnapshot {\n return {\n traces: [...this.#traces.values()].reverse().map(summarize),\n failures: [...this.#failures],\n reloads: [...this.#reloads],\n architecture: this.#architecture,\n api: this.#api,\n docs: this.#docs,\n inspector: Boolean(this.#inspector),\n };\n }\n\n subscribe(listener: (event: DevTelemetryEvent) => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #entry(traceId: string, generation: number, timeMs: number): TraceEntry {\n let entry = this.#traces.get(traceId);\n if (!entry) {\n entry = {\n traceId,\n generation,\n spans: new Map(),\n name: \"\",\n startMs: timeMs,\n status: \"running\",\n failureRecorded: false,\n truncated: false,\n };\n this.#traces.set(traceId, entry);\n if (this.#traces.size > LIMITS.traces) {\n const oldest = this.#traces.keys().next().value;\n if (oldest !== undefined) this.#traces.delete(oldest);\n }\n }\n return entry;\n }\n\n #start(entry: TraceEntry, record: SpanStartRecord): void {\n entry.startMs = Math.min(entry.startMs, record.startMs);\n // The local root has no parent here: either none, or a remote caller's span\n // from an incoming traceparent. Children start after it in this process.\n const parentIsLocal =\n record.parentSpanId !== undefined && entry.spans.has(record.parentSpanId);\n if (!parentIsLocal && entry.rootSpanId === undefined) {\n entry.rootSpanId = record.spanId;\n entry.name = record.name;\n entry.method = stringAttribute(record.attributes, \"http.request.method\");\n entry.route = stringAttribute(record.attributes, \"http.route\");\n entry.path = stringAttribute(record.attributes, \"url.path\");\n }\n if (entry.spans.size >= LIMITS.spansPerTrace) {\n entry.truncated = true;\n return;\n }\n entry.spans.set(record.spanId, {\n spanId: record.spanId,\n parentSpanId: record.parentSpanId,\n name: record.name,\n startMs: record.startMs,\n status: \"running\",\n attributes: record.attributes,\n events: [],\n });\n }\n\n #end(entry: TraceEntry, record: SpanEndRecord): void {\n const existing = entry.spans.get(record.spanId);\n const span: TraceSpan = existing ?? {\n spanId: record.spanId,\n name: record.name,\n startMs: record.endMs,\n status: \"running\",\n attributes: {},\n events: [],\n };\n if (!existing) {\n if (entry.spans.size < LIMITS.spansPerTrace) {\n entry.spans.set(record.spanId, span);\n } else {\n entry.truncated = true;\n }\n }\n span.endMs = record.endMs;\n span.status = record.status === \"error\" ? \"error\" : \"ok\";\n span.statusMessage = record.statusMessage;\n span.attributes = { ...span.attributes, ...record.attributes };\n span.events = record.events;\n\n const code = stringAttribute(record.attributes, \"brick.error.code\");\n if (code !== undefined) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code,\n message:\n stringAttribute(exception, \"exception.message\") ??\n stringAttribute(record.attributes, \"brick.error.message\") ??\n code,\n status: numberAttribute(record.attributes, \"brick.error.status\"),\n stack: stringAttribute(exception, \"exception.stacktrace\"),\n traceId: entry.traceId,\n route: entry.route,\n service: stringAttribute(record.attributes, \"brick.service\"),\n action: stringAttribute(record.attributes, \"brick.action\"),\n generation: entry.generation,\n });\n entry.failureRecorded = true;\n }\n\n if (record.spanId !== entry.rootSpanId) return;\n entry.endMs = record.endMs;\n entry.httpStatus = numberAttribute(\n record.attributes,\n \"http.response.status_code\",\n );\n // Server faults make the trace an error. Client errors still show in the\n // Errors tab, so a raw route's 401 is visible without a coded failure.\n const status = entry.httpStatus ?? 0;\n const serverFault = status >= 500;\n const failed = record.status === \"error\" || serverFault;\n entry.status = failed ? \"error\" : \"ok\";\n if ((failed || status >= 400) && !entry.failureRecorded) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code: status >= 400 ? `HTTP_${status}` : \"UNHANDLED_ERROR\",\n message:\n stringAttribute(exception, \"exception.message\") ??\n record.statusMessage ??\n describeResponse(entry, status),\n status: entry.httpStatus,\n stack: stringAttribute(exception, \"exception.stacktrace\"),\n traceId: entry.traceId,\n route: entry.route,\n generation: entry.generation,\n });\n entry.failureRecorded = true;\n }\n }\n\n #pushFailure(failure: Omit<FailureSummary, \"id\" | \"at\">): void {\n const entry: FailureSummary = {\n id: ++this.#sequence,\n at: Date.now(),\n ...failure,\n };\n this.#failures.unshift(entry);\n if (this.#failures.length > LIMITS.failures) {\n this.#failures.length = LIMITS.failures;\n }\n // The request keeps the first reason it failed, to show beside it.\n const trace =\n failure.traceId === undefined\n ? undefined\n : this.#traces.get(failure.traceId);\n if (trace) trace.message ??= failure.message;\n this.#emit({ type: \"failure\", failure: entry });\n }\n\n #emit(event: DevTelemetryEvent): void {\n for (const listener of this.#listeners) {\n try {\n listener(event);\n } catch {\n this.#listeners.delete(listener);\n }\n }\n }\n}\n\nfunction summarize(entry: TraceEntry): TraceSummary {\n const spans = [...entry.spans.values()].sort((a, b) => a.startMs - b.startMs);\n const actionSpan = spans.find((span) => span.name.startsWith(\"action \"));\n return {\n traceId: entry.traceId,\n name: entry.name || spans[0]?.name || entry.traceId,\n method: entry.method,\n route: entry.route,\n path: entry.path,\n httpStatus: entry.httpStatus,\n generation: entry.generation,\n startMs: entry.startMs,\n endMs: entry.endMs,\n durationMs:\n entry.endMs === undefined ? undefined : entry.endMs - entry.startMs,\n status: entry.status,\n truncated: entry.truncated,\n service: stringAttribute(actionSpan?.attributes, \"brick.service\"),\n action: stringAttribute(actionSpan?.attributes, \"brick.action\"),\n message: entry.message,\n ...(entry.spans.get(entry.rootSpanId ?? \"\")?.attributes[\n \"brick.legacy_route\"\n ] === true\n ? { legacyRoute: true }\n : {}),\n spans,\n };\n}\n\nfunction describeResponse(entry: TraceEntry, status: number): string {\n const target = entry.path ?? entry.route ?? entry.name;\n const request = entry.method ? `${entry.method} ${target}` : target;\n return status ? `${request} returned ${status}` : request;\n}\n\nfunction findException(events: SpanEventRecord[]): Attributes | undefined {\n return events.find((event) => event.name === \"exception\")?.attributes;\n}\n\nfunction stringAttribute(\n attributes: Attributes | undefined,\n key: string,\n): string | undefined {\n const value = attributes?.[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction numberAttribute(\n attributes: Attributes | undefined,\n key: string,\n): number | undefined {\n const value = attributes?.[key];\n return typeof value === \"number\" ? value : undefined;\n}\n"],"mappings":";;;;;;;;;;;AAOA,MAAa,iBAAiB;;AAE9B,MAAa,yBAAyB;;AAUtC,MAAM,sBAAsB,cAC1B,IAAI,IAAI,sBAAsB,YAAY,GAAG,CAC/C;;AAGA,SAAS,OAAO,MAAuB;CACrC,IAAI;EACF,OAAO,SAAS,IAAI,CAAC,CAAC,OAAO;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;AAQA,SAAS,aAAa,SAAkB,QAAsC;CAC5E,IAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,QAAQ,OAAO,KAAA;CAClE,MAAM,EAAE,aAAa,IAAI,IAAI,QAAQ,GAAG;CACxC,IAAI,CAAC,SAAS,WAAW,oBAA2B,GAAG,OAAO,KAAA;CAC9D,MAAM,OAAO,QAAQ,QAAQ,SAAS,MAAM,EAAyB,CAAC;CACtE,IAAI,CAAC,KAAK,WAAW,SAAS,GAAG,KAAK,CAAC,OAAO,IAAI,GAChD,OAAO,IAAI,SAAS,aAAa,EAAE,QAAQ,IAAI,CAAC;CAClD,OAAO,IAAI,SAAS,IAAI,KAAK,IAAI,GAAG,EAClC,SAAS,EAAE,iBAAiB,sCAAsC,EACpE,CAAC;AACH;;;;;;;;;;;;;AAcA,eAAsB,eACpB,KACA,YAAY,qBACoB;CAChC,MAAM,SAAS,IAAI,QAAQ;CAC3B,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,MAAM,QAAQ,KAAK,WAAW,UAAU,UAAU;CAClD,IAA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