@brickkit/cli 0.14.0 → 0.15.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.
@@ -1 +1 @@
1
- {"version":3,"file":"dashboard-host.js","names":[],"sources":["../src/dashboard-extension.ts","../src/dev-docs.ts","../src/dashboard-query.ts","../src/dev-dashboard-shell.ts","../src/dashboard-access.ts","../src/dev-dashboard.ts","../src/dev-history.ts","../src/dev-telemetry-store.ts","../src/dashboard-host.ts"],"sourcesContent":["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 { ConfigError } from \"./config\";\nimport {\n ASSETS,\n SHARED_MODULES,\n type ExtensionPart,\n} from \"./dashboard-protocol\";\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 ConfigError(\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 ConfigError(\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 ConfigError(\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 ConfigError(\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\nconst SHARED = SHARED_MODULES.map((module) => module.specifier);\n\n/** Bundle a module of React components for the dashboard to import (an extension, or the docs' components), with its shared modules left to the page. */\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 dashboard module produced no output.\");\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 /** The `extension-N.js` files `js` lists, by name. */\n parts?: Record<string, string>;\n}\n\n/** The `warn` functions already told that tailwindcss is missing: once each, not once per rebuild. */\nconst warnedTailwind = new WeakSet<(message: string) => void>();\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 }\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.has(warn))\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.add(warn);\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 warn = (message: string) => console.warn(message);\n const built = await Promise.all(\n parts.map((part) =>\n buildDashboardExtension(part.path, { warn }).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 writeBuiltFolder(\n outdir,\n layoutParts(\n parts.map((part, index) => ({ ...part, built: built[index] })),\n )!,\n );\n return true;\n}\n\n/** Whether `path` is a folder `brick build` wrote, which is served as it is. */\nconst isBuiltFolder = (path: string): boolean =>\n existsSync(join(path, ASSETS.extension));\n\n/** Write the extensions as `layoutParts` lays them out; `readBuiltFolder` reads them back. */\nasync function writeBuiltFolder(\n outdir: string,\n layout: BuiltExtension,\n): Promise<void> {\n await mkdir(outdir, { recursive: true });\n await writeFile(join(outdir, ASSETS.extension), layout.js);\n await writeFile(join(outdir, ASSETS.extensionCss), layout.css);\n for (const [name, js] of Object.entries(layout.parts ?? {}))\n await writeFile(join(outdir, name), js);\n}\n\nasync function readBuiltFolder(path: string): Promise<BuiltExtension> {\n const css = join(path, ASSETS.extensionCss);\n const parts: Record<string, string> = {};\n for (const name of await readdir(path))\n if (/^extension-\\d+\\.js$/.test(name))\n parts[name] = await readFile(join(path, name), \"utf8\");\n return {\n js: await readFile(join(path, ASSETS.extension), \"utf8\"),\n css: existsSync(css) ? await readFile(css, \"utf8\") : \"\",\n parts,\n };\n}\n\n/**\n * How the extensions are served, by `brick dev` and from a `brick build`\n * folder alike. The app's alone is served as it is. Otherwise each that built\n * is `extension-<index>.js`, `extension.js` lists them for the page to load\n * and merge, and their styles are served together. `version` is added to each\n * part's address, so a rebuilt one is fetched again.\n */\nfunction layoutParts(\n parts: readonly {\n name: string;\n plugin: boolean;\n built: BuiltExtension | undefined;\n }[],\n version = \"\",\n): BuiltExtension | undefined {\n if (parts.length === 1 && !parts[0]!.plugin) return parts[0]!.built;\n const built = parts.flatMap((part, index) =>\n part.built\n ? [{ ...part, built: part.built, file: `extension-${index}.js` }]\n : [],\n );\n if (!built.length) return undefined;\n return {\n js: extensionManifest(\n built.map((part) => ({\n name: part.name,\n src: `./${part.file}${version}`,\n plugin: part.plugin,\n })),\n ),\n css: built.map((part) => part.built.css).join(\"\"),\n parts: Object.fromEntries(built.map((part) => [part.file, part.built.js])),\n };\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 if (isBuiltFolder(this.#path)) {\n this.built = await readBuiltFolder(this.#path);\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 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 lists them,\n * and the page imports each apart and merges them (`mergeExtensions` there).\n */\nexport function extensionManifest(parts: readonly ExtensionPart[]): string {\n return `export const parts = ${JSON.stringify(parts)};\\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 /** The app's own first, when it has one, then its plugins'. */\n readonly #parts: {\n name: string;\n path: string;\n plugin: boolean;\n host: DashboardExtensionHost;\n }[] = [];\n revision = 0;\n\n constructor(path: string | undefined, warn: (message: string) => void) {\n this.#warn = warn;\n if (path) this.#add(\"app\", path, false);\n }\n\n #add(name: string, path: string, plugin: boolean) {\n const host = new DashboardExtensionHost(path, this.#warn);\n host.onChange(() => this.#changed());\n this.#parts.push({ name, path: resolve(path), plugin, host });\n return host;\n }\n\n get #own() {\n return this.#parts.find((part) => !part.plugin);\n }\n\n #changed() {\n this.revision++;\n for (const listener of this.#listeners) listener();\n }\n\n get active(): boolean {\n return this.#parts.length > 0;\n }\n\n get built(): BuiltExtension | undefined {\n return layoutParts(\n this.#parts.map((part) => ({\n name: part.name,\n plugin: part.plugin,\n built: part.host.built,\n })),\n `?v=${this.revision}`,\n );\n }\n\n get error(): string | undefined {\n const errors = this.#parts.flatMap((part) =>\n part.host.error\n ? [\n this.#parts.length === 1 && !part.plugin\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 === ASSETS.extension) return this.built?.js;\n if (name === ASSETS.extensionCss) return this.built?.css;\n // From the layout, or the `brick build` folder the app's names.\n return this.built?.parts?.[name];\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 const own = this.#own;\n if (own && isBuiltFolder(own.path)) return;\n const wanted = pluginDashboards(plugins);\n const current = this.#parts.filter((part) => part.plugin);\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(own ? 1 : 0);\n const loads = [...wanted].map(([path, name]) =>\n this.#add(name, path, true).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 this.#own?.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 { 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 { bundleComponents } from \"./dashboard-extension\";\nimport {\n decode,\n docsFileUrl,\n docsHref,\n isExternalHref,\n type DocsInfo,\n type DocsNode,\n type DocsPage,\n type DocsSearchHit,\n type DocsSnapshot,\n type DocsTree,\n} from \"./dashboard-protocol\";\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\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;\n/** What the docs are called when their folder does not name them. */\nconst DEFAULT_TITLE = \"Docs\";\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 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 (isExternalHref(href) || href.startsWith(\"#\")) 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 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 = DEFAULT_TITLE;\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 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 : DEFAULT_TITLE;\n this.revision++;\n for (const listener of this.#listeners) listener();\n }\n\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 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 = docsFileUrl(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 = docsFileUrl(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 anchor = hashAt >= 0 ? decode(href.slice(hashAt + 1)) : undefined;\n const target =\n (hashAt >= 0 ? href.slice(0, hashAt) : href).split(\"?\")[0] ?? \"\";\n const route = (slug: string) =>\n docsHref(slug ? slug.split(\"/\") : [], anchor);\n if (isExternalHref(href) || !target) 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/** 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) || DEFAULT_TITLE,\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 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 #publish: (docs: DocsSnapshot | null) => void;\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(\n publish: (docs: DocsSnapshot | null) => void,\n warn: (message: string) => void,\n ) {\n this.#publish = publish;\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.#publish(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.#publish(\n opened.status === \"missing\"\n ? { status: \"missing\", packages: opened.packages, message }\n : { status: \"error\", message },\n );\n return;\n }\n this.#docs = opened.docs;\n this.#stopListening = opened.docs.onChange(() =>\n this.#publish(opened.docs.snapshot()),\n );\n this.#publish(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 {\n SPAN,\n type FacetValue,\n type HistoryFacets,\n type HistorySummary,\n type HistoryTrace,\n type Outcome,\n type TraceSummary,\n type SpanEventRecord,\n type VolumeBucket,\n} from \"./dashboard-protocol\";\n\n/*\n * The request log's rules, as plain functions over rows: what a request's\n * outcome is, which rows a filter keeps, and the counts the log shows. The\n * page runs them over live requests; stored history runs the same rules in SQL\n * (dev-history.ts), and a test keeps the two in step.\n */\n\n/** A response status at or above this is a server error; below it and at or above `CLIENT_ERROR`, a client error. */\nexport const SERVER_ERROR = 500;\nexport const CLIENT_ERROR = 400;\n\nexport function outcomeOf(\n row: Pick<TraceSummary, \"status\" | \"httpStatus\">,\n): Outcome {\n const http = row.httpStatus ?? 0;\n if (row.status === \"error\" || http >= SERVER_ERROR) return \"server\";\n if (http >= CLIENT_ERROR) return \"client\";\n return \"ok\";\n}\n\nexport function endpointOf(\n trace: Pick<TraceSummary, \"method\" | \"route\" | \"name\">,\n): string {\n return trace.method && trace.route\n ? `${trace.method} ${trace.route}`\n : trace.name;\n}\n\n/** A live request as a log row; the same shape the history API returns. */\nexport function toRow(trace: TraceSummary): HistoryTrace {\n const { spans: _spans, ...row } = trace;\n return { ...row, endpoint: endpointOf(trace) };\n}\n\nexport const OUTCOMES: readonly Outcome[] = [\"ok\", \"client\", \"server\"];\n\n/** The filters of the request log, over a window, a page at a time. */\nexport interface HistoryQuery extends RowFilters {\n from: number;\n to: number;\n limit?: number;\n offset?: number;\n}\n\n/** A history query as the query string the history API takes. */\nexport function encodeHistoryQuery(query: HistoryQuery): URLSearchParams {\n const params = new URLSearchParams({\n from: String(query.from),\n to: String(query.to),\n });\n for (const endpoint of query.endpoints ?? [])\n params.append(\"endpoint\", endpoint);\n for (const method of query.methods ?? []) params.append(\"method\", method);\n for (const service of query.services ?? []) params.append(\"service\", service);\n for (const outcome of query.outcomes ?? []) params.append(\"outcome\", outcome);\n if (query.minMs !== undefined) params.set(\"minMs\", String(query.minMs));\n if (query.query) params.set(\"q\", query.query);\n if (query.sort && query.sort !== \"recent\") params.set(\"sort\", query.sort);\n if (query.limit !== undefined) params.set(\"limit\", String(query.limit));\n if (query.offset !== undefined) params.set(\"offset\", String(query.offset));\n return params;\n}\n\n/** The history query in a query string, parsed defensively: what `encodeHistoryQuery` wrote. */\nexport function decodeHistoryQuery(\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) ? Math.trunc(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 // A week back by default.\n from: integer(\"from\") ?? to - 7 * 86_400_000,\n endpoints: all(\"endpoint\"),\n methods: all(\"method\"),\n services: all(\"service\"),\n outcomes: all(\"outcome\")?.filter((value): value is Outcome =>\n OUTCOMES.includes(value as Outcome),\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/** A filter groups its values with OR; separate filters combine with AND. */\nexport interface RowFilters {\n endpoints?: string[];\n methods?: string[];\n services?: string[];\n outcomes?: Outcome[];\n /** Only requests at least this slow, in milliseconds. */\n minMs?: number;\n /** Matches the endpoint, path, span name, action or failure message. */\n query?: string;\n sort?: \"recent\" | \"slowest\";\n}\n\nexport type Facet = keyof HistoryFacets;\n\n/** The fields the search box looks in. */\nexport const SEARCHED: readonly (keyof HistoryTrace)[] = [\n \"endpoint\",\n \"path\",\n \"name\",\n \"action\",\n \"message\",\n];\n\n/** Whether `row` passes the filters, leaving out `skip` when counting its facet. */\nexport function matches(\n row: HistoryTrace,\n filters: RowFilters,\n skip?: Facet,\n): boolean {\n const anyOf = (facet: Facet, values: string[] | undefined, value?: string) =>\n skip === facet ||\n !values?.length ||\n (value !== undefined && values.includes(value));\n if (!anyOf(\"endpoint\", filters.endpoints, row.endpoint)) return false;\n if (!anyOf(\"method\", filters.methods, row.method)) return false;\n if (!anyOf(\"service\", filters.services, row.service)) return false;\n if (!anyOf(\"outcome\", filters.outcomes, outcomeOf(row))) return false;\n if (\n filters.minMs !== undefined &&\n filters.minMs > 0 &&\n (row.durationMs ?? 0) < filters.minMs\n )\n return false;\n const needle = filters.query?.trim().toLowerCase();\n if (needle)\n return SEARCHED.some((field) =>\n String(row[field] ?? \"\")\n .toLowerCase()\n .includes(needle),\n );\n return true;\n}\n\n/** Newest first, or slowest first and then newest. */\nexport function compareRows(\n sort: RowFilters[\"sort\"],\n): (a: HistoryTrace, b: HistoryTrace) => number {\n return sort === \"slowest\"\n ? (a, b) =>\n (b.durationMs ?? 0) - (a.durationMs ?? 0) || b.startMs - a.startMs\n : (a, b) => b.startMs - a.startMs;\n}\n\nexport function applyFilters(\n rows: HistoryTrace[],\n filters: RowFilters,\n): HistoryTrace[] {\n return rows\n .filter((row) => matches(row, filters))\n .sort(compareRows(filters.sort));\n}\n\n/** The most values a facet lists. */\nexport const MAX_FACET_VALUES = 30;\n\nconst FACET_VALUE: Record<Facet, (row: HistoryTrace) => string | undefined> = {\n outcome: outcomeOf,\n method: (row) => row.method,\n service: (row) => row.service,\n endpoint: (row) => row.endpoint,\n};\n\n/** Counts for each filter, as if that filter were not applied. */\nexport function computeFacets(\n rows: HistoryTrace[],\n filters: RowFilters,\n): HistoryFacets {\n const count = (facet: Facet): FacetValue[] => {\n const counts = new Map<string, number>();\n for (const row of rows) {\n if (!matches(row, filters, facet)) continue;\n const value = FACET_VALUE[facet](row);\n if (value !== undefined) counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n return [...counts.entries()]\n .map(([value, total]) => ({ value, count: total }))\n .sort(\n (a, b) =>\n b.count - a.count ||\n (a.value < b.value ? -1 : a.value > b.value ? 1 : 0),\n )\n .slice(0, MAX_FACET_VALUES);\n };\n return {\n outcome: count(\"outcome\"),\n method: count(\"method\"),\n service: count(\"service\"),\n endpoint: count(\"endpoint\"),\n };\n}\n\n/** The width of each of `count` buckets across [from, to]: whole milliseconds, at least one. */\nexport const bucketSize = (from: number, to: number, count: number): number =>\n Math.max(Math.ceil((to - from) / count), 1);\n\n/** Count rows into `count` equal time buckets across [from, to], by outcome. */\nexport function bucketRows(\n rows: HistoryTrace[],\n from: number,\n to: number,\n count: number,\n): VolumeBucket[] {\n const size = bucketSize(from, to, count);\n const buckets: VolumeBucket[] = Array.from({ length: count }, (_, index) => ({\n start: from + index * size,\n ok: 0,\n client: 0,\n server: 0,\n }));\n for (const row of rows) {\n if (row.startMs < from || row.startMs > to) continue;\n const index = Math.floor((row.startMs - from) / size);\n buckets[Math.min(index, count - 1)]![outcomeOf(row)] += 1;\n }\n return buckets;\n}\n\n/** Linear-interpolated percentile of an ascending list; 0 for an empty list. */\nexport function 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 (\n sorted[lower]! + (sorted[upper]! - sorted[lower]!) * (position - lower)\n );\n}\n\n/** The numbers for the cards at the top of the log, for these requests. */\nexport function summarizeRows(rows: HistoryTrace[]): HistorySummary {\n let clientErrors = 0;\n let serverErrors = 0;\n const durations: number[] = [];\n for (const row of rows) {\n const outcome = outcomeOf(row);\n if (outcome === \"client\") clientErrors += 1;\n if (outcome === \"server\") serverErrors += 1;\n if (row.durationMs !== undefined) durations.push(row.durationMs);\n }\n durations.sort((a, b) => a - b);\n return {\n total: rows.length,\n clientErrors,\n serverErrors,\n medianMs: percentile(durations, 0.5),\n p95Ms: percentile(durations, 0.95),\n };\n}\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 [\n new Date(trace.startMs).toISOString(),\n trace.method,\n trace.route,\n trace.path,\n trace.httpStatus ?? trace.status,\n outcomeOf(trace),\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\n/** A string attribute, or undefined when it is missing or of another type. */\nexport function 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\n/** The attributes of the exception a span recorded, if it recorded one. */\nexport function findException(\n events: SpanEventRecord[],\n): Attributes | undefined {\n return events.find((event) => event.name === SPAN.exceptionEvent)?.attributes;\n}\n\n/** The span that ran the request's action, when it ran one. */\nexport function actionSpan<T extends { name: string }>(\n spans: readonly T[],\n): T | undefined {\n return spans.find((span) => span.name.startsWith(SPAN.actionPrefix));\n}\n","import {\n ASSETS,\n assetUrl,\n SHARED_MODULES,\n THEME_STORAGE_KEY,\n} from \"./dashboard-protocol\";\n\nconst IMPORT_MAP = JSON.stringify({\n imports: Object.fromEntries(\n SHARED_MODULES.map((module) => [module.specifier, assetUrl(module.file)]),\n ),\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 mode?: \"dev\" | \"production\";\n } = {},\n): string {\n const { extension, theme, mode } = 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>${mode === \"production\" ? \"Brick\" : \"Brick dev\"}</title>\n<link rel=\"icon\" href=\"data:,\">\n<script>\n(function () {\n try {\n var theme = localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)});\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=\"${assetUrl(ASSETS.appCss)}\">\n${extension?.css ? `<link rel=\"stylesheet\" href=\"${assetUrl(ASSETS.extensionCss)}${version}\">\\n` : \"\"}${theme ? `<link rel=\"stylesheet\" href=\"${assetUrl(ASSETS.theme)}\" data-brick-theme>\\n` : \"\"}${extension ? `<meta name=\"brick-extension\" data-revision=\"${extension.revision}\"${extension.js ? ` data-src=\"${assetUrl(ASSETS.extension)}${version}\"` : \"\"}>\\n` : \"\"}<script type=\"importmap\">\n${IMPORT_MAP}\n</script>\n</head>\n<body>\n<div id=\"root\"></div>\n<script type=\"module\" src=\"${assetUrl(ASSETS.app)}\"></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. */\nconst AUTHORIZE_TIMEOUT_MS = 5000;\n\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 protocol the client used: https when a proxy in front terminated TLS and says so. */\nexport function requestProtocol(request: IncomingMessage): \"http\" | \"https\" {\n const forwarded = request.headers[\"x-forwarded-proto\"];\n return (Array.isArray(forwarded) ? forwarded[0] : forwarded)\n ?.split(\",\")[0]\n ?.trim() === \"https\"\n ? \"https\"\n : \"http\";\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 protocol = requestProtocol(request);\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 { 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 { ConfigError } from \"./config\";\nimport type { DevDocs } from \"./dev-docs\";\nimport type { DevHistory } from \"./dev-history\";\nimport { decodeHistoryQuery, type HistoryQuery } from \"./dashboard-query\";\nimport type { DevTelemetryStore } from \"./dev-telemetry-store\";\nimport { dashboardShell } from \"./dev-dashboard-shell\";\nimport type { DashboardAuth } from \"@brickkit/core\";\nimport {\n createAccess,\n isLoopbackHost,\n requestProtocol,\n} from \"./dashboard-access\";\nimport {\n ASSETS,\n CSRF_HEADER,\n CSRF_VALUE,\n DOCS_PATHS,\n INSPECTOR_TOKEN_HEADER,\n matchRoute,\n ROUTES,\n type DashboardEvents,\n type DashboardSnapshot,\n type HistoryResponses,\n type IngestPayload,\n type RouteName,\n} from \"./dashboard-protocol\";\nimport {\n assetsDirectory,\n DashboardExtensions,\n type PluginDashboard,\n themeCss,\n type DashboardExtensionOptions,\n} from \"./dashboard-extension\";\n\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\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 the routes marked `production`, 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 /** How the host's user picks another port, added when the port is taken. */\n portHint?: 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 ConfigError(\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 route = matchRoute(request.method, url.pathname);\n if (route === \"health\") {\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 (!route || (production && !servedInProduction(route))) {\n send(response, 404, \"Not found\");\n return;\n }\n if (\n \"csrf\" in ROUTES[route] &&\n request.headers[CSRF_HEADER] !== CSRF_VALUE\n ) {\n send(response, 403, \"Forbidden\");\n return;\n }\n await handlers[route](request, response, url);\n }\n\n function servedInProduction(route: RouteName): boolean {\n const served: boolean | \"extension\" = ROUTES[route].production;\n return served === \"extension\" ? Boolean(extension?.active) : served;\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 type Handler = (\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ) => void | Promise<void>;\n\n const handlers: Record<Exclude<RouteName, \"health\">, Handler> = {\n shell: (_request, response) =>\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 mode: production ? \"production\" : \"dev\",\n }),\n {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n },\n ),\n assets(_request, response, url) {\n const name = url.pathname.slice(ROUTES.assets.path.length + 1);\n // The project's own files, kept in memory beside the dashboard's.\n const own = name === ASSETS.theme ? theme : extension?.asset(name);\n if (own !== undefined)\n send(response, 200, own, {\n \"content-type\": assetType(name),\n \"cache-control\": \"no-store\",\n });\n else serveAsset(response, name);\n },\n app,\n state: (_request, response) => json(response, snapshot()),\n events: eventStream,\n history(_request, response, url) {\n if (options.history)\n history(options.history, url.pathname, url.searchParams, response);\n else send(response, 404, \"Not found\");\n },\n docs: (_request, response, url) =>\n docsRoute(response, url.pathname, url.searchParams),\n openapi: (_request, response) =>\n json(response, options.store.apiDocuments()),\n proxy,\n workflows(request, response, url) {\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 frameOnlyHere(response);\n return inspector(request, response, url);\n },\n schedules: (request, response, url) => inspector(request, response, url),\n ingest,\n restart(request, response) {\n if (!options.restart) {\n send(response, 404, \"Not found\");\n return;\n }\n options.restart();\n send(response, 202, \"\");\n },\n };\n\n function snapshot(): DashboardSnapshot {\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 async function ingest(\n request: IncomingMessage,\n response: ServerResponse,\n ): Promise<void> {\n const body = await readBytes(request, MAX_INGEST_BYTES);\n if (!body) {\n tooLarge(response);\n return;\n }\n let payload: IngestPayload | null;\n try {\n payload = JSON.parse(Buffer.from(body).toString(\"utf8\")) as IngestPayload;\n } catch {\n payload = null;\n }\n if (payload === null || typeof payload !== \"object\") {\n send(response, 400, \"Bad request\");\n return;\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 }\n\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 try {\n if (pathname === DOCS_PATHS.info) return json(response, docs.info());\n if (pathname === DOCS_PATHS.search)\n return json(response, await docs.search(params.get(\"q\") ?? \"\"));\n if (pathname === DOCS_PATHS.components) {\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 = DOCS_PATHS.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\n ? json(response, page)\n : send(response, 404, \"No such page.\");\n }\n const filePrefix = `${DOCS_PATHS.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 * 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 and schedules are not being served. The app may be restarting, or it may have neither workflows nor schedules.\",\n { \"content-type\": \"text/plain; charset=utf-8\" },\n );\n return;\n }\n if (!isBodyless(request) && !fromOwnPage(request)) {\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 if (!fromOwnPage(request)) {\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 frameOnlyHere(response);\n await forward(\n request,\n response,\n `${new URL(appUrl).origin}${url.pathname.slice(ROUTES.app.path.length) || \"/\"}${url.search}`,\n (headers) => {\n if (access) headers.delete(\"authorization\");\n },\n \"Could not reach the app.\",\n );\n }\n\n /**\n * Send the request on to `target` and stream its answer back. `body`: the\n * request's body when the caller already read it; else it is streamed.\n */\n async function forward(\n request: IncomingMessage,\n response: ServerResponse,\n target: string,\n adjust: (headers: Headers) => void,\n unreachable: string,\n body?: Uint8Array,\n ): Promise<void> {\n const headers = forwardedHeaders(request);\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 ...(isBodyless(request)\n ? {}\n : body\n ? { body: body as BodyInit }\n : {\n body: Readable.toWeb(request) as unknown as BodyInit,\n duplex: \"half\",\n }),\n } as RequestInit);\n response.writeHead(upstream.status, returnedHeaders(upstream));\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 /**\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 async function proxy(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ): Promise<void> {\n if (!fromOwnPage(request)) {\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 tooLarge(response);\n return;\n }\n const cookie = url.searchParams.get(\"cookie\");\n await forward(\n request,\n response,\n target.href,\n (headers) => {\n if (cookie) headers.set(\"cookie\", cookie);\n },\n \"Could not reach the app.\",\n body,\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 const emit = <K extends keyof DashboardEvents>(\n name: K,\n data: DashboardEvents[K],\n ) => write(`event: ${name}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n emit(\"snapshot\", snapshot());\n const unsubscribe = options.store.subscribe((event) =>\n emit(event.type, event),\n );\n const unwatch = extension?.onChange(() =>\n emit(\"extension\", snapshot().extension),\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 `Brick: dashboard port ${options.port} is unavailable.${options.portHint ? ` ${options.portHint}` : \"\"}`,\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 // Stop buffering; tooLarge() answers and closes the connection.\n request.removeAllListeners(\"data\");\n request.resume();\n resolve(undefined);\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 queries: {\n [K in keyof HistoryResponses]: (query: HistoryQuery) => HistoryResponses[K];\n } = {\n summary: (query) => store.summary(query),\n traces: (query) => store.traces(query),\n facets: (query) => store.facets(query),\n volume: (query) => store.volume(query),\n };\n try {\n const endpoint = pathname.slice(ROUTES.history.path.length + 1);\n if (endpoint === \"\") return json(response, store.info());\n if (endpoint === \"export\") {\n return send(response, 200, store.exportCsv(decodeHistoryQuery(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 if (Object.hasOwn(queries, endpoint))\n return json(\n response,\n queries[endpoint as keyof typeof queries](decodeHistoryQuery(params)),\n );\n const prefix = \"traces/\";\n if (endpoint.startsWith(prefix)) {\n const trace = store.trace(\n decodeURIComponent(endpoint.slice(prefix.length)),\n );\n if (trace) return json(response, trace);\n }\n send(response, 404, \"Not found\");\n } catch (error) {\n // A malformed `%` in the trace id is the caller's mistake.\n if (error instanceof URIError) return send(response, 400, error.message);\n console.error(\"[Brick-TS] A dashboard history query failed:\", error);\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\nconst assetType = (name: string): string =>\n ASSET_TYPES[extname(name)] ?? \"application/octet-stream\";\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\": assetType(name),\n \"cache-control\": \"no-store\",\n }),\n () => send(response, 404, \"Not found\"),\n );\n}\n\nfunction tooLarge(response: ServerResponse): void {\n // Closing after the 413 stops the rest of the upload being read.\n send(response, 413, \"Payload too large\", {\n \"content-type\": \"text/plain; charset=utf-8\",\n connection: \"close\",\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\nfunction json(response: ServerResponse, body: unknown): void {\n send(response, 200, JSON.stringify(body), {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n });\n}\n\nconst isBodyless = (request: IncomingMessage) =>\n request.method === \"GET\" || request.method === \"HEAD\";\n\n/**\n * Whether a request comes from the dashboard's own page, as far as the browser\n * says: the same site, and the same origin as the address it was sent to.\n * Behind a proxy that terminates TLS that address is https.\n */\nfunction fromOwnPage(request: IncomingMessage): boolean {\n const site = request.headers[\"sec-fetch-site\"];\n const origin = request.headers.origin;\n return (\n (site === undefined || site === \"same-origin\") &&\n (origin === undefined ||\n origin === `${requestProtocol(request)}://${request.headers.host}`)\n );\n}\n\nfunction frameOnlyHere(response: ServerResponse): void {\n response.setHeader(\"content-security-policy\", \"frame-ancestors 'self'\");\n response.setHeader(\"x-frame-options\", \"SAMEORIGIN\");\n}\n\n/** The request's headers to send on, without those of this hop or this page. */\nfunction forwardedHeaders(request: IncomingMessage): Headers {\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 return headers;\n}\n\nfunction returnedHeaders(upstream: Response): Record<string, string> {\n const returned: Record<string, string> = {};\n upstream.headers.forEach((value, name) => {\n if (!NOT_RETURNED.has(name)) returned[name] = value;\n });\n return returned;\n}\n","import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n HISTORY_PAGE_SIZE,\n type FacetValue,\n type HistoryFacets,\n type HistoryInfo,\n type HistorySummary,\n type HistoryTrace,\n type Outcome,\n type SpanOutcome,\n type TraceSummary,\n type VolumeBucket,\n} from \"./dashboard-protocol\";\nimport {\n bucketSize,\n CLIENT_ERROR,\n endpointOf,\n MAX_FACET_VALUES,\n percentile,\n SEARCHED,\n SERVER_ERROR,\n tracesToCsv,\n type Facet,\n type HistoryQuery,\n} from \"./dashboard-query\";\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 MAX_LIMIT = 500;\nconst MAX_EXPORT_ROWS = 100_000;\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, options.warn);\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\n/** Each row's outcome, by the rules of `outcomeOf`. */\nconst OUTCOME_CASE = `CASE\n WHEN status = 'error' OR http_status >= ${SERVER_ERROR} THEN 'server'\n WHEN http_status >= ${CLIENT_ERROR} THEN 'client'\n ELSE 'ok' END`;\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\") anyOf(OUTCOME_CASE, query.outcomes);\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 `(${SEARCHED.map((column) => `${column} LIKE ? ESCAPE '\\\\'`).join(\" OR \")})`,\n );\n params.push(...SEARCHED.map(() => pattern));\n }\n return { sql: clauses.join(\" AND \"), params };\n}\n\nconst orderSql = (sort: HistoryQuery[\"sort\"]) =>\n sort === \"slowest\" ? \"duration_ms DESC, start_ms DESC\" : \"start_ms DESC\";\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 readonly #warn?: (message: string) => void;\n /** Failure kinds already reported: one warning each, not one per batch. */\n readonly #warned = new Set<string>();\n\n constructor(\n database: Database,\n days: number,\n warn?: (message: string) => void,\n ) {\n this.#database = database;\n this.days = days;\n this.#warn = warn;\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 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 endpointOf(trace),\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 (error) {\n // A failed write loses a batch of history; it must not break the app.\n this.#warnOnce(\"save requests to\", error);\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 (error) {\n // Pruning is housekeeping; try again next time.\n this.#warnOnce(\"prune\", error);\n }\n }\n\n #warnOnce(action: string, error: unknown): void {\n if (this.#warned.has(action)) return;\n this.#warned.add(action);\n const reason = error instanceof Error ? error.message : String(error);\n this.#warn?.(\n `[Brick-TS] Could not ${action} the request history (${reason}).`,\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 ?? HISTORY_PAGE_SIZE, 1),\n MAX_LIMIT,\n );\n const offset = Math.max(query.offset ?? 0, 0);\n const rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} 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 = bucketSize(query.from, query.to, buckets);\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 rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} LIMIT ?`,\n )\n .all(...params, MAX_EXPORT_ROWS);\n return tracesToCsv(rows.map(toHistoryTrace));\n }\n\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","import type { Attributes } from \"@opentelemetry/api\";\nimport type { ApiDocument, ArchitectureSchema } from \"@brickkit/core\";\nimport {\n ATTR,\n LIVE_LIMITS,\n type ApiSnapshot,\n type ArchitectureSnapshot,\n type DevTelemetryEvent,\n type DevTelemetrySnapshot,\n type DocsSnapshot,\n type FailureSummary,\n type ReloadSummary,\n type SerializedError,\n type SpanEndRecord,\n type SpanOutcome,\n type SpanStartRecord,\n type TelemetryRecord,\n type TraceSpan,\n type TraceSummary,\n type WorkerErrorPhase,\n} from \"./dashboard-protocol\";\nimport {\n actionSpan,\n CLIENT_ERROR,\n findException,\n outcomeOf,\n stringAttribute,\n} from \"./dashboard-query\";\n\nconst LIMITS = { ...LIVE_LIMITS, spansPerTrace: 500 };\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: { saveTrace(trace: TraceSummary): void } | undefined;\n #architecture: ArchitectureSnapshot | null = null;\n #api: ApiSnapshot | null = null;\n #docs: DocsSnapshot | null = null;\n #inspector: { port: number; token: string; workflows: boolean } | undefined;\n #apiDocuments: ApiDocument[] = [];\n #sequence = 0;\n #generation = 0;\n\n /** Finished requests are also kept in `history`, when given. */\n constructor(\n options: { history?: { saveTrace(trace: TraceSummary): void } } = {},\n ) {\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 and schedules, or\n * `undefined` when it stops. The address stays here: the snapshot says only\n * whether there is a workflow inspector.\n */\n setInspector(\n target: { port: number; token: string; workflows: boolean } | undefined,\n ): void {\n this.#inspector = target;\n this.#emit({ type: \"inspector\", inspector: Boolean(target?.workflows) });\n }\n\n /** Where the dashboard proxies the workflow inspector and schedules, when the app serves them. */\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?.workflows),\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, ATTR.httpMethod);\n entry.route = stringAttribute(record.attributes, ATTR.httpRoute);\n entry.path = stringAttribute(record.attributes, ATTR.urlPath);\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, ATTR.errorCode);\n if (code !== undefined) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code,\n message:\n stringAttribute(exception, ATTR.exceptionMessage) ??\n stringAttribute(record.attributes, ATTR.errorMessage) ??\n code,\n status: numberAttribute(record.attributes, ATTR.errorStatus),\n stack: stringAttribute(exception, ATTR.exceptionStack),\n traceId: entry.traceId,\n route: entry.route,\n service: stringAttribute(record.attributes, ATTR.service),\n action: stringAttribute(record.attributes, ATTR.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(record.attributes, ATTR.httpStatus);\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 outcome = outcomeOf({\n status: record.status === \"error\" ? \"error\" : \"ok\",\n httpStatus: entry.httpStatus,\n });\n entry.status = outcome === \"server\" ? \"error\" : \"ok\";\n if (outcome !== \"ok\" && !entry.failureRecorded) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code: status >= CLIENT_ERROR ? `HTTP_${status}` : \"UNHANDLED_ERROR\",\n message:\n stringAttribute(exception, ATTR.exceptionMessage) ??\n record.statusMessage ??\n describeResponse(entry, status),\n status: entry.httpStatus,\n stack: stringAttribute(exception, ATTR.exceptionStack),\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 (error) {\n this.#listeners.delete(listener);\n console.warn(\n \"[Brick-TS] A dashboard client stopped receiving updates:\",\n error,\n );\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 action = actionSpan(spans);\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(action?.attributes, ATTR.service),\n action: stringAttribute(action?.attributes, ATTR.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 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","import {\n ConfigError,\n DEFAULT_DASHBOARD_PORT,\n DEFAULT_HISTORY_DAYS,\n} from \"./config\";\nimport { DocsHost } from \"./dev-docs\";\nimport {\n startDevDashboard,\n type DevDashboard,\n type DevDashboardOptions,\n} from \"./dev-dashboard\";\nimport { openHistory } from \"./dev-history\";\nimport { DevTelemetryStore } from \"./dev-telemetry-store\";\n\nexport interface DashboardHost extends DevDashboard {\n /** Where the host records what the app reports. */\n readonly store: DevTelemetryStore;\n /** The app's developer documentation, when `docs` was asked for. */\n readonly docs?: DocsHost;\n}\n\n/**\n * Open the dashboard with its history, store and docs, for `brick dev`, the\n * Vite plugin and the production dashboard alike. When it cannot start, what\n * it opened is closed, `warn` says why, and the host runs on without it. A\n * configuration mistake (a bad theme, a public host without auth) throws.\n */\nexport async function openDashboard(\n options: Omit<DevDashboardOptions, \"store\" | \"history\" | \"docs\" | \"port\"> & {\n /** Default 9400. */\n port?: number;\n /** The project folder; history is kept in `.brick/` inside it. */\n directory: string;\n /** Days of requests to keep on disk; zero for none. Default 90. */\n historyDays?: number;\n warn: (message: string) => void;\n /** Serve the app's developer documentation (the Docs tab). */\n docs?: boolean;\n },\n): Promise<DashboardHost | undefined> {\n const {\n port = DEFAULT_DASHBOARD_PORT,\n directory,\n historyDays = DEFAULT_HISTORY_DAYS,\n warn,\n docs: withDocs,\n ...rest\n } = options;\n const history = await openHistory({ directory, days: historyDays, warn });\n const store = new DevTelemetryStore({ history });\n const docs = withDocs\n ? new DocsHost((docs) => store.setDocs(docs), warn)\n : undefined;\n let server: DevDashboard;\n try {\n server = await startDevDashboard({\n ...rest,\n port,\n store,\n history,\n docs: docs && (() => docs.current),\n });\n } catch (error) {\n docs?.close();\n history?.close();\n if (error instanceof ConfigError) throw error;\n const reason = error instanceof Error ? error.message : String(error);\n warn(`[Brick-TS] ${reason} Continuing without the dashboard.`);\n return undefined;\n }\n return {\n port: server.port,\n store,\n docs,\n setPluginExtensions: (plugins) => server.setPluginExtensions(plugins),\n stop() {\n server.stop();\n docs?.close();\n history?.close();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA0CA,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,6BAAa,IAAI,IAAI;CAAC;CAAS;CAAQ;CAAU;AAAO,CAAC;AAC/D,MAAM,4BAAY,IAAI,IAAI,CAAC,QAAQ,MAAM,CAAC;AAC1C,MAAM,SAAS,IAAI,IAAY,YAAY;;AAG3C,SAAS,SAAS,OAAe,OAAwB;CACvD,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,YAAY,KAAK,KAAK,GACtE,MAAM,IAAI,YACR,0BAA0B,MAAM,8CAClC;CACF,OAAO,MAAM,KAAK;AACpB;;;;;AAMA,SAAgB,SAAS,OAA2C;CAClE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AI,UAAU,SAAS,MAAM,QAAQ,IAAI,GAAG,IAAI,IAChD,KAAA;CACJ,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,kBAAkB;GAC/B,GAAG;GACH;GACA;GACA;GACA,MAAM,eAAe,KAAK;EAC5B,CAAC;CACH,SAAS,OAAO;EACd,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,IAAI,iBAAiB,aAAa,MAAM;EAExC,KAAK,cADU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAC1C,mCAAmC;EAC7D;CACF;CACA,OAAO;EACL,MAAM,OAAO;EACb;EACA;EACA,sBAAsB,YAAY,OAAO,oBAAoB,OAAO;EACpE,OAAO;GACL,OAAO,KAAK;GACZ,MAAM,MAAM;GACZ,SAAS,MAAM;EACjB;CACF;AACF"}
1
+ {"version":3,"file":"dashboard-host.js","names":[],"sources":["../src/dashboard-extension.ts","../src/dev-docs.ts","../src/dashboard-query.ts","../src/dev-dashboard-shell.ts","../src/dashboard-access.ts","../src/dev-dashboard.ts","../src/dev-history.ts","../src/dev-telemetry-store.ts","../src/dashboard-host.ts"],"sourcesContent":["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 { ConfigError } from \"./config\";\nimport {\n ASSETS,\n SHARED_MODULES,\n type ExtensionPart,\n} from \"./dashboard-protocol\";\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 ConfigError(\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 ConfigError(\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 ConfigError(\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 ConfigError(\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\nconst SHARED = SHARED_MODULES.map((module) => module.specifier);\n\n/** Bundle a module of React components for the dashboard to import (an extension, or the docs' components), with its shared modules left to the page. */\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 dashboard module produced no output.\");\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 /** The `extension-N.js` files `js` lists, by name. */\n parts?: Record<string, string>;\n}\n\n/** The `warn` functions already told that tailwindcss is missing: once each, not once per rebuild. */\nconst warnedTailwind = new WeakSet<(message: string) => void>();\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 }\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.has(warn))\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.add(warn);\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 warn = (message: string) => console.warn(message);\n const built = await Promise.all(\n parts.map((part) =>\n buildDashboardExtension(part.path, { warn }).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 writeBuiltFolder(\n outdir,\n layoutParts(\n parts.map((part, index) => ({ ...part, built: built[index] })),\n )!,\n );\n return true;\n}\n\n/** Whether `path` is a folder `brick build` wrote, which is served as it is. */\nconst isBuiltFolder = (path: string): boolean =>\n existsSync(join(path, ASSETS.extension));\n\n/** Write the extensions as `layoutParts` lays them out; `readBuiltFolder` reads them back. */\nasync function writeBuiltFolder(\n outdir: string,\n layout: BuiltExtension,\n): Promise<void> {\n await mkdir(outdir, { recursive: true });\n await writeFile(join(outdir, ASSETS.extension), layout.js);\n await writeFile(join(outdir, ASSETS.extensionCss), layout.css);\n for (const [name, js] of Object.entries(layout.parts ?? {}))\n await writeFile(join(outdir, name), js);\n}\n\nasync function readBuiltFolder(path: string): Promise<BuiltExtension> {\n const css = join(path, ASSETS.extensionCss);\n const parts: Record<string, string> = {};\n for (const name of await readdir(path))\n if (/^extension-\\d+\\.js$/.test(name))\n parts[name] = await readFile(join(path, name), \"utf8\");\n return {\n js: await readFile(join(path, ASSETS.extension), \"utf8\"),\n css: existsSync(css) ? await readFile(css, \"utf8\") : \"\",\n parts,\n };\n}\n\n/**\n * How the extensions are served, by `brick dev` and from a `brick build`\n * folder alike. The app's alone is served as it is. Otherwise each that built\n * is `extension-<index>.js`, `extension.js` lists them for the page to load\n * and merge, and their styles are served together. `version` is added to each\n * part's address, so a rebuilt one is fetched again.\n */\nfunction layoutParts(\n parts: readonly {\n name: string;\n plugin: boolean;\n built: BuiltExtension | undefined;\n }[],\n version = \"\",\n): BuiltExtension | undefined {\n if (parts.length === 1 && !parts[0]!.plugin) return parts[0]!.built;\n const built = parts.flatMap((part, index) =>\n part.built\n ? [{ ...part, built: part.built, file: `extension-${index}.js` }]\n : [],\n );\n if (!built.length) return undefined;\n return {\n js: extensionManifest(\n built.map((part) => ({\n name: part.name,\n src: `./${part.file}${version}`,\n plugin: part.plugin,\n })),\n ),\n css: built.map((part) => part.built.css).join(\"\"),\n parts: Object.fromEntries(built.map((part) => [part.file, part.built.js])),\n };\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 if (isBuiltFolder(this.#path)) {\n this.built = await readBuiltFolder(this.#path);\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 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 lists them,\n * and the page imports each apart and merges them (`mergeExtensions` there).\n */\nexport function extensionManifest(parts: readonly ExtensionPart[]): string {\n return `export const parts = ${JSON.stringify(parts)};\\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 /** The app's own first, when it has one, then its plugins'. */\n readonly #parts: {\n name: string;\n path: string;\n plugin: boolean;\n host: DashboardExtensionHost;\n }[] = [];\n revision = 0;\n\n constructor(path: string | undefined, warn: (message: string) => void) {\n this.#warn = warn;\n if (path) this.#add(\"app\", path, false);\n }\n\n #add(name: string, path: string, plugin: boolean) {\n const host = new DashboardExtensionHost(path, this.#warn);\n host.onChange(() => this.#changed());\n this.#parts.push({ name, path: resolve(path), plugin, host });\n return host;\n }\n\n get #own() {\n return this.#parts.find((part) => !part.plugin);\n }\n\n #changed() {\n this.revision++;\n for (const listener of this.#listeners) listener();\n }\n\n get active(): boolean {\n return this.#parts.length > 0;\n }\n\n get built(): BuiltExtension | undefined {\n return layoutParts(\n this.#parts.map((part) => ({\n name: part.name,\n plugin: part.plugin,\n built: part.host.built,\n })),\n `?v=${this.revision}`,\n );\n }\n\n get error(): string | undefined {\n const errors = this.#parts.flatMap((part) =>\n part.host.error\n ? [\n this.#parts.length === 1 && !part.plugin\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 === ASSETS.extension) return this.built?.js;\n if (name === ASSETS.extensionCss) return this.built?.css;\n // From the layout, or the `brick build` folder the app's names.\n return this.built?.parts?.[name];\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 const own = this.#own;\n if (own && isBuiltFolder(own.path)) return;\n const wanted = pluginDashboards(plugins);\n const current = this.#parts.filter((part) => part.plugin);\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(own ? 1 : 0);\n const loads = [...wanted].map(([path, name]) =>\n this.#add(name, path, true).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 this.#own?.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 { 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 { bundleComponents } from \"./dashboard-extension\";\nimport {\n decode,\n docsFileUrl,\n docsHref,\n isExternalHref,\n type DocsInfo,\n type DocsNode,\n type DocsPage,\n type DocsSearchHit,\n type DocsSnapshot,\n type DocsTree,\n} from \"./dashboard-protocol\";\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\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;\n/** What the docs are called when their folder does not name them. */\nconst DEFAULT_TITLE = \"Docs\";\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 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 (isExternalHref(href) || href.startsWith(\"#\")) 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 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 = DEFAULT_TITLE;\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 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 : DEFAULT_TITLE;\n this.revision++;\n for (const listener of this.#listeners) listener();\n }\n\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 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 = docsFileUrl(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 = docsFileUrl(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 anchor = hashAt >= 0 ? decode(href.slice(hashAt + 1)) : undefined;\n const target =\n (hashAt >= 0 ? href.slice(0, hashAt) : href).split(\"?\")[0] ?? \"\";\n const route = (slug: string) =>\n docsHref(slug ? slug.split(\"/\") : [], anchor);\n if (isExternalHref(href) || !target) 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/** 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) || DEFAULT_TITLE,\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 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 #publish: (docs: DocsSnapshot | null) => void;\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(\n publish: (docs: DocsSnapshot | null) => void,\n warn: (message: string) => void,\n ) {\n this.#publish = publish;\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.#publish(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.#publish(\n opened.status === \"missing\"\n ? { status: \"missing\", packages: opened.packages, message }\n : { status: \"error\", message },\n );\n return;\n }\n this.#docs = opened.docs;\n this.#stopListening = opened.docs.onChange(() =>\n this.#publish(opened.docs.snapshot()),\n );\n this.#publish(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 {\n SPAN,\n type FacetValue,\n type HistoryFacets,\n type HistorySummary,\n type HistoryTrace,\n type Outcome,\n type TraceSummary,\n type SpanEventRecord,\n type VolumeBucket,\n} from \"./dashboard-protocol\";\n\n/*\n * The request log's rules, as plain functions over rows: what a request's\n * outcome is, which rows a filter keeps, and the counts the log shows. The\n * page runs them over live requests; stored history runs the same rules in SQL\n * (dev-history.ts), and a test keeps the two in step.\n */\n\n/** A response status at or above this is a server error; below it and at or above `CLIENT_ERROR`, a client error. */\nexport const SERVER_ERROR = 500;\nexport const CLIENT_ERROR = 400;\n\nexport function outcomeOf(\n row: Pick<TraceSummary, \"status\" | \"httpStatus\">,\n): Outcome {\n const http = row.httpStatus ?? 0;\n if (row.status === \"error\" || http >= SERVER_ERROR) return \"server\";\n if (http >= CLIENT_ERROR) return \"client\";\n return \"ok\";\n}\n\nexport function endpointOf(\n trace: Pick<TraceSummary, \"method\" | \"route\" | \"name\">,\n): string {\n return trace.method && trace.route\n ? `${trace.method} ${trace.route}`\n : trace.name;\n}\n\n/** A live request as a log row; the same shape the history API returns. */\nexport function toRow(trace: TraceSummary): HistoryTrace {\n const { spans: _spans, ...row } = trace;\n return { ...row, endpoint: endpointOf(trace) };\n}\n\nexport const OUTCOMES: readonly Outcome[] = [\"ok\", \"client\", \"server\"];\n\n/** The filters of the request log, over a window, a page at a time. */\nexport interface HistoryQuery extends RowFilters {\n from: number;\n to: number;\n limit?: number;\n offset?: number;\n}\n\n/** A history query as the query string the history API takes. */\nexport function encodeHistoryQuery(query: HistoryQuery): URLSearchParams {\n const params = new URLSearchParams({\n from: String(query.from),\n to: String(query.to),\n });\n for (const endpoint of query.endpoints ?? [])\n params.append(\"endpoint\", endpoint);\n for (const method of query.methods ?? []) params.append(\"method\", method);\n for (const service of query.services ?? []) params.append(\"service\", service);\n for (const outcome of query.outcomes ?? []) params.append(\"outcome\", outcome);\n if (query.minMs !== undefined) params.set(\"minMs\", String(query.minMs));\n if (query.query) params.set(\"q\", query.query);\n if (query.sort && query.sort !== \"recent\") params.set(\"sort\", query.sort);\n if (query.limit !== undefined) params.set(\"limit\", String(query.limit));\n if (query.offset !== undefined) params.set(\"offset\", String(query.offset));\n return params;\n}\n\n/** The history query in a query string, parsed defensively: what `encodeHistoryQuery` wrote. */\nexport function decodeHistoryQuery(\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) ? Math.trunc(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 // A week back by default.\n from: integer(\"from\") ?? to - 7 * 86_400_000,\n endpoints: all(\"endpoint\"),\n methods: all(\"method\"),\n services: all(\"service\"),\n outcomes: all(\"outcome\")?.filter((value): value is Outcome =>\n OUTCOMES.includes(value as Outcome),\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/** A filter groups its values with OR; separate filters combine with AND. */\nexport interface RowFilters {\n endpoints?: string[];\n methods?: string[];\n services?: string[];\n outcomes?: Outcome[];\n /** Only requests at least this slow, in milliseconds. */\n minMs?: number;\n /** Matches the endpoint, path, span name, action or failure message. */\n query?: string;\n sort?: \"recent\" | \"slowest\";\n}\n\nexport type Facet = keyof HistoryFacets;\n\n/** The fields the search box looks in. */\nexport const SEARCHED: readonly (keyof HistoryTrace)[] = [\n \"endpoint\",\n \"path\",\n \"name\",\n \"action\",\n \"message\",\n];\n\n/** Whether `row` passes the filters, leaving out `skip` when counting its facet. */\nexport function matches(\n row: HistoryTrace,\n filters: RowFilters,\n skip?: Facet,\n): boolean {\n const anyOf = (facet: Facet, values: string[] | undefined, value?: string) =>\n skip === facet ||\n !values?.length ||\n (value !== undefined && values.includes(value));\n if (!anyOf(\"endpoint\", filters.endpoints, row.endpoint)) return false;\n if (!anyOf(\"method\", filters.methods, row.method)) return false;\n if (!anyOf(\"service\", filters.services, row.service)) return false;\n if (!anyOf(\"outcome\", filters.outcomes, outcomeOf(row))) return false;\n if (\n filters.minMs !== undefined &&\n filters.minMs > 0 &&\n (row.durationMs ?? 0) < filters.minMs\n )\n return false;\n const needle = filters.query?.trim().toLowerCase();\n if (needle)\n return SEARCHED.some((field) =>\n String(row[field] ?? \"\")\n .toLowerCase()\n .includes(needle),\n );\n return true;\n}\n\n/** Newest first, or slowest first and then newest. */\nexport function compareRows(\n sort: RowFilters[\"sort\"],\n): (a: HistoryTrace, b: HistoryTrace) => number {\n return sort === \"slowest\"\n ? (a, b) =>\n (b.durationMs ?? 0) - (a.durationMs ?? 0) || b.startMs - a.startMs\n : (a, b) => b.startMs - a.startMs;\n}\n\nexport function applyFilters(\n rows: HistoryTrace[],\n filters: RowFilters,\n): HistoryTrace[] {\n return rows\n .filter((row) => matches(row, filters))\n .sort(compareRows(filters.sort));\n}\n\n/** The most values a facet lists. */\nexport const MAX_FACET_VALUES = 30;\n\nconst FACET_VALUE: Record<Facet, (row: HistoryTrace) => string | undefined> = {\n outcome: outcomeOf,\n method: (row) => row.method,\n service: (row) => row.service,\n endpoint: (row) => row.endpoint,\n};\n\n/** Counts for each filter, as if that filter were not applied. */\nexport function computeFacets(\n rows: HistoryTrace[],\n filters: RowFilters,\n): HistoryFacets {\n const count = (facet: Facet): FacetValue[] => {\n const counts = new Map<string, number>();\n for (const row of rows) {\n if (!matches(row, filters, facet)) continue;\n const value = FACET_VALUE[facet](row);\n if (value !== undefined) counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n return [...counts.entries()]\n .map(([value, total]) => ({ value, count: total }))\n .sort(\n (a, b) =>\n b.count - a.count ||\n (a.value < b.value ? -1 : a.value > b.value ? 1 : 0),\n )\n .slice(0, MAX_FACET_VALUES);\n };\n return {\n outcome: count(\"outcome\"),\n method: count(\"method\"),\n service: count(\"service\"),\n endpoint: count(\"endpoint\"),\n };\n}\n\n/** The width of each of `count` buckets across [from, to]: whole milliseconds, at least one. */\nexport const bucketSize = (from: number, to: number, count: number): number =>\n Math.max(Math.ceil((to - from) / count), 1);\n\n/** Count rows into `count` equal time buckets across [from, to], by outcome. */\nexport function bucketRows(\n rows: HistoryTrace[],\n from: number,\n to: number,\n count: number,\n): VolumeBucket[] {\n const size = bucketSize(from, to, count);\n const buckets: VolumeBucket[] = Array.from({ length: count }, (_, index) => ({\n start: from + index * size,\n ok: 0,\n client: 0,\n server: 0,\n }));\n for (const row of rows) {\n if (row.startMs < from || row.startMs > to) continue;\n const index = Math.floor((row.startMs - from) / size);\n buckets[Math.min(index, count - 1)]![outcomeOf(row)] += 1;\n }\n return buckets;\n}\n\n/** Linear-interpolated percentile of an ascending list; 0 for an empty list. */\nexport function 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 (\n sorted[lower]! + (sorted[upper]! - sorted[lower]!) * (position - lower)\n );\n}\n\n/** The numbers for the cards at the top of the log, for these requests. */\nexport function summarizeRows(rows: HistoryTrace[]): HistorySummary {\n let clientErrors = 0;\n let serverErrors = 0;\n const durations: number[] = [];\n for (const row of rows) {\n const outcome = outcomeOf(row);\n if (outcome === \"client\") clientErrors += 1;\n if (outcome === \"server\") serverErrors += 1;\n if (row.durationMs !== undefined) durations.push(row.durationMs);\n }\n durations.sort((a, b) => a - b);\n return {\n total: rows.length,\n clientErrors,\n serverErrors,\n medianMs: percentile(durations, 0.5),\n p95Ms: percentile(durations, 0.95),\n };\n}\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 [\n new Date(trace.startMs).toISOString(),\n trace.method,\n trace.route,\n trace.path,\n trace.httpStatus ?? trace.status,\n outcomeOf(trace),\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\n/** A string attribute, or undefined when it is missing or of another type. */\nexport function 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\n/** The attributes of the exception a span recorded, if it recorded one. */\nexport function findException(\n events: SpanEventRecord[],\n): Attributes | undefined {\n return events.find((event) => event.name === SPAN.exceptionEvent)?.attributes;\n}\n\n/** The span that ran the request's action, when it ran one. */\nexport function actionSpan<T extends { name: string }>(\n spans: readonly T[],\n): T | undefined {\n return spans.find((span) => span.name.startsWith(SPAN.actionPrefix));\n}\n","import {\n ASSETS,\n assetUrl,\n SHARED_MODULES,\n THEME_STORAGE_KEY,\n} from \"./dashboard-protocol\";\n\nconst IMPORT_MAP = JSON.stringify({\n imports: Object.fromEntries(\n SHARED_MODULES.map((module) => [module.specifier, assetUrl(module.file)]),\n ),\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 mode?: \"dev\" | \"production\";\n } = {},\n): string {\n const { extension, theme, mode } = 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>${mode === \"production\" ? \"Brick\" : \"Brick dev\"}</title>\n<link rel=\"icon\" href=\"data:,\">\n<script>\n(function () {\n try {\n var theme = localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)});\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=\"${assetUrl(ASSETS.appCss)}\">\n${extension?.css ? `<link rel=\"stylesheet\" href=\"${assetUrl(ASSETS.extensionCss)}${version}\">\\n` : \"\"}${theme ? `<link rel=\"stylesheet\" href=\"${assetUrl(ASSETS.theme)}\" data-brick-theme>\\n` : \"\"}${extension ? `<meta name=\"brick-extension\" data-revision=\"${extension.revision}\"${extension.js ? ` data-src=\"${assetUrl(ASSETS.extension)}${version}\"` : \"\"}>\\n` : \"\"}<script type=\"importmap\">\n${IMPORT_MAP}\n</script>\n</head>\n<body>\n<div id=\"root\"></div>\n<script type=\"module\" src=\"${assetUrl(ASSETS.app)}\"></script>\n</body>\n</html>\n`;\n}\n","import { createHash, timingSafeEqual } from \"node:crypto\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { DashboardAuth, DashboardIdentity } from \"@brickkit/core\";\n\nexport type Access =\n | { allowed: true; identity: DashboardIdentity }\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. */\nconst AUTHORIZE_TIMEOUT_MS = 5000;\n\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 protocol the client used: https when a proxy in front terminated TLS and says so. */\nexport function requestProtocol(request: IncomingMessage): \"http\" | \"https\" {\n const forwarded = request.headers[\"x-forwarded-proto\"];\n return (Array.isArray(forwarded) ? forwarded[0] : forwarded)\n ?.split(\",\")[0]\n ?.trim() === \"https\"\n ? \"https\"\n : \"http\";\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 protocol = requestProtocol(request);\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 isIdentity = (value: unknown): value is Required<DashboardIdentity> =>\n typeof value === \"object\" &&\n value !== null &&\n !(value instanceof Response) &&\n typeof (value as DashboardIdentity).user?.id === \"string\";\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` or an identity (`{ user }`). 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, identity: {} };\n if (!auth.authorize) return refusal(401, \"Unauthorized\", prompt);\n\n let decision: boolean | Response | DashboardIdentity;\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, identity: {} };\n if (isIdentity(decision))\n return {\n allowed: true,\n identity: {\n user: {\n id: decision.user.id,\n ...(typeof decision.user.name === \"string\"\n ? { name: decision.user.name }\n : {}),\n },\n },\n };\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 { 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 { ConfigError } from \"./config\";\nimport type { DevDocs } from \"./dev-docs\";\nimport type { DevHistory } from \"./dev-history\";\nimport { decodeHistoryQuery, type HistoryQuery } from \"./dashboard-query\";\nimport type { DevTelemetryStore } from \"./dev-telemetry-store\";\nimport { dashboardShell } from \"./dev-dashboard-shell\";\nimport {\n DASHBOARD_IDENTITY_HEADER,\n signDashboardIdentity,\n type DashboardAuth,\n type DashboardIdentity,\n} from \"@brickkit/core\";\nimport {\n createAccess,\n isLoopbackHost,\n requestProtocol,\n} from \"./dashboard-access\";\nimport {\n ASSETS,\n CSRF_HEADER,\n CSRF_VALUE,\n DOCS_PATHS,\n INSPECTOR_TOKEN_HEADER,\n matchRoute,\n ROUTES,\n type DashboardEvents,\n type DashboardSnapshot,\n type HistoryResponses,\n type IngestPayload,\n type RouteName,\n} from \"./dashboard-protocol\";\nimport {\n assetsDirectory,\n DashboardExtensions,\n type PluginDashboard,\n themeCss,\n type DashboardExtensionOptions,\n} from \"./dashboard-extension\";\n\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\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 the routes marked `production`, 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 /** How the host's user picks another port, added when the port is taken. */\n portHint?: 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 ConfigError(\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 route = matchRoute(request.method, url.pathname);\n if (route === \"health\") {\n await health(response);\n return;\n }\n let identity: DashboardIdentity = {};\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 identity = decision.identity;\n }\n if (!route || (production && !servedInProduction(route))) {\n send(response, 404, \"Not found\");\n return;\n }\n if (\n \"csrf\" in ROUTES[route] &&\n request.headers[CSRF_HEADER] !== CSRF_VALUE\n ) {\n send(response, 403, \"Forbidden\");\n return;\n }\n await handlers[route](request, response, url, identity);\n }\n\n function servedInProduction(route: RouteName): boolean {\n const served: boolean | \"extension\" = ROUTES[route].production;\n return served === \"extension\" ? Boolean(extension?.active) : served;\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 type Handler = (\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n identity: DashboardIdentity,\n ) => void | Promise<void>;\n\n const handlers: Record<Exclude<RouteName, \"health\">, Handler> = {\n shell: (_request, response) =>\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 mode: production ? \"production\" : \"dev\",\n }),\n {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n },\n ),\n assets(_request, response, url) {\n const name = url.pathname.slice(ROUTES.assets.path.length + 1);\n // The project's own files, kept in memory beside the dashboard's.\n const own = name === ASSETS.theme ? theme : extension?.asset(name);\n if (own !== undefined)\n send(response, 200, own, {\n \"content-type\": assetType(name),\n \"cache-control\": \"no-store\",\n });\n else serveAsset(response, name);\n },\n app,\n state: (_request, response) => json(response, snapshot()),\n events: eventStream,\n history(_request, response, url) {\n if (options.history)\n history(options.history, url.pathname, url.searchParams, response);\n else send(response, 404, \"Not found\");\n },\n docs: (_request, response, url) =>\n docsRoute(response, url.pathname, url.searchParams),\n openapi: (_request, response) =>\n json(response, options.store.apiDocuments()),\n proxy,\n workflows(request, response, url) {\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 frameOnlyHere(response);\n return inspector(request, response, url);\n },\n schedules: (request, response, url) => inspector(request, response, url),\n ingest,\n restart(request, response) {\n if (!options.restart) {\n send(response, 404, \"Not found\");\n return;\n }\n options.restart();\n send(response, 202, \"\");\n },\n };\n\n function snapshot(): DashboardSnapshot {\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 async function ingest(\n request: IncomingMessage,\n response: ServerResponse,\n ): Promise<void> {\n const body = await readBytes(request, MAX_INGEST_BYTES);\n if (!body) {\n tooLarge(response);\n return;\n }\n let payload: IngestPayload | null;\n try {\n payload = JSON.parse(Buffer.from(body).toString(\"utf8\")) as IngestPayload;\n } catch {\n payload = null;\n }\n if (payload === null || typeof payload !== \"object\") {\n send(response, 400, \"Bad request\");\n return;\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 }\n\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 try {\n if (pathname === DOCS_PATHS.info) return json(response, docs.info());\n if (pathname === DOCS_PATHS.search)\n return json(response, await docs.search(params.get(\"q\") ?? \"\"));\n if (pathname === DOCS_PATHS.components) {\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 = DOCS_PATHS.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\n ? json(response, page)\n : send(response, 404, \"No such page.\");\n }\n const filePrefix = `${DOCS_PATHS.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 * 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 and schedules are not being served. The app may be restarting, or it may have neither workflows nor schedules.\",\n { \"content-type\": \"text/plain; charset=utf-8\" },\n );\n return;\n }\n if (!isBodyless(request) && !fromOwnPage(request)) {\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; who the\n * dashboard let in is, signed, for `ctx.dashboard` and `dashboardUser()`.\n */\n async function app(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n identity: DashboardIdentity,\n ): Promise<void> {\n if (!fromOwnPage(request)) {\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 frameOnlyHere(response);\n await forward(\n request,\n response,\n `${new URL(appUrl).origin}${url.pathname.slice(ROUTES.app.path.length) || \"/\"}${url.search}`,\n (headers) => {\n if (access) headers.delete(\"authorization\");\n headers.set(DASHBOARD_IDENTITY_HEADER, signDashboardIdentity(identity));\n },\n \"Could not reach the app.\",\n );\n }\n\n /**\n * Send the request on to `target` and stream its answer back. `body`: the\n * request's body when the caller already read it; else it is streamed.\n */\n async function forward(\n request: IncomingMessage,\n response: ServerResponse,\n target: string,\n adjust: (headers: Headers) => void,\n unreachable: string,\n body?: Uint8Array,\n ): Promise<void> {\n const headers = forwardedHeaders(request);\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 ...(isBodyless(request)\n ? {}\n : body\n ? { body: body as BodyInit }\n : {\n body: Readable.toWeb(request) as unknown as BodyInit,\n duplex: \"half\",\n }),\n } as RequestInit);\n response.writeHead(upstream.status, returnedHeaders(upstream));\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 /**\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 async function proxy(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ): Promise<void> {\n if (!fromOwnPage(request)) {\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 tooLarge(response);\n return;\n }\n const cookie = url.searchParams.get(\"cookie\");\n await forward(\n request,\n response,\n target.href,\n (headers) => {\n if (cookie) headers.set(\"cookie\", cookie);\n },\n \"Could not reach the app.\",\n body,\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 const emit = <K extends keyof DashboardEvents>(\n name: K,\n data: DashboardEvents[K],\n ) => write(`event: ${name}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n emit(\"snapshot\", snapshot());\n const unsubscribe = options.store.subscribe((event) =>\n emit(event.type, event),\n );\n const unwatch = extension?.onChange(() =>\n emit(\"extension\", snapshot().extension),\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 `Brick: dashboard port ${options.port} is unavailable.${options.portHint ? ` ${options.portHint}` : \"\"}`,\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 // Stop buffering; tooLarge() answers and closes the connection.\n request.removeAllListeners(\"data\");\n request.resume();\n resolve(undefined);\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 queries: {\n [K in keyof HistoryResponses]: (query: HistoryQuery) => HistoryResponses[K];\n } = {\n summary: (query) => store.summary(query),\n traces: (query) => store.traces(query),\n facets: (query) => store.facets(query),\n volume: (query) => store.volume(query),\n };\n try {\n const endpoint = pathname.slice(ROUTES.history.path.length + 1);\n if (endpoint === \"\") return json(response, store.info());\n if (endpoint === \"export\") {\n return send(response, 200, store.exportCsv(decodeHistoryQuery(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 if (Object.hasOwn(queries, endpoint))\n return json(\n response,\n queries[endpoint as keyof typeof queries](decodeHistoryQuery(params)),\n );\n const prefix = \"traces/\";\n if (endpoint.startsWith(prefix)) {\n const trace = store.trace(\n decodeURIComponent(endpoint.slice(prefix.length)),\n );\n if (trace) return json(response, trace);\n }\n send(response, 404, \"Not found\");\n } catch (error) {\n // A malformed `%` in the trace id is the caller's mistake.\n if (error instanceof URIError) return send(response, 400, error.message);\n console.error(\"[Brick-TS] A dashboard history query failed:\", error);\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\nconst assetType = (name: string): string =>\n ASSET_TYPES[extname(name)] ?? \"application/octet-stream\";\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\": assetType(name),\n \"cache-control\": \"no-store\",\n }),\n () => send(response, 404, \"Not found\"),\n );\n}\n\nfunction tooLarge(response: ServerResponse): void {\n // Closing after the 413 stops the rest of the upload being read.\n send(response, 413, \"Payload too large\", {\n \"content-type\": \"text/plain; charset=utf-8\",\n connection: \"close\",\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\nfunction json(response: ServerResponse, body: unknown): void {\n send(response, 200, JSON.stringify(body), {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n });\n}\n\nconst isBodyless = (request: IncomingMessage) =>\n request.method === \"GET\" || request.method === \"HEAD\";\n\n/**\n * Whether a request comes from the dashboard's own page, as far as the browser\n * says: the same site, and the same origin as the address it was sent to.\n * Behind a proxy that terminates TLS that address is https.\n */\nfunction fromOwnPage(request: IncomingMessage): boolean {\n const site = request.headers[\"sec-fetch-site\"];\n const origin = request.headers.origin;\n return (\n (site === undefined || site === \"same-origin\") &&\n (origin === undefined ||\n origin === `${requestProtocol(request)}://${request.headers.host}`)\n );\n}\n\nfunction frameOnlyHere(response: ServerResponse): void {\n response.setHeader(\"content-security-policy\", \"frame-ancestors 'self'\");\n response.setHeader(\"x-frame-options\", \"SAMEORIGIN\");\n}\n\n/** The request's headers to send on, without those of this hop or this page. */\nfunction forwardedHeaders(request: IncomingMessage): Headers {\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (\n value === undefined ||\n NOT_FORWARDED.has(name) ||\n name === DASHBOARD_IDENTITY_HEADER\n )\n continue;\n if (name.startsWith(\"sec-\")) continue;\n headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n }\n return headers;\n}\n\nfunction returnedHeaders(upstream: Response): Record<string, string> {\n const returned: Record<string, string> = {};\n upstream.headers.forEach((value, name) => {\n if (!NOT_RETURNED.has(name)) returned[name] = value;\n });\n return returned;\n}\n","import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n HISTORY_PAGE_SIZE,\n type FacetValue,\n type HistoryFacets,\n type HistoryInfo,\n type HistorySummary,\n type HistoryTrace,\n type Outcome,\n type SpanOutcome,\n type TraceSummary,\n type VolumeBucket,\n} from \"./dashboard-protocol\";\nimport {\n bucketSize,\n CLIENT_ERROR,\n endpointOf,\n MAX_FACET_VALUES,\n percentile,\n SEARCHED,\n SERVER_ERROR,\n tracesToCsv,\n type Facet,\n type HistoryQuery,\n} from \"./dashboard-query\";\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 MAX_LIMIT = 500;\nconst MAX_EXPORT_ROWS = 100_000;\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, options.warn);\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\n/** Each row's outcome, by the rules of `outcomeOf`. */\nconst OUTCOME_CASE = `CASE\n WHEN status = 'error' OR http_status >= ${SERVER_ERROR} THEN 'server'\n WHEN http_status >= ${CLIENT_ERROR} THEN 'client'\n ELSE 'ok' END`;\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\") anyOf(OUTCOME_CASE, query.outcomes);\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 `(${SEARCHED.map((column) => `${column} LIKE ? ESCAPE '\\\\'`).join(\" OR \")})`,\n );\n params.push(...SEARCHED.map(() => pattern));\n }\n return { sql: clauses.join(\" AND \"), params };\n}\n\nconst orderSql = (sort: HistoryQuery[\"sort\"]) =>\n sort === \"slowest\" ? \"duration_ms DESC, start_ms DESC\" : \"start_ms DESC\";\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 readonly #warn?: (message: string) => void;\n /** Failure kinds already reported: one warning each, not one per batch. */\n readonly #warned = new Set<string>();\n\n constructor(\n database: Database,\n days: number,\n warn?: (message: string) => void,\n ) {\n this.#database = database;\n this.days = days;\n this.#warn = warn;\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 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 endpointOf(trace),\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 (error) {\n // A failed write loses a batch of history; it must not break the app.\n this.#warnOnce(\"save requests to\", error);\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 (error) {\n // Pruning is housekeeping; try again next time.\n this.#warnOnce(\"prune\", error);\n }\n }\n\n #warnOnce(action: string, error: unknown): void {\n if (this.#warned.has(action)) return;\n this.#warned.add(action);\n const reason = error instanceof Error ? error.message : String(error);\n this.#warn?.(\n `[Brick-TS] Could not ${action} the request history (${reason}).`,\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 ?? HISTORY_PAGE_SIZE, 1),\n MAX_LIMIT,\n );\n const offset = Math.max(query.offset ?? 0, 0);\n const rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} 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 = bucketSize(query.from, query.to, buckets);\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 rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} LIMIT ?`,\n )\n .all(...params, MAX_EXPORT_ROWS);\n return tracesToCsv(rows.map(toHistoryTrace));\n }\n\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","import type { Attributes } from \"@opentelemetry/api\";\nimport type { ApiDocument, ArchitectureSchema } from \"@brickkit/core\";\nimport {\n ATTR,\n LIVE_LIMITS,\n type ApiSnapshot,\n type ArchitectureSnapshot,\n type DevTelemetryEvent,\n type DevTelemetrySnapshot,\n type DocsSnapshot,\n type FailureSummary,\n type ReloadSummary,\n type SerializedError,\n type SpanEndRecord,\n type SpanOutcome,\n type SpanStartRecord,\n type TelemetryRecord,\n type TraceSpan,\n type TraceSummary,\n type WorkerErrorPhase,\n} from \"./dashboard-protocol\";\nimport {\n actionSpan,\n CLIENT_ERROR,\n findException,\n outcomeOf,\n stringAttribute,\n} from \"./dashboard-query\";\n\nconst LIMITS = { ...LIVE_LIMITS, spansPerTrace: 500 };\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: { saveTrace(trace: TraceSummary): void } | undefined;\n #architecture: ArchitectureSnapshot | null = null;\n #api: ApiSnapshot | null = null;\n #docs: DocsSnapshot | null = null;\n #inspector: { port: number; token: string; workflows: boolean } | undefined;\n #apiDocuments: ApiDocument[] = [];\n #sequence = 0;\n #generation = 0;\n\n /** Finished requests are also kept in `history`, when given. */\n constructor(\n options: { history?: { saveTrace(trace: TraceSummary): void } } = {},\n ) {\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 and schedules, or\n * `undefined` when it stops. The address stays here: the snapshot says only\n * whether there is a workflow inspector.\n */\n setInspector(\n target: { port: number; token: string; workflows: boolean } | undefined,\n ): void {\n this.#inspector = target;\n this.#emit({ type: \"inspector\", inspector: Boolean(target?.workflows) });\n }\n\n /** Where the dashboard proxies the workflow inspector and schedules, when the app serves them. */\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?.workflows),\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, ATTR.httpMethod);\n entry.route = stringAttribute(record.attributes, ATTR.httpRoute);\n entry.path = stringAttribute(record.attributes, ATTR.urlPath);\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, ATTR.errorCode);\n if (code !== undefined) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code,\n message:\n stringAttribute(exception, ATTR.exceptionMessage) ??\n stringAttribute(record.attributes, ATTR.errorMessage) ??\n code,\n status: numberAttribute(record.attributes, ATTR.errorStatus),\n stack: stringAttribute(exception, ATTR.exceptionStack),\n traceId: entry.traceId,\n route: entry.route,\n service: stringAttribute(record.attributes, ATTR.service),\n action: stringAttribute(record.attributes, ATTR.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(record.attributes, ATTR.httpStatus);\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 outcome = outcomeOf({\n status: record.status === \"error\" ? \"error\" : \"ok\",\n httpStatus: entry.httpStatus,\n });\n entry.status = outcome === \"server\" ? \"error\" : \"ok\";\n if (outcome !== \"ok\" && !entry.failureRecorded) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code: status >= CLIENT_ERROR ? `HTTP_${status}` : \"UNHANDLED_ERROR\",\n message:\n stringAttribute(exception, ATTR.exceptionMessage) ??\n record.statusMessage ??\n describeResponse(entry, status),\n status: entry.httpStatus,\n stack: stringAttribute(exception, ATTR.exceptionStack),\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 (error) {\n this.#listeners.delete(listener);\n console.warn(\n \"[Brick-TS] A dashboard client stopped receiving updates:\",\n error,\n );\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 action = actionSpan(spans);\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(action?.attributes, ATTR.service),\n action: stringAttribute(action?.attributes, ATTR.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 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","import {\n ConfigError,\n DEFAULT_DASHBOARD_PORT,\n DEFAULT_HISTORY_DAYS,\n} from \"./config\";\nimport { DocsHost } from \"./dev-docs\";\nimport {\n startDevDashboard,\n type DevDashboard,\n type DevDashboardOptions,\n} from \"./dev-dashboard\";\nimport { openHistory } from \"./dev-history\";\nimport { DevTelemetryStore } from \"./dev-telemetry-store\";\n\nexport interface DashboardHost extends DevDashboard {\n /** Where the host records what the app reports. */\n readonly store: DevTelemetryStore;\n /** The app's developer documentation, when `docs` was asked for. */\n readonly docs?: DocsHost;\n}\n\n/**\n * Open the dashboard with its history, store and docs, for `brick dev`, the\n * Vite plugin and the production dashboard alike. When it cannot start, what\n * it opened is closed, `warn` says why, and the host runs on without it. A\n * configuration mistake (a bad theme, a public host without auth) throws.\n */\nexport async function openDashboard(\n options: Omit<DevDashboardOptions, \"store\" | \"history\" | \"docs\" | \"port\"> & {\n /** Default 9400. */\n port?: number;\n /** The project folder; history is kept in `.brick/` inside it. */\n directory: string;\n /** Days of requests to keep on disk; zero for none. Default 90. */\n historyDays?: number;\n warn: (message: string) => void;\n /** Serve the app's developer documentation (the Docs tab). */\n docs?: boolean;\n },\n): Promise<DashboardHost | undefined> {\n const {\n port = DEFAULT_DASHBOARD_PORT,\n directory,\n historyDays = DEFAULT_HISTORY_DAYS,\n warn,\n docs: withDocs,\n ...rest\n } = options;\n const history = await openHistory({ directory, days: historyDays, warn });\n const store = new DevTelemetryStore({ history });\n const docs = withDocs\n ? new DocsHost((docs) => store.setDocs(docs), warn)\n : undefined;\n let server: DevDashboard;\n try {\n server = await startDevDashboard({\n ...rest,\n port,\n store,\n history,\n docs: docs && (() => docs.current),\n });\n } catch (error) {\n docs?.close();\n history?.close();\n if (error instanceof ConfigError) throw error;\n const reason = error instanceof Error ? error.message : String(error);\n warn(`[Brick-TS] ${reason} Continuing without the dashboard.`);\n return undefined;\n }\n return {\n port: server.port,\n store,\n docs,\n setPluginExtensions: (plugins) => server.setPluginExtensions(plugins),\n stop() {\n server.stop();\n docs?.close();\n history?.close();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA0CA,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,6BAAa,IAAI,IAAI;CAAC;CAAS;CAAQ;CAAU;AAAO,CAAC;AAC/D,MAAM,4BAAY,IAAI,IAAI,CAAC,QAAQ,MAAM,CAAC;AAC1C,MAAM,SAAS,IAAI,IAAY,YAAY;;AAG3C,SAAS,SAAS,OAAe,OAAwB;CACvD,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,YAAY,KAAK,KAAK,GACtE,MAAM,IAAI,YACR,0BAA0B,MAAM,8CAClC;CACF,OAAO,MAAM,KAAK;AACpB;;;;;AAMA,SAAgB,SAAS,OAA2C;CAClE,IAAI,CAAC,OAAO,OAAO;CACnB,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GACjC,IAAI,CAAC,WAAW,IAAI,GAAG,GACrB,MAAM,IAAI,YACR,kCAAkC,IAAI,2CACxC;CACJ,MAAM,QAAkB,CAAC;CACzB,MAAM,OAAiB,CAAC;CACxB,IAAI,MAAM,WAAW,KAAA,GACnB,KAAK,KAAK,aAAa,SAAS,UAAU,MAAM,MAAM,EAAE,EAAE;CAC5D,KAAK,MAAM,CAAC,MAAM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