@brickkit/cli 0.12.0 → 0.13.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.
Files changed (119) hide show
  1. package/dashboard-dist/{api-reference-B-bZRtNV.js → api-reference-mT9VNcPb.js} +69 -69
  2. package/dashboard-dist/app.js +12 -13
  3. package/dashboard-dist/{client-BJJtVSVr.js → client-CwATkLJa.js} +1 -1
  4. package/dashboard-dist/{core-Z7NJFk0K.js → core-BEUWp6B5.js} +1 -1
  5. package/dashboard-dist/docs-BRrtyxDB.js +4 -0
  6. package/dashboard-dist/kit.js +1 -1
  7. package/dashboard-dist/popover-Bj9x-88h.js +1 -0
  8. package/dist/bin.js +154 -217
  9. package/dist/bin.js.map +1 -1
  10. package/dist/build.js +463 -0
  11. package/dist/build.js.map +1 -0
  12. package/dist/client-contract-file.js +356 -1
  13. package/dist/client-contract-file.js.map +1 -0
  14. package/dist/compiler.d.ts +12 -2
  15. package/dist/compiler2.js +12 -5
  16. package/dist/compiler2.js.map +1 -1
  17. package/dist/config.d.ts +3 -0
  18. package/dist/config.js +1 -250
  19. package/dist/config2.d.ts +122 -0
  20. package/dist/config2.js +207 -0
  21. package/dist/config2.js.map +1 -0
  22. package/dist/dashboard-extension.d.ts +3 -0
  23. package/dist/{dev-telemetry-store.js → dashboard-host.js} +1533 -1574
  24. package/dist/dashboard-host.js.map +1 -0
  25. package/dist/dashboard-protocol.js +189 -0
  26. package/dist/dashboard-protocol.js.map +1 -0
  27. package/dist/dashboard.d.ts +4 -1
  28. package/dist/definitions.js +33 -0
  29. package/dist/definitions.js.map +1 -0
  30. package/dist/dev-application.js +34 -0
  31. package/dist/dev-application.js.map +1 -0
  32. package/dist/dev-protocol.js +21 -0
  33. package/dist/dev-protocol.js.map +1 -0
  34. package/dist/dev-reporter.js +2 -1
  35. package/dist/dev-reporter.js.map +1 -1
  36. package/dist/dev-telemetry.js +5 -20
  37. package/dist/dev-telemetry.js.map +1 -1
  38. package/dist/dev-worker.js +79 -19
  39. package/dist/dev-worker.js.map +1 -1
  40. package/dist/index.d.ts +15 -74
  41. package/dist/index.js +12 -5
  42. package/dist/index.js.map +1 -0
  43. package/dist/lint/oxlint.js +5 -3
  44. package/dist/lint/oxlint.js.map +1 -1
  45. package/dist/own-module.js +7 -0
  46. package/dist/own-module.js.map +1 -0
  47. package/dist/plugin.d.ts +6 -5
  48. package/dist/plugin.js +5 -39
  49. package/dist/plugin.js.map +1 -1
  50. package/dist/production-dashboard.d.ts +2 -0
  51. package/dist/production-dashboard.js +51 -0
  52. package/dist/production-dashboard.js.map +1 -0
  53. package/dist/production-dashboard2.d.ts +34 -0
  54. package/dist/{presets.js → project.js} +104 -106
  55. package/dist/project.js.map +1 -0
  56. package/dist/serve.d.ts +24 -0
  57. package/dist/serve.js +1 -0
  58. package/dist/serve2.js +49 -0
  59. package/dist/serve2.js.map +1 -0
  60. package/dist/vite.js +26 -47
  61. package/dist/vite.js.map +1 -1
  62. package/dist/workflows.d.ts +2 -2
  63. package/dist/workflows2.js +59 -37
  64. package/dist/workflows2.js.map +1 -1
  65. package/inspector-dist/client/assets/app-CeSwVsRm.css +2 -0
  66. package/inspector-dist/client/assets/{highlighted-body-B3W2YXNL-DYVdwGy2.js → highlighted-body-B3W2YXNL-CfRnuITN.js} +1 -1
  67. package/inspector-dist/client/assets/{home-CyjkvtII.js → home-hwPlkNhv.js} +1529 -378
  68. package/inspector-dist/client/assets/manifest-0e76e9ac.js +1 -0
  69. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-ZDR2PNY_.js +1 -0
  70. package/inspector-dist/client/assets/root-ChBNTZd2.css +2 -0
  71. package/inspector-dist/client/assets/{root-DX9wtogx.js → root-SLeEf-sT.js} +17 -29
  72. package/inspector-dist/client/assets/{run-detail-C69EJGql.js → run-detail-DYbVkIFH.js} +398 -76
  73. package/inspector-dist/client/assets/{tabs-B6B88IjT.js → tabs-CaJisoyb.js} +189 -2130
  74. package/inspector-dist/client/assets/{zstd-browser-decoder-ByUgcY9H.js → zstd-browser-decoder-D94wmfAU.js} +1 -1
  75. package/inspector-dist/server/assets/{app-WoDoT62X.js → app-DGlfWVUI.js} +69783 -70608
  76. package/inspector-dist/server/assets/{chunk-RLXIAIE6-CbvDIAEa.js → chunk-RLXIAIE6-F0SJZlei.js} +4 -6
  77. package/inspector-dist/server/assets/{dist-qR-969AD.js → dist-BCbwm6jl.js} +2 -4
  78. package/inspector-dist/server/assets/{dist-CQnQcIJg.js → dist-CG2aVufI.js} +0 -2
  79. package/inspector-dist/server/assets/{dist-BRxZSWUN.js → dist-Ce0I2PUv.js} +2 -5
  80. package/inspector-dist/server/assets/{dist-DqRd9pyS.js → dist-DY0UlahA.js} +0 -2
  81. package/inspector-dist/server/assets/{encryption-_PuklZNX.js → encryption-DdQgC8Rk.js} +2 -4
  82. package/inspector-dist/server/assets/{event-metadata-BVakQJ_y.js → event-metadata-n7E4zEmT.js} +0 -2
  83. package/inspector-dist/server/assets/{functions-CImcpqNl.js → functions-CNVQtbgg.js} +2 -4
  84. package/inspector-dist/server/assets/{global-singleton-CPirHxFh.js → global-singleton-D8sIN5du.js} +0 -2
  85. package/inspector-dist/server/assets/{highlighted-body-B3W2YXNL-fPMB_t7F.js → highlighted-body-B3W2YXNL-CWRzMxYD.js} +2 -4
  86. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-D0v0ngVr.js +1 -0
  87. package/inspector-dist/server/assets/{parse-D9Vvgzt9.js → parse-Begau9cA.js} +0 -2
  88. package/inspector-dist/server/assets/{rolldown-runtime-CLg409Sh.js → rolldown-runtime-C1I3wEg2.js} +1 -2
  89. package/inspector-dist/server/assets/{serialization-format-DDtsVTU1.js → serialization-format-BbuGfHog.js} +6 -8
  90. package/inspector-dist/server/assets/{token-BW4GdQZh.js → token-BgMmJNP5.js} +2 -4
  91. package/inspector-dist/server/assets/{token-D6FXdkJT.js → token-BrUX0bxz.js} +2 -4
  92. package/inspector-dist/server/assets/{token-util-BoNmi-wE.js → token-util-DZN32qmT.js} +1 -3
  93. package/inspector-dist/server/assets/{wrapper-wiqsGXcE.js → wrapper-CIC3w0oC.js} +1 -3
  94. package/inspector-dist/server/assets/{ws-transport-DV7oG4mL.js → ws-transport-CxTYB11n.js} +24094 -24096
  95. package/inspector-dist/server/assets/{zstd-browser-decoder-Cswf0KO6.js → zstd-browser-decoder-D7bCXbGg.js} +2 -4
  96. package/inspector-dist/server/index.js +1 -3
  97. package/package.json +12 -2
  98. package/dashboard-dist/docs-Dpfc0wJb.js +0 -4
  99. package/dashboard-dist/popover-BzejBolB.js +0 -1
  100. package/dist/app-entry.js +0 -1
  101. package/dist/app-entry2.js +0 -18
  102. package/dist/app-entry2.js.map +0 -1
  103. package/dist/client-contract-file2.js +0 -33
  104. package/dist/client-contract-file2.js.map +0 -1
  105. package/dist/client-contract.js +0 -1
  106. package/dist/client-contract2.js +0 -296
  107. package/dist/client-contract2.js.map +0 -1
  108. package/dist/config.js.map +0 -1
  109. package/dist/dev-telemetry-store.js.map +0 -1
  110. package/dist/emit.d.ts +0 -5
  111. package/dist/presets.js.map +0 -1
  112. package/dist/runner.js +0 -519
  113. package/dist/runner.js.map +0 -1
  114. package/inspector-dist/client/assets/app-CCzpuUz_.css +0 -2
  115. package/inspector-dist/client/assets/manifest-ba30b52d.js +0 -1
  116. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-Dy6IVqPy.js +0 -1
  117. package/inspector-dist/client/assets/root-8BMab1lL.css +0 -2
  118. package/inspector-dist/client/assets/world-config-context-C3BqXPIv.js +0 -30
  119. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-bADXySE3.js +0 -3
@@ -1,877 +1,644 @@
1
+ import { n as ConfigError, r as DEFAULT_DASHBOARD_PORT } from "./config2.js";
2
+ import { a as INSPECTOR_TOKEN_HEADER, c as SHARED_MODULES, d as assetUrl, f as decode, g as matchRoute, h as isExternalHref, i as DOCS_PATHS, l as SPAN, m as docsHref, n as ATTR, o as LIVE_LIMITS, p as docsFileUrl, s as ROUTES, t as ASSETS, u as THEME_STORAGE_KEY } from "./dashboard-protocol.js";
1
3
  import { createRequire } from "node:module";
4
+ import { existsSync, mkdirSync, watch, writeFileSync } from "node:fs";
5
+ import { basename, dirname, extname, join, posix, relative, resolve, sep } from "node:path";
2
6
  import { fileURLToPath, pathToFileURL } from "node:url";
3
7
  import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
8
+ import { createHash, timingSafeEqual } from "node:crypto";
4
9
  import { createServer } from "node:http";
5
- import { basename, dirname, extname, join, posix, relative, resolve, sep } from "node:path";
6
10
  import { Readable } from "node:stream";
7
11
  import { pipeline } from "node:stream/promises";
8
- import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
9
- import { existsSync, mkdirSync, statSync, watch, writeFileSync } from "node:fs";
10
- // src/dev-inspector.ts
11
- /** Where the dashboard serves the inspector. */
12
- const INSPECTOR_PATH = "/workflows";
13
- /** The header that proves a request comes from the dashboard. */
14
- const INSPECTOR_TOKEN_HEADER = "x-brick-inspector";
15
- /** The built inspector, next to `src/` in the repo and next to `dist/` when published. */
16
- const INSPECTOR_DIRECTORY = fileURLToPath(new URL("../inspector-dist/", import.meta.url));
17
- /** Whether a path is a regular file; any failure to find out (not a directory, name too long) says no. */
18
- function isFile(path) {
19
- try {
20
- return statSync(path).isFile();
21
- } catch {
22
- return false;
23
- }
12
+ // src/dashboard-extension.ts
13
+ /** The colour tokens of `dashboard/theme.css`; a test keeps the two in step. */
14
+ const THEME_TOKENS = [
15
+ "background",
16
+ "foreground",
17
+ "card",
18
+ "card-foreground",
19
+ "popover",
20
+ "popover-foreground",
21
+ "primary",
22
+ "primary-foreground",
23
+ "secondary",
24
+ "secondary-foreground",
25
+ "muted",
26
+ "muted-foreground",
27
+ "accent",
28
+ "accent-foreground",
29
+ "destructive",
30
+ "destructive-foreground",
31
+ "positive",
32
+ "border",
33
+ "input",
34
+ "ring",
35
+ "chart-1",
36
+ "chart-2",
37
+ "chart-3",
38
+ "chart-4",
39
+ "chart-5",
40
+ "span-request",
41
+ "span-action",
42
+ "span-rpc",
43
+ "span-sql",
44
+ "span-event",
45
+ "span-other"
46
+ ];
47
+ const THEME_KEYS = /* @__PURE__ */ new Set([
48
+ "light",
49
+ "dark",
50
+ "radius",
51
+ "fonts"
52
+ ]);
53
+ const FONT_KEYS = /* @__PURE__ */ new Set(["sans", "mono"]);
54
+ const TOKENS = new Set(THEME_TOKENS);
55
+ /** A value that cannot close the rule it sits in. */
56
+ function cssValue(where, value) {
57
+ if (typeof value !== "string" || !value.trim() || /[;{}<>\\]/.test(value)) throw new ConfigError(`Brick: dashboard.theme.${where} must be a CSS value without ; { } < > or \\.`);
58
+ return value.trim();
24
59
  }
25
60
  /**
26
- * A file of the inspector's browser build. Its names carry a hash of their
27
- * content, so a browser may keep them for good. Anything else under `assets/`
28
- * is a plain 404: the page would answer with HTML. `undefined` for requests
29
- * outside `assets/`, which are the page's to answer.
61
+ * The stylesheet for a theme, loaded after the dashboard's own; empty when the
62
+ * theme sets nothing. Throws on a token name theme.css does not have.
30
63
  */
31
- function browserAsset(request, client) {
32
- if (request.method !== "GET" && request.method !== "HEAD") return void 0;
33
- const { pathname } = new URL(request.url);
34
- if (!pathname.startsWith(`/workflows/assets/`)) return void 0;
35
- const file = resolve(client, pathname.slice(11));
36
- if (!file.startsWith(client + sep) || !isFile(file)) return new Response("Not found", { status: 404 });
37
- return new Response(Bun.file(file), { headers: { "cache-control": "public, max-age=31536000, immutable" } });
64
+ function themeCss(theme) {
65
+ if (!theme) return "";
66
+ for (const key of Object.keys(theme)) if (!THEME_KEYS.has(key)) throw new ConfigError(`Brick: dashboard.theme has no "${key}". It takes light, dark, radius and fonts.`);
67
+ const rules = [];
68
+ const root = [];
69
+ if (theme.radius !== void 0) root.push(`--radius: ${cssValue("radius", theme.radius)};`);
70
+ for (const [name, value] of Object.entries(theme.fonts ?? {})) {
71
+ if (!FONT_KEYS.has(name)) throw new ConfigError(`Brick: dashboard.theme.fonts has no "${name}". It takes sans and mono.`);
72
+ root.push(`--font-${name}: ${cssValue(`fonts.${name}`, value)};`);
73
+ }
74
+ if (root.length) rules.push(`:root {\n ${root.join("\n ")}\n}`);
75
+ for (const [mode, selector] of [["light", ":root:not(.dark)"], ["dark", ":root.dark"]]) {
76
+ const tokens = theme[mode];
77
+ if (!tokens) continue;
78
+ const lines = Object.entries(tokens).map(([name, value]) => {
79
+ if (!TOKENS.has(name)) throw new ConfigError(`Brick: dashboard.theme.${mode} has no token "${name}". Tokens: ${THEME_TOKENS.join(", ")}.`);
80
+ return `--${name}: ${cssValue(`${mode}.${name}`, value)};`;
81
+ });
82
+ if (lines.length) rules.push(`${selector} {\n ${lines.join("\n ")}\n}`);
83
+ }
84
+ return rules.length ? `${rules.join("\n")}\n` : "";
85
+ }
86
+ const SHARED = SHARED_MODULES.map((module) => module.specifier);
87
+ /** 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. */
88
+ async function bundleComponents(entry) {
89
+ if (typeof Bun !== "undefined") {
90
+ const result = await Bun.build({
91
+ entrypoints: [entry],
92
+ target: "browser",
93
+ format: "esm",
94
+ external: SHARED,
95
+ minify: false,
96
+ throw: false
97
+ });
98
+ if (!result.success) throw new Error(result.logs.map((log) => log.message).join("\n"));
99
+ return (result.outputs.find((item) => item.kind === "entry-point") ?? result.outputs[0]).text();
100
+ }
101
+ const { build } = await import("vite");
102
+ const output = await build({
103
+ configFile: false,
104
+ logLevel: "silent",
105
+ root: dirname(entry),
106
+ oxc: { jsx: { runtime: "automatic" } },
107
+ esbuild: { jsx: "automatic" },
108
+ define: { "process.env.NODE_ENV": "\"development\"" },
109
+ build: {
110
+ write: false,
111
+ minify: false,
112
+ lib: {
113
+ entry,
114
+ formats: ["es"],
115
+ fileName: "components"
116
+ },
117
+ rollupOptions: { external: SHARED }
118
+ }
119
+ });
120
+ const bundles = Array.isArray(output) ? output : [output];
121
+ for (const bundle of bundles) {
122
+ const chunk = ("output" in bundle ? bundle.output : []).find((item) => item.type === "chunk" && item.isEntry);
123
+ if (chunk && "code" in chunk) return chunk.code;
124
+ }
125
+ throw new Error("Brick: the dashboard module produced no output.");
126
+ }
127
+ /** The built React app, next to `src/` in the repo and next to `dist/` when published. */
128
+ function assetsDirectory() {
129
+ for (const relative of ["../dashboard-dist/", "../../dashboard-dist/"]) {
130
+ const directory = fileURLToPath(new URL(relative, import.meta.url));
131
+ if (existsSync(join(directory, "app.js"))) return directory;
132
+ }
38
133
  }
134
+ /** The `warn` functions already told that tailwindcss is missing: once each, not once per rebuild. */
135
+ const warnedTailwind = /* @__PURE__ */ new WeakSet();
39
136
  /**
40
- * Serve the Workflow inspector (the Workflow SDK's observability UI, built into
41
- * this package) for the app's world, on a loopback port of its own. The
42
- * dashboard proxies it at `/workflows`; it is the only caller that knows the
43
- * token. The UI can cancel runs and resume hooks, so nothing else may reach it,
44
- * and it exists only under `brick dev`.
45
- *
46
- * @param app - The loaded app, running in this process.
47
- * @param directory - The inspector's build; this package's own by default.
48
- * @returns The inspector, or `undefined` when the app runs no workflows.
49
- * @throws When the inspector's build is missing.
137
+ * Tailwind for the classes in the extension's bundle, compiled against the
138
+ * dashboard's theme.css so `bg-primary` and the rest match. Only utilities are
139
+ * emitted: the dashboard's stylesheet already has the base styles and tokens.
140
+ * Tailwind is an optional peer, found from the project first.
50
141
  */
51
- async function startInspector(app, directory = INSPECTOR_DIRECTORY) {
52
- const target = app.events?.workflows;
53
- if (!target) return void 0;
54
- const entry = join(directory, "server", "index.js");
55
- if (!existsSync(entry)) throw new Error("The workflow inspector is not built. Build it with: bun run --filter @brickkit/cli build");
56
- const { createFetchHandler } = await import(pathToFileURL(entry).href);
57
- const page = createFetchHandler(INSPECTOR_PATH, { world: target.world });
58
- const client = join(directory, "client");
59
- const token = randomBytes(16).toString("hex");
60
- const server = Bun.serve({
61
- hostname: "127.0.0.1",
62
- port: 0,
63
- idleTimeout: 0,
64
- fetch: (request) => request.headers.get("x-brick-inspector") === token ? browserAsset(request, client) ?? page(request) : new Response("Forbidden", { status: 403 })
142
+ async function extensionCss(entry, js, warn) {
143
+ let tailwind;
144
+ let main;
145
+ for (const from of [entry, fileURLToPath(import.meta.url)]) try {
146
+ const require = createRequire(from);
147
+ tailwind = require.resolve("tailwindcss/package.json");
148
+ main = require.resolve("tailwindcss");
149
+ break;
150
+ } catch {}
151
+ const assets = assetsDirectory();
152
+ const themeFile = assets ? join(assets, "theme.css") : fileURLToPath(new URL("../dashboard/theme.css", import.meta.url));
153
+ if (!tailwind || !main) {
154
+ if (!warnedTailwind.has(warn)) warn("[Brick-TS] tailwindcss is not installed, so the dashboard extension's own Tailwind classes are not compiled. The UI kit is styled either way.");
155
+ warnedTailwind.add(warn);
156
+ return "";
157
+ }
158
+ const root = dirname(tailwind);
159
+ const { compile } = await import(pathToFileURL(main).href);
160
+ const compiler = await compile(`@layer theme, base, components, utilities;
161
+ @import "tailwindcss/theme.css" theme(reference inline);
162
+ @import "tailwindcss/utilities.css" layer(utilities);
163
+ @reference "brick/theme.css";
164
+ `, {
165
+ base: root,
166
+ async loadStylesheet(id) {
167
+ const path = id === "brick/theme.css" ? themeFile : join(root, id.replace(/^tailwindcss\//, ""));
168
+ return {
169
+ path,
170
+ base: dirname(path),
171
+ content: await readFile(path, "utf8")
172
+ };
173
+ }
65
174
  });
175
+ const candidates = new Set(js.split(/[\s"'`]+/).filter(Boolean));
176
+ const css = compiler.build([...candidates]);
177
+ return /\{/.test(css) ? css : "";
178
+ }
179
+ /** Bundle the extension and its styles for the dashboard page. */
180
+ async function buildDashboardExtension(entry, options = {}) {
181
+ const js = await bundleComponents(entry);
66
182
  return {
67
- port: server.port,
68
- token,
69
- stop: () => void server.stop(true)
183
+ js,
184
+ css: await extensionCss(entry, js, options.warn ?? ((message) => console.warn(message)))
70
185
  };
71
186
  }
72
- // src/dev-history-csv.ts
73
- const CSV_COLUMNS = [
74
- "time",
75
- "method",
76
- "route",
77
- "path",
78
- "status",
79
- "outcome",
80
- "duration_ms",
81
- "service",
82
- "action",
83
- "message",
84
- "trace_id"
85
- ];
86
- function csvCell(value) {
87
- if (value === void 0) return "";
88
- const text = String(value);
89
- const safe = /^[=+\-@\t\r]/.test(text) ? `'${text}` : text;
90
- return /[",\n\r]/.test(safe) ? `"${safe.replace(/"/g, "\"\"")}"` : safe;
187
+ /**
188
+ * Write the app's extension and its plugins' into `outdir`, where `brick start`
189
+ * can serve them: the app's alone as it is, or with plugins each part apart
190
+ * and `extension.js` loading them, as `brick dev` serves them. Returns false
191
+ * when there is none to write. A plugin's that fails to build throws.
192
+ */
193
+ async function writeDashboardExtension(entry, plugins, outdir) {
194
+ const parts = [...entry ? [{
195
+ name: "app",
196
+ path: entry,
197
+ plugin: false
198
+ }] : [], ...[...pluginDashboards(plugins)].map(([path, name]) => ({
199
+ name,
200
+ path,
201
+ plugin: true
202
+ }))];
203
+ if (!parts.length) return false;
204
+ const warn = (message) => console.warn(message);
205
+ const built = await Promise.all(parts.map((part) => buildDashboardExtension(part.path, { warn }).catch((error) => {
206
+ if (!part.plugin) throw error;
207
+ throw new Error(`Brick compiler: the dashboard extension of plugin ${part.name} failed to build: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
208
+ })));
209
+ await writeBuiltFolder(outdir, layoutParts(parts.map((part, index) => ({
210
+ ...part,
211
+ built: built[index]
212
+ }))));
213
+ return true;
91
214
  }
92
- /** Requests as CSV with a header row, for the dashboard's export. */
93
- function tracesToCsv(traces) {
94
- const lines = traces.map((trace) => {
95
- const failed = trace.status === "error" || (trace.httpStatus ?? 0) >= 500;
96
- const client = (trace.httpStatus ?? 0) >= 400;
97
- return [
98
- new Date(trace.startMs).toISOString(),
99
- trace.method,
100
- trace.route,
101
- trace.path,
102
- trace.httpStatus ?? trace.status,
103
- failed ? "server" : client ? "client" : "ok",
104
- trace.durationMs === void 0 ? void 0 : trace.durationMs.toFixed(3),
105
- trace.service,
106
- trace.action,
107
- trace.message,
108
- trace.traceId
109
- ].map(csvCell).join(",");
110
- });
111
- return [CSV_COLUMNS.join(","), ...lines].join("\n") + "\n";
215
+ /** Whether `path` is a folder `brick build` wrote, which is served as it is. */
216
+ const isBuiltFolder = (path) => existsSync(join(path, ASSETS.extension));
217
+ /** Write the extensions as `layoutParts` lays them out; `readBuiltFolder` reads them back. */
218
+ async function writeBuiltFolder(outdir, layout) {
219
+ await mkdir(outdir, { recursive: true });
220
+ await writeFile(join(outdir, ASSETS.extension), layout.js);
221
+ await writeFile(join(outdir, ASSETS.extensionCss), layout.css);
222
+ for (const [name, js] of Object.entries(layout.parts ?? {})) await writeFile(join(outdir, name), js);
223
+ }
224
+ async function readBuiltFolder(path) {
225
+ const css = join(path, ASSETS.extensionCss);
226
+ const parts = {};
227
+ for (const name of await readdir(path)) if (/^extension-\d+\.js$/.test(name)) parts[name] = await readFile(join(path, name), "utf8");
228
+ return {
229
+ js: await readFile(join(path, ASSETS.extension), "utf8"),
230
+ css: existsSync(css) ? await readFile(css, "utf8") : "",
231
+ parts
232
+ };
112
233
  }
113
- // src/dev-history.ts
114
- const DAY_MS = 864e5;
115
- const MAX_TRACES = 1e5;
116
- const FLUSH_MS = 250;
117
- const PRUNE_MS = 18e5;
118
- const VOLUME_BUCKETS = 48;
119
- const DEFAULT_LIMIT = 100;
120
- const MAX_LIMIT = 500;
121
- const MAX_FACET_VALUES = 30;
122
- const MAX_EXPORT_ROWS = 1e5;
123
- const OUTCOMES = /* @__PURE__ */ new Set([
124
- "ok",
125
- "client",
126
- "server"
127
- ]);
128
234
  /**
129
- * SQLite from whichever runtime is running: `bun:sqlite` under Bun, and
130
- * `node:sqlite` under Node, which is what runs Vite's dev server. Both are
131
- * imported by a variable name so bundlers leave them alone.
235
+ * How the extensions are served, by `brick dev` and from a `brick build`
236
+ * folder alike. The app's alone is served as it is. Otherwise each that built
237
+ * is `extension-<index>.js`, `extension.js` lists them for the page to load
238
+ * and merge, and their styles are served together. `version` is added to each
239
+ * part's address, so a rebuilt one is fetched again.
132
240
  */
133
- async function openDatabase(file) {
134
- if (typeof Bun !== "undefined") {
135
- const { Database } = await import("bun:sqlite");
136
- return new Database(file, { create: true });
137
- }
138
- const specifier = "node:sqlite";
139
- const emit = process.emitWarning;
140
- process.emitWarning = ((warning, ...rest) => {
141
- if (typeof warning === "string" && warning.includes("SQLite")) return;
142
- return emit.call(process, warning, ...rest);
143
- });
144
- try {
145
- const { DatabaseSync } = await import(specifier);
146
- return new DatabaseSync(file);
147
- } finally {
148
- process.emitWarning = emit;
149
- }
241
+ function layoutParts(parts, version = "") {
242
+ if (parts.length === 1 && !parts[0].plugin) return parts[0].built;
243
+ const built = parts.flatMap((part, index) => part.built ? [{
244
+ ...part,
245
+ built: part.built,
246
+ file: `extension-${index}.js`
247
+ }] : []);
248
+ if (!built.length) return void 0;
249
+ return {
250
+ js: extensionManifest(built.map((part) => ({
251
+ name: part.name,
252
+ src: `./${part.file}${version}`,
253
+ plugin: part.plugin
254
+ }))),
255
+ css: built.map((part) => part.built.css).join(""),
256
+ parts: Object.fromEntries(built.map((part) => [part.file, part.built.js]))
257
+ };
150
258
  }
151
259
  /**
152
- * Open the request history, or return undefined when it is turned off or this
153
- * runtime has no SQLite. Never throws: the dashboard works without history.
260
+ * The extension as the dashboard serves it. From source it is built here, and
261
+ * rebuilt as its folder changes when watching; from a `brick build` folder it
262
+ * is read as it is. A failed build keeps the error to show on the page.
154
263
  */
155
- async function openHistory(options) {
156
- if (!(options.days > 0)) return void 0;
157
- try {
158
- const folder = join(options.directory, ".brick");
159
- mkdirSync(folder, { recursive: true });
160
- const ignore = join(folder, ".gitignore");
161
- if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
162
- return new DevHistory(await openDatabase(join(folder, "telemetry.sqlite")), options.days);
163
- } catch (error) {
164
- const reason = error instanceof Error ? error.message : String(error);
165
- options.warn?.(`[Brick-TS] Request history is unavailable (${reason}). It needs Bun, or Node 22.5 or later. Continuing without it.`);
166
- return;
264
+ var DashboardExtensionHost = class {
265
+ #path;
266
+ #warn;
267
+ #listeners = /* @__PURE__ */ new Set();
268
+ #watcher;
269
+ #timer;
270
+ #pending = Promise.resolve();
271
+ revision = 0;
272
+ built;
273
+ error;
274
+ constructor(path, warn) {
275
+ this.#path = resolve(path);
276
+ this.#warn = warn;
167
277
  }
168
- }
169
- const text = (value) => value === null || value === void 0 ? void 0 : String(value);
170
- const number = (value) => value === null || value === void 0 ? void 0 : Number(value);
171
- function percentile(sorted, fraction) {
172
- if (sorted.length === 0) return 0;
173
- const position = (sorted.length - 1) * fraction;
174
- const lower = Math.floor(position);
175
- const upper = Math.ceil(position);
176
- return sorted[lower] + (sorted[upper] - sorted[lower]) * (position - lower);
177
- }
178
- const OUTCOME_SQL = {
179
- server: "(status = 'error' OR http_status >= 500)",
180
- client: "(status != 'error' AND http_status >= 400 AND http_status < 500)",
181
- ok: "(status != 'error' AND (http_status IS NULL OR http_status < 400))"
182
- };
183
- /** The outcome of each row, for counting; agrees with OUTCOME_SQL. */
184
- const OUTCOME_CASE = `CASE
185
- WHEN status = 'error' OR http_status >= 500 THEN 'server'
186
- WHEN http_status >= 400 AND http_status < 500 THEN 'client'
187
- ELSE 'ok' END`;
188
- const FACET_COLUMNS = {
189
- outcome: OUTCOME_CASE,
190
- method: "method",
191
- service: "service",
192
- endpoint: "endpoint"
193
- };
194
- /** The WHERE clause for a query, leaving out one filter when counting its facet. */
195
- function filterSql(query, skip) {
196
- const clauses = ["start_ms >= ?", "start_ms <= ?"];
197
- const params = [query.from, query.to];
198
- const anyOf = (column, values) => {
199
- if (!values || values.length === 0) return;
200
- clauses.push(`${column} IN (${values.map(() => "?").join(", ")})`);
201
- params.push(...values);
202
- };
203
- if (skip !== "endpoint") anyOf("endpoint", query.endpoints);
204
- if (skip !== "method") anyOf("method", query.methods);
205
- if (skip !== "service") anyOf("service", query.services);
206
- if (skip !== "outcome" && query.outcomes && query.outcomes.length > 0) clauses.push(`(${query.outcomes.map((outcome) => OUTCOME_SQL[outcome]).join(" OR ")})`);
207
- if (query.minMs !== void 0 && query.minMs > 0) {
208
- clauses.push("duration_ms >= ?");
209
- params.push(query.minMs);
278
+ load() {
279
+ this.#pending = this.#pending.then(async () => {
280
+ const before = JSON.stringify([this.built, this.error]);
281
+ try {
282
+ if (isBuiltFolder(this.#path)) this.built = await readBuiltFolder(this.#path);
283
+ else {
284
+ if (!existsSync(this.#path)) throw new Error(`Brick: the dashboard extension ${this.#path} does not exist.`);
285
+ this.built = await buildDashboardExtension(this.#path, { warn: this.#warn });
286
+ }
287
+ this.error = void 0;
288
+ } catch (error) {
289
+ this.built = void 0;
290
+ this.error = error instanceof Error ? error.message : String(error);
291
+ this.#warn(`[Brick-TS] Dashboard extension: ${this.error}`);
292
+ }
293
+ if (JSON.stringify([this.built, this.error]) === before) return;
294
+ this.revision++;
295
+ for (const listener of this.#listeners) listener();
296
+ });
297
+ return this.#pending;
210
298
  }
211
- const needle = query.query?.trim();
212
- if (needle) {
213
- const pattern = `%${needle.replace(/[\\%_]/g, "\\$&")}%`;
214
- clauses.push("(endpoint LIKE ? ESCAPE '\\' OR path LIKE ? ESCAPE '\\' OR name LIKE ? ESCAPE '\\' OR action LIKE ? ESCAPE '\\' OR message LIKE ? ESCAPE '\\')");
215
- params.push(pattern, pattern, pattern, pattern, pattern);
299
+ watch() {
300
+ try {
301
+ this.#watcher = watch(dirname(this.#path), { recursive: true }, (_event, file) => {
302
+ if (file && /(^|[\\/])(node_modules|\.)/.test(file)) return;
303
+ clearTimeout(this.#timer);
304
+ this.#timer = setTimeout(() => void this.load(), 100);
305
+ });
306
+ } catch {}
216
307
  }
217
- return {
218
- sql: clauses.join(" AND "),
219
- params
220
- };
308
+ onChange(listener) {
309
+ this.#listeners.add(listener);
310
+ return () => {
311
+ this.#listeners.delete(listener);
312
+ };
313
+ }
314
+ close() {
315
+ clearTimeout(this.#timer);
316
+ this.#watcher?.close();
317
+ this.#listeners.clear();
318
+ }
319
+ };
320
+ /** The plugins' extensions by path, each once, in install order. */
321
+ function pluginDashboards(plugins) {
322
+ const wanted = /* @__PURE__ */ new Map();
323
+ for (const plugin of plugins) if (plugin.dashboard && !wanted.has(resolve(plugin.dashboard))) wanted.set(resolve(plugin.dashboard), plugin.name);
324
+ return wanted;
221
325
  }
222
- const LIST_COLUMNS = `trace_id, name, endpoint, method, route, path, http_status, generation,
223
- start_ms, end_ms, duration_ms, status, truncated, service, action, message`;
224
- function toHistoryTrace(row) {
225
- return {
226
- traceId: String(row.trace_id),
227
- name: String(row.name),
228
- endpoint: String(row.endpoint),
229
- method: text(row.method),
230
- route: text(row.route),
231
- path: text(row.path),
232
- httpStatus: number(row.http_status),
233
- generation: Number(row.generation),
234
- startMs: Number(row.start_ms),
235
- endMs: number(row.end_ms),
236
- durationMs: number(row.duration_ms),
237
- status: String(row.status),
238
- truncated: Number(row.truncated) === 1,
239
- service: text(row.service),
240
- action: text(row.action),
241
- message: text(row.message)
242
- };
326
+ /**
327
+ * The module the page loads when several extensions take part: it lists them,
328
+ * and the page imports each apart and merges them (`mergeExtensions` there).
329
+ */
330
+ function extensionManifest(parts) {
331
+ return `export const parts = ${JSON.stringify(parts)};\n`;
243
332
  }
244
333
  /**
245
- * Requests kept on disk between runs, for looking back over weeks
246
- * instead of the last few minutes. Writes are batched; reads see them.
334
+ * The app's extension and those of its plugins, served as one. With only the
335
+ * app's, it is served as it is; with plugins, each is built apart (a failed
336
+ * build leaves the others) and `extension.js` loads them all.
247
337
  */
248
- var DevHistory = class {
249
- days;
250
- #database;
251
- #pendingTraces = /* @__PURE__ */ new Map();
252
- #flushTimer;
253
- #pruneTimer;
254
- #closed = false;
255
- constructor(database, days) {
256
- this.#database = database;
257
- this.days = days;
258
- database.exec(`
259
- PRAGMA journal_mode = WAL;
260
- PRAGMA synchronous = NORMAL;
261
- PRAGMA busy_timeout = 2000;
262
- CREATE TABLE IF NOT EXISTS traces (
263
- trace_id TEXT PRIMARY KEY,
264
- name TEXT NOT NULL,
265
- endpoint TEXT NOT NULL,
266
- method TEXT,
267
- route TEXT,
268
- path TEXT,
269
- http_status INTEGER,
270
- generation INTEGER NOT NULL,
271
- start_ms INTEGER NOT NULL,
272
- end_ms INTEGER,
273
- duration_ms REAL,
274
- status TEXT NOT NULL,
275
- truncated INTEGER NOT NULL,
276
- spans TEXT NOT NULL,
277
- service TEXT,
278
- action TEXT,
279
- message TEXT
280
- );
281
- CREATE INDEX IF NOT EXISTS traces_start ON traces (start_ms);
282
- CREATE INDEX IF NOT EXISTS traces_endpoint ON traces (endpoint, start_ms);
283
- -- Earlier versions kept failures here; nothing reads them now.
284
- DROP TABLE IF EXISTS failures;
285
- `);
286
- this.#addMissingColumns();
287
- this.prune();
288
- this.#pruneTimer = setInterval(() => this.prune(), PRUNE_MS);
289
- this.#pruneTimer.unref?.();
338
+ var DashboardExtensions = class {
339
+ #warn;
340
+ #listeners = /* @__PURE__ */ new Set();
341
+ /** The app's own first, when it has one, then its plugins'. */
342
+ #parts = [];
343
+ revision = 0;
344
+ constructor(path, warn) {
345
+ this.#warn = warn;
346
+ if (path) this.#add("app", path, false);
290
347
  }
291
- /** A folder from an earlier version has the table without the newer columns. */
292
- #addMissingColumns() {
293
- const present = new Set(this.#database.prepare("PRAGMA table_info(traces)").all().map((column) => String(column.name)));
294
- for (const column of [
295
- "service",
296
- "action",
297
- "message"
298
- ]) if (!present.has(column)) this.#database.exec(`ALTER TABLE traces ADD COLUMN ${column} TEXT`);
348
+ #add(name, path, plugin) {
349
+ const host = new DashboardExtensionHost(path, this.#warn);
350
+ host.onChange(() => this.#changed());
351
+ this.#parts.push({
352
+ name,
353
+ path: resolve(path),
354
+ plugin,
355
+ host
356
+ });
357
+ return host;
299
358
  }
300
- /** Queue a finished request. A later save of the same request replaces it. */
301
- saveTrace(trace) {
302
- if (this.#closed) return;
303
- this.#pendingTraces.set(trace.traceId, trace);
304
- this.#scheduleFlush();
359
+ get #own() {
360
+ return this.#parts.find((part) => !part.plugin);
305
361
  }
306
- #scheduleFlush() {
307
- if (this.#flushTimer) return;
308
- this.#flushTimer = setTimeout(() => this.flush(), FLUSH_MS);
309
- this.#flushTimer.unref?.();
362
+ #changed() {
363
+ this.revision++;
364
+ for (const listener of this.#listeners) listener();
310
365
  }
311
- /** Write queued requests now. */
312
- flush() {
313
- if (this.#flushTimer) {
314
- clearTimeout(this.#flushTimer);
315
- this.#flushTimer = void 0;
316
- }
317
- if (this.#closed || this.#pendingTraces.size === 0) return;
318
- const traces = [...this.#pendingTraces.values()];
319
- this.#pendingTraces.clear();
320
- try {
321
- this.#database.exec("BEGIN");
322
- const saveTrace = this.#database.prepare(`INSERT OR REPLACE INTO traces (trace_id, name, endpoint, method, route, path,
323
- http_status, generation, start_ms, end_ms, duration_ms, status, truncated, spans,
324
- service, action, message)
325
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
326
- for (const trace of traces) saveTrace.run(trace.traceId, trace.name, trace.method && trace.route ? `${trace.method} ${trace.route}` : trace.name, trace.method ?? null, trace.route ?? null, trace.path ?? null, trace.httpStatus ?? null, trace.generation, trace.startMs, trace.endMs ?? null, trace.durationMs ?? null, trace.status, trace.truncated ? 1 : 0, JSON.stringify(trace.spans), trace.service ?? null, trace.action ?? null, trace.message ?? null);
327
- this.#database.exec("COMMIT");
328
- } catch {
329
- try {
330
- this.#database.exec("ROLLBACK");
331
- } catch {}
332
- }
366
+ get active() {
367
+ return this.#parts.length > 0;
333
368
  }
334
- /** Drop what is past retention, then the oldest beyond the size cap. */
335
- prune(now = Date.now()) {
336
- if (this.#closed) return;
337
- try {
338
- const cutoff = now - this.days * DAY_MS;
339
- this.#database.prepare("DELETE FROM traces WHERE start_ms < ?").run(cutoff);
340
- const count = Number(this.#database.prepare("SELECT COUNT(*) AS n FROM traces").get()?.n ?? 0);
341
- if (count > MAX_TRACES) this.#database.prepare("DELETE FROM traces WHERE trace_id IN (SELECT trace_id FROM traces ORDER BY start_ms ASC LIMIT ?)").run(count - MAX_TRACES);
342
- } catch {}
369
+ get built() {
370
+ return layoutParts(this.#parts.map((part) => ({
371
+ name: part.name,
372
+ plugin: part.plugin,
373
+ built: part.host.built
374
+ })), `?v=${this.revision}`);
343
375
  }
344
- info() {
345
- this.flush();
346
- const row = this.#database.prepare("SELECT COUNT(*) AS n, MIN(start_ms) AS oldest FROM traces").get();
347
- return {
348
- days: this.days,
349
- count: Number(row?.n ?? 0),
350
- oldestMs: number(row?.oldest)
351
- };
376
+ get error() {
377
+ const errors = this.#parts.flatMap((part) => part.host.error ? [this.#parts.length === 1 && !part.plugin ? part.host.error : `${part.name}: ${part.host.error}`] : []);
378
+ return errors.length ? errors.join("\n") : void 0;
352
379
  }
353
- /** Matching requests, without spans, and how many match in total. */
354
- traces(query) {
355
- this.flush();
356
- const { sql, params } = filterSql(query);
357
- const total = Number(this.#database.prepare(`SELECT COUNT(*) AS n FROM traces WHERE ${sql}`).get(...params)?.n ?? 0);
358
- const limit = Math.min(Math.max(query.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);
359
- const offset = Math.max(query.offset ?? 0, 0);
360
- const order = query.sort === "slowest" ? "duration_ms DESC, start_ms DESC" : "start_ms DESC";
361
- return {
362
- total,
363
- traces: this.#database.prepare(`SELECT ${LIST_COLUMNS}
364
- FROM traces WHERE ${sql} ORDER BY ${order} LIMIT ? OFFSET ?`).all(...params, limit, offset).map(toHistoryTrace)
365
- };
380
+ /** A file under `/assets/` this serves, or undefined. */
381
+ asset(name) {
382
+ if (name === ASSETS.extension) return this.built?.js;
383
+ if (name === ASSETS.extensionCss) return this.built?.css;
384
+ return this.built?.parts?.[name];
366
385
  }
367
- /** Counts for each filter over the range, ignoring that filter's own choice. */
368
- facets(query) {
369
- this.flush();
370
- const count = (facet) => {
371
- const { sql, params } = filterSql(query, facet);
372
- const column = FACET_COLUMNS[facet];
373
- return this.#database.prepare(`SELECT ${column} AS value, COUNT(*) AS n FROM traces
374
- WHERE ${sql} AND ${column} IS NOT NULL
375
- GROUP BY value ORDER BY n DESC, value ASC LIMIT ?`).all(...params, MAX_FACET_VALUES).map((row) => ({
376
- value: String(row.value),
377
- count: Number(row.n)
378
- }));
379
- };
380
- return {
381
- outcome: count("outcome"),
382
- method: count("method"),
383
- service: count("service"),
384
- endpoint: count("endpoint")
385
- };
386
+ /** Follow the app's plugins: build the extensions they ship, drop the rest. */
387
+ async setPlugins(plugins) {
388
+ const own = this.#own;
389
+ if (own && isBuiltFolder(own.path)) return;
390
+ const wanted = pluginDashboards(plugins);
391
+ const current = this.#parts.filter((part) => part.plugin);
392
+ if (current.length === wanted.size && current.every((part) => wanted.get(part.path) === part.name)) return;
393
+ for (const part of current) part.host.close();
394
+ this.#parts.splice(own ? 1 : 0);
395
+ const loads = [...wanted].map(([path, name]) => this.#add(name, path, true).load());
396
+ await Promise.all(loads);
397
+ this.#changed();
386
398
  }
387
- /** Matching requests per time bucket across the range, by outcome. */
388
- volume(query, buckets = VOLUME_BUCKETS) {
389
- this.flush();
390
- const { sql, params } = filterSql(query);
391
- const bucketMs = Math.max(Math.ceil((query.to - query.from) / buckets), 1);
392
- const result = Array.from({ length: buckets }, (_, index) => ({
393
- start: query.from + index * bucketMs,
394
- ok: 0,
395
- client: 0,
396
- server: 0
397
- }));
398
- const rows = this.#database.prepare(`SELECT CAST((start_ms - ?) / ? AS INTEGER) AS bucket, ${OUTCOME_CASE} AS outcome,
399
- COUNT(*) AS n
400
- FROM traces WHERE ${sql} GROUP BY bucket, outcome`).all(query.from, bucketMs, ...params);
401
- for (const row of rows) {
402
- const bucket = result[Math.min(Math.max(Number(row.bucket), 0), buckets - 1)];
403
- const outcome = String(row.outcome);
404
- if (bucket) bucket[outcome] += Number(row.n);
405
- }
406
- return result;
399
+ load() {
400
+ return Promise.all(this.#parts.map((part) => part.host.load())).then(() => void 0);
407
401
  }
408
- /** Every matching request, newest first, as CSV for a spreadsheet. */
409
- exportCsv(query) {
410
- this.flush();
411
- const { sql, params } = filterSql(query);
412
- const order = query.sort === "slowest" ? "duration_ms DESC, start_ms DESC" : "start_ms DESC";
413
- return tracesToCsv(this.#database.prepare(`SELECT ${LIST_COLUMNS}
414
- FROM traces WHERE ${sql} ORDER BY ${order} LIMIT ?`).all(...params, MAX_EXPORT_ROWS).map(toHistoryTrace));
402
+ /** Rebuild the app's own as its folder changes; plugins' are packages. */
403
+ watch() {
404
+ this.#own?.host.watch();
415
405
  }
416
- /** One request with all its spans. */
417
- trace(traceId) {
418
- this.flush();
419
- const row = this.#database.prepare(`SELECT ${LIST_COLUMNS}, spans FROM traces WHERE trace_id = ?`).get(traceId);
420
- if (!row) return void 0;
421
- const { endpoint: _endpoint, ...trace } = toHistoryTrace(row);
422
- return {
423
- ...trace,
424
- spans: JSON.parse(String(row.spans))
406
+ onChange(listener) {
407
+ this.#listeners.add(listener);
408
+ return () => {
409
+ this.#listeners.delete(listener);
425
410
  };
426
411
  }
427
- /** How many requests match, how many failed, and how long they took. */
428
- summary(query) {
429
- this.flush();
430
- const { sql, params } = filterSql(query);
431
- let total = 0;
432
- let clientErrors = 0;
433
- let serverErrors = 0;
434
- const counts = this.#database.prepare(`SELECT ${OUTCOME_CASE} AS outcome, COUNT(*) AS n
435
- FROM traces WHERE ${sql} GROUP BY outcome`).all(...params);
436
- for (const row of counts) {
437
- const n = Number(row.n);
438
- total += n;
439
- if (row.outcome === "client") clientErrors = n;
440
- if (row.outcome === "server") serverErrors = n;
441
- }
442
- const durations = this.#database.prepare(`SELECT duration_ms FROM traces
443
- WHERE ${sql} AND duration_ms IS NOT NULL ORDER BY duration_ms`).all(...params).map((row) => Number(row.duration_ms));
412
+ close() {
413
+ for (const part of this.#parts) part.host.close();
414
+ this.#listeners.clear();
415
+ }
416
+ };
417
+ // src/dev-docs.ts
418
+ const PACKAGES = ["fumadocs-core", "@mdx-js/mdx"];
419
+ /** What the docs are called when their folder does not name them. */
420
+ const DEFAULT_TITLE = "Docs";
421
+ const PAGE_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".mdx"]);
422
+ const IMAGE_TYPES = {
423
+ ".png": "image/png",
424
+ ".jpg": "image/jpeg",
425
+ ".jpeg": "image/jpeg",
426
+ ".gif": "image/gif",
427
+ ".webp": "image/webp",
428
+ ".avif": "image/avif",
429
+ ".svg": "image/svg+xml",
430
+ ".ico": "image/x-icon"
431
+ };
432
+ const REFRESH_DELAY_MS = 100;
433
+ async function loadFumadocs() {
434
+ try {
435
+ const [source, matter, plugins, search, mdx] = await Promise.all([
436
+ import("fumadocs-core/source"),
437
+ import("fumadocs-core/content/md/frontmatter"),
438
+ import("fumadocs-core/mdx-plugins"),
439
+ import("fumadocs-core/search/server"),
440
+ import("@mdx-js/mdx")
441
+ ]);
444
442
  return {
445
- total,
446
- clientErrors,
447
- serverErrors,
448
- medianMs: percentile(durations, .5),
449
- p95Ms: percentile(durations, .95)
443
+ loader: source.loader,
444
+ frontmatter: matter.frontmatter,
445
+ plugins,
446
+ createSearchAPI: search.createSearchAPI,
447
+ compile: mdx.compile
450
448
  };
449
+ } catch (error) {
450
+ if (error.code === "ERR_MODULE_NOT_FOUND" || /Cannot find (module|package)/.test(String(error?.message))) return [...PACKAGES];
451
+ throw error;
451
452
  }
452
- /** Write what is queued and release the database. */
453
- close() {
454
- if (this.#closed) return;
455
- this.flush();
456
- this.#closed = true;
457
- clearInterval(this.#pruneTimer);
458
- try {
459
- this.#database.close();
460
- } catch {}
461
- }
453
+ }
454
+ const humanize = (name) => {
455
+ const spaced = name.replace(/[-_]+/g, " ").trim();
456
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
462
457
  };
463
- /** Query-string values the dashboard sends, parsed defensively. */
464
- function parseHistoryQuery(params, now = Date.now()) {
465
- const integer = (name) => {
466
- const raw = params.get(name);
467
- if (raw === null || raw.trim() === "") return void 0;
468
- const value = Number(raw);
469
- return Number.isFinite(value) ? value : void 0;
470
- };
471
- const all = (name) => {
472
- const values = params.getAll(name).filter((value) => value !== "");
473
- return values.length > 0 ? values : void 0;
474
- };
475
- const to = integer("to") ?? now;
458
+ const H1 = /^#\s+(.+?)\s*#*\s*$/;
459
+ /**
460
+ * The first `# Heading` outside code fences: its text, and the content without
461
+ * it. The page shows its title above the content, so a heading that only
462
+ * repeats the title would appear twice.
463
+ */
464
+ function firstHeading(content) {
465
+ const lines = content.split("\n");
466
+ let fenced = false;
467
+ let seenText = false;
468
+ for (const [index, line] of lines.entries()) if (/^\s*(```|~~~)/.test(line)) {
469
+ fenced = !fenced;
470
+ seenText = true;
471
+ } else if (!fenced) {
472
+ const match = H1.exec(line);
473
+ if (match) {
474
+ const rest = [...lines.slice(0, index), ...lines.slice(index + 1)];
475
+ if (rest[index]?.trim() === "") rest.splice(index, 1);
476
+ return {
477
+ text: match[1],
478
+ rest: rest.join("\n"),
479
+ leading: !seenText
480
+ };
481
+ }
482
+ if (line.trim() !== "") seenText = true;
483
+ }
484
+ }
485
+ async function scan(root, fumadocs, warn) {
486
+ const pages = [];
487
+ const metas = [];
488
+ async function visit(directory) {
489
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
490
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
491
+ const absolute = join(directory, entry.name);
492
+ const path = relative(root, absolute).split(sep).join("/");
493
+ if (entry.isDirectory()) await visit(absolute);
494
+ else if (entry.name === "meta.json") try {
495
+ const data = JSON.parse(await readFile(absolute, "utf8"));
496
+ if (data && typeof data === "object") metas.push({
497
+ path,
498
+ data
499
+ });
500
+ } catch (error) {
501
+ warn(`[Brick-TS] Skipping docs ${path}: ${errorMessage(error)}`);
502
+ }
503
+ else if (PAGE_EXTENSIONS.has(extname(entry.name))) {
504
+ const text = await readFile(absolute, "utf8");
505
+ let data = {};
506
+ let content = text;
507
+ try {
508
+ const parsed = fumadocs.frontmatter(text);
509
+ data = parsed.data;
510
+ content = parsed.content;
511
+ } catch (error) {
512
+ warn(`[Brick-TS] Ignoring the frontmatter of docs ${path}: ${errorMessage(error)}`);
513
+ }
514
+ const name = basename(entry.name, extname(entry.name));
515
+ const heading = firstHeading(content);
516
+ const given = typeof data.title === "string" && data.title ? data.title : void 0;
517
+ const title = given ?? heading?.text ?? humanize(name === "index" ? basename(dirname(path)) || "Home" : name);
518
+ if (heading && (!given || heading.leading && heading.text === given)) content = heading.rest;
519
+ pages.push({
520
+ path,
521
+ absolute,
522
+ title,
523
+ description: typeof data.description === "string" ? data.description : void 0,
524
+ content,
525
+ data
526
+ });
527
+ }
528
+ }
529
+ }
530
+ await visit(root);
476
531
  return {
477
- to,
478
- from: integer("from") ?? to - 7 * DAY_MS,
479
- endpoints: all("endpoint"),
480
- methods: all("method"),
481
- services: all("service"),
482
- outcomes: all("outcome")?.filter((value) => OUTCOMES.has(value)),
483
- minMs: integer("minMs"),
484
- query: params.get("q") || void 0,
485
- sort: params.get("sort") === "slowest" ? "slowest" : "recent",
486
- limit: integer("limit"),
487
- offset: integer("offset")
532
+ pages,
533
+ metas
488
534
  };
489
535
  }
490
- // src/dev-dashboard-shell.ts
536
+ function errorMessage(error) {
537
+ return error instanceof Error ? error.message : String(error);
538
+ }
539
+ function walk(node, visit) {
540
+ visit(node);
541
+ for (const child of node.children ?? []) walk(child, visit);
542
+ }
543
+ /** Ways a link inside a page can point at another page or a local image. */
544
+ function resolveInside(from, href) {
545
+ if (isExternalHref(href) || href.startsWith("#")) return void 0;
546
+ if (href.startsWith("/")) return void 0;
547
+ const [target] = href.split(/[?#]/);
548
+ if (!target) return void 0;
549
+ const resolved = posix.normalize(posix.join(posix.dirname(from), target));
550
+ return resolved.startsWith("../") ? void 0 : resolved;
551
+ }
491
552
  /**
492
- * The page the dashboard serves at `/`. The React app and its styles load from
493
- * `/assets/`; the inline script applies the saved theme before first paint. The
494
- * import map hands the project's own modules (its docs components and its
495
- * dashboard extension), bundled apart from the dashboard, the dashboard's copy
496
- * of React and its UI kit, so there is one of each on the page.
497
- *
498
- * `extension` describes the project's extension: `revision` changes with every
499
- * rebuild (the page reloads when it does), `js` and `css` say what it built.
500
- * `theme` is whether `/assets/brick-theme.css` has token values to apply.
553
+ * The page tree and compiled pages of one docs folder. It watches the folder,
554
+ * so edits show in the dashboard as they are saved.
501
555
  */
502
- function dashboardShell(options = {}) {
503
- const { extension, theme } = options;
504
- const version = extension ? `?v=${extension.revision}` : "";
505
- return `<!doctype html>
506
- <html lang="en">
507
- <head>
508
- <meta charset="utf-8">
509
- <meta name="viewport" content="width=device-width, initial-scale=1">
510
- <title>Brick dev</title>
511
- <link rel="icon" href="data:,">
512
- <script>
513
- (function () {
514
- try {
515
- var theme = localStorage.getItem("brick-dashboard-theme");
516
- var dark = theme === "dark" || (theme !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches);
517
- if (dark) document.documentElement.classList.add("dark");
518
- } catch (error) {}
519
- })();
520
- <\/script>
521
- <link rel="stylesheet" href="/assets/app.css">
522
- ${extension?.css ? `<link rel="stylesheet" href="/assets/extension.css${version}">\n` : ""}${theme ? `<link rel="stylesheet" href="/assets/brick-theme.css" data-brick-theme>\n` : ""}${extension ? `<meta name="brick-extension" data-revision="${extension.revision}"${extension.js ? ` data-src="/assets/extension.js${version}"` : ""}>\n` : ""}<script type="importmap">
523
- {"imports":{"react":"/assets/react.js","react/jsx-runtime":"/assets/react-jsx-runtime.js","react/jsx-dev-runtime":"/assets/react-jsx-runtime.js","react-dom":"/assets/react-dom.js","react-dom/client":"/assets/react-dom-client.js","@brickkit/cli/dashboard":"/assets/kit.js"}}
524
- <\/script>
525
- </head>
526
- <body>
527
- <div id="root"></div>
528
- <script type="module" src="/assets/app.js"><\/script>
529
- </body>
530
- </html>
531
- `;
532
- }
533
- // src/dashboard-access.ts
534
- /** How long the app's `authorize` may take before the request is refused. */
535
- const AUTHORIZE_TIMEOUT_MS = 5e3;
536
- /** Whether `host` can only be reached from the machine it runs on. */
537
- function isLoopbackHost(host) {
538
- const name = host.toLowerCase();
539
- return name === "localhost" || name === "::1" || name === "[::1]" || /^127(\.\d{1,3}){3}$/.test(name);
540
- }
541
- const NOT_COPIED = /* @__PURE__ */ new Set([
542
- "set-cookie",
543
- "content-length",
544
- "content-encoding",
545
- "transfer-encoding",
546
- "connection",
547
- "keep-alive"
548
- ]);
549
- const digest = (value) => createHash("sha256").update(value).digest();
550
- /** Whether `candidate` is one of `tokens`, in the same time whichever it is. */
551
- function isToken(candidate, tokens) {
552
- if (candidate === void 0) return false;
553
- const given = digest(candidate);
554
- let match = false;
555
- for (const token of tokens) if (timingSafeEqual(given, digest(token))) match = true;
556
- return match;
557
- }
558
- /** The secret in an `Authorization` header: a Bearer token, or a Basic password. */
559
- function credential(request) {
560
- const header = request.headers.authorization;
561
- if (!header) return void 0;
562
- const space = header.indexOf(" ");
563
- if (space < 0) return void 0;
564
- const scheme = header.slice(0, space).toLowerCase();
565
- const value = header.slice(space + 1).trim();
566
- if (scheme === "bearer") return value;
567
- if (scheme === "basic") {
568
- const decoded = Buffer.from(value, "base64").toString("utf8");
569
- const colon = decoded.indexOf(":");
570
- return colon < 0 ? void 0 : decoded.slice(colon + 1);
571
- }
572
- }
573
- /** The request as the app's `authorize` sees it: standard, with no body. */
574
- function webRequest(request) {
575
- const headers = new Headers();
576
- for (const [name, value] of Object.entries(request.headers)) {
577
- if (value === void 0) continue;
578
- try {
579
- headers.set(name, Array.isArray(value) ? value.join(", ") : value);
580
- } catch {}
581
- }
582
- const forwarded = request.headers["x-forwarded-proto"];
583
- const protocol = (Array.isArray(forwarded) ? forwarded[0] : forwarded)?.split(",")[0]?.trim() === "https" ? "https" : "http";
584
- const host = request.headers.host ?? "localhost";
585
- let url;
586
- try {
587
- url = new URL(request.url ?? "/", `${protocol}://${host}`).href;
588
- } catch {
589
- url = `${protocol}://localhost${request.url ?? "/"}`;
556
+ var DevDocs = class {
557
+ #root;
558
+ #documentation;
559
+ #base;
560
+ #fumadocs;
561
+ #warn;
562
+ #listeners = /* @__PURE__ */ new Set();
563
+ #watchers = [];
564
+ #loader;
565
+ #pages = /* @__PURE__ */ new Map();
566
+ #byPath = /* @__PURE__ */ new Map();
567
+ #compiled = /* @__PURE__ */ new Map();
568
+ #search;
569
+ #timer;
570
+ #refreshing = Promise.resolve();
571
+ #closed = false;
572
+ #title = DEFAULT_TITLE;
573
+ revision = 0;
574
+ constructor(base, documentation, fumadocs, warn) {
575
+ this.#base = base;
576
+ this.#documentation = documentation;
577
+ this.#root = resolve(base, documentation.dir);
578
+ this.#fumadocs = fumadocs;
579
+ this.#warn = warn;
590
580
  }
591
- return new Request(url, {
592
- method: request.method ?? "GET",
593
- headers
594
- });
595
- }
596
- const refusal = (status, body, headers = {}) => ({
597
- allowed: false,
598
- status,
599
- body,
600
- headers: {
601
- "content-type": "text/plain; charset=utf-8",
602
- ...headers
581
+ async refresh() {
582
+ this.#refreshing = this.#refreshing.then(() => this.#scan());
583
+ await this.#refreshing;
603
584
  }
604
- });
605
- /**
606
- * The check for the dashboard's requests. A request passes with a valid token,
607
- * or when the app's `authorize` returns `true`. Anything else is answered:
608
- * what `authorize` returned if it returned a `Response`, else 401 (with a
609
- * browser sign-in prompt when tokens are in use), and 503 when `authorize`
610
- * threw or ran out of time, since a check that cannot answer must not let
611
- * anyone in.
612
- */
613
- function createAccess(auth, onError = () => {}, timeoutMs = AUTHORIZE_TIMEOUT_MS) {
614
- const tokens = auth.token === void 0 ? [] : typeof auth.token === "string" ? [auth.token] : [...auth.token];
615
- const prompt = tokens.length > 0 ? { "www-authenticate": "Basic realm=\"Brick dashboard\", charset=\"UTF-8\"" } : {};
616
- return async (request) => {
617
- if (tokens.length > 0 && isToken(credential(request), tokens)) return { allowed: true };
618
- if (!auth.authorize) return refusal(401, "Unauthorized", prompt);
619
- let decision;
620
- let timer;
621
- try {
622
- decision = await Promise.race([Promise.resolve(auth.authorize(webRequest(request))), new Promise((_, reject) => {
623
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error("dashboard authorize timed out")), timeoutMs);
624
- })]);
625
- } catch (error) {
626
- onError(error);
627
- return refusal(503, "Sign-in is unavailable.");
628
- } finally {
629
- clearTimeout(timer);
585
+ async #scan() {
586
+ const { pages, metas } = await scan(this.#root, this.#fumadocs, this.#warn);
587
+ if (this.#closed) return;
588
+ const source = this.#fumadocs.loader({
589
+ baseUrl: "/",
590
+ source: { files: [...pages.map((page) => ({
591
+ type: "page",
592
+ path: page.path,
593
+ data: {
594
+ ...page.data,
595
+ title: page.title,
596
+ description: page.description
597
+ }
598
+ })), ...metas.map((meta) => ({
599
+ type: "meta",
600
+ path: meta.path,
601
+ data: meta.data
602
+ }))] }
603
+ });
604
+ this.#loader = source;
605
+ this.#pages = /* @__PURE__ */ new Map();
606
+ this.#byPath = /* @__PURE__ */ new Map();
607
+ for (const page of this.#loader.getPages()) {
608
+ const slug = page.slugs.join("/");
609
+ const file = pages.find((candidate) => candidate.path === page.path);
610
+ if (!file) continue;
611
+ this.#pages.set(slug, file);
612
+ this.#byPath.set(file.path, slug);
630
613
  }
631
- if (decision === true) return { allowed: true };
632
- if (decision instanceof Response) {
633
- const headers = {};
634
- decision.headers.forEach((value, name) => {
635
- if (!NOT_COPIED.has(name)) headers[name] = value;
636
- });
637
- const cookies = decision.headers.getSetCookie();
638
- if (cookies.length > 0) headers["set-cookie"] = cookies;
639
- return {
640
- allowed: false,
641
- status: decision.status,
642
- headers,
643
- body: new Uint8Array(await decision.arrayBuffer())
644
- };
614
+ this.#compiled.clear();
615
+ this.#search = void 0;
616
+ const tree = this.#loader.getPageTree();
617
+ this.#title = typeof tree.name === "string" ? tree.name : DEFAULT_TITLE;
618
+ this.revision++;
619
+ for (const listener of this.#listeners) listener();
620
+ }
621
+ watch() {
622
+ const changed = () => {
623
+ clearTimeout(this.#timer);
624
+ this.#timer = setTimeout(() => {
625
+ this.refresh().catch((error) => this.#warn(`[Brick-TS] Docs: ${errorMessage(error)}`));
626
+ }, REFRESH_DELAY_MS);
627
+ };
628
+ const folders = [this.#root];
629
+ if (this.#documentation.components) folders.push(dirname(this.#componentsPath()));
630
+ for (const [index, folder] of folders.entries()) try {
631
+ this.#watchers.push(watch(folder, { recursive: index === 0 }, () => changed()));
632
+ } catch {
633
+ try {
634
+ this.#watchers.push(watch(folder, () => changed()));
635
+ } catch {}
645
636
  }
646
- return refusal(401, "Unauthorized", prompt);
647
- };
648
- }
649
- // src/dev-docs.ts
650
- const PACKAGES = ["fumadocs-core", "@mdx-js/mdx"];
651
- const PAGE_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".mdx"]);
652
- const IMAGE_TYPES = {
653
- ".png": "image/png",
654
- ".jpg": "image/jpeg",
655
- ".jpeg": "image/jpeg",
656
- ".gif": "image/gif",
657
- ".webp": "image/webp",
658
- ".avif": "image/avif",
659
- ".svg": "image/svg+xml",
660
- ".ico": "image/x-icon"
661
- };
662
- const REFRESH_DELAY_MS = 100;
663
- async function loadFumadocs() {
664
- try {
665
- const [source, matter, plugins, search, mdx] = await Promise.all([
666
- import("fumadocs-core/source"),
667
- import("fumadocs-core/content/md/frontmatter"),
668
- import("fumadocs-core/mdx-plugins"),
669
- import("fumadocs-core/search/server"),
670
- import("@mdx-js/mdx")
671
- ]);
672
- return {
673
- loader: source.loader,
674
- frontmatter: matter.frontmatter,
675
- plugins,
676
- createSearchAPI: search.createSearchAPI,
677
- compile: mdx.compile
678
- };
679
- } catch (error) {
680
- if (error.code === "ERR_MODULE_NOT_FOUND" || /Cannot find (module|package)/.test(String(error?.message))) return [...PACKAGES];
681
- throw error;
682
- }
683
- }
684
- const humanize = (name) => {
685
- const spaced = name.replace(/[-_]+/g, " ").trim();
686
- return spaced.charAt(0).toUpperCase() + spaced.slice(1);
687
- };
688
- const H1 = /^#\s+(.+?)\s*#*\s*$/;
689
- /**
690
- * The first `# Heading` outside code fences: its text, and the content without
691
- * it. The page shows its title above the content, so a heading that only
692
- * repeats the title would appear twice.
693
- */
694
- function firstHeading(content) {
695
- const lines = content.split("\n");
696
- let fenced = false;
697
- let seenText = false;
698
- for (const [index, line] of lines.entries()) if (/^\s*(```|~~~)/.test(line)) {
699
- fenced = !fenced;
700
- seenText = true;
701
- } else if (!fenced) {
702
- const match = H1.exec(line);
703
- if (match) {
704
- const rest = [...lines.slice(0, index), ...lines.slice(index + 1)];
705
- if (rest[index]?.trim() === "") rest.splice(index, 1);
706
- return {
707
- text: match[1],
708
- rest: rest.join("\n"),
709
- leading: !seenText
710
- };
711
- }
712
- if (line.trim() !== "") seenText = true;
713
- }
714
- }
715
- async function scan(root, fumadocs, warn) {
716
- const pages = [];
717
- const metas = [];
718
- async function visit(directory) {
719
- for (const entry of await readdir(directory, { withFileTypes: true })) {
720
- if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
721
- const absolute = join(directory, entry.name);
722
- const path = relative(root, absolute).split(sep).join("/");
723
- if (entry.isDirectory()) await visit(absolute);
724
- else if (entry.name === "meta.json") try {
725
- const data = JSON.parse(await readFile(absolute, "utf8"));
726
- if (data && typeof data === "object") metas.push({
727
- path,
728
- data
729
- });
730
- } catch (error) {
731
- warn(`[Brick-TS] Skipping docs ${path}: ${errorMessage(error)}`);
732
- }
733
- else if (PAGE_EXTENSIONS.has(extname(entry.name))) {
734
- const text = await readFile(absolute, "utf8");
735
- let data = {};
736
- let content = text;
737
- try {
738
- const parsed = fumadocs.frontmatter(text);
739
- data = parsed.data;
740
- content = parsed.content;
741
- } catch (error) {
742
- warn(`[Brick-TS] Ignoring the frontmatter of docs ${path}: ${errorMessage(error)}`);
743
- }
744
- const name = basename(entry.name, extname(entry.name));
745
- const heading = firstHeading(content);
746
- const given = typeof data.title === "string" && data.title ? data.title : void 0;
747
- const title = given ?? heading?.text ?? humanize(name === "index" ? basename(dirname(path)) || "Home" : name);
748
- if (heading && (!given || heading.leading && heading.text === given)) content = heading.rest;
749
- pages.push({
750
- path,
751
- absolute,
752
- title,
753
- description: typeof data.description === "string" ? data.description : void 0,
754
- content,
755
- data
756
- });
757
- }
758
- }
759
- }
760
- await visit(root);
761
- return {
762
- pages,
763
- metas
764
- };
765
- }
766
- function errorMessage(error) {
767
- return error instanceof Error ? error.message : String(error);
768
- }
769
- function walk(node, visit) {
770
- visit(node);
771
- for (const child of node.children ?? []) walk(child, visit);
772
- }
773
- /** Ways a link inside a page can point at another page or a local image. */
774
- function resolveInside(from, href) {
775
- if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("#")) return void 0;
776
- if (href.startsWith("/")) return void 0;
777
- const [target] = href.split(/[?#]/);
778
- if (!target) return void 0;
779
- const resolved = posix.normalize(posix.join(posix.dirname(from), target));
780
- return resolved.startsWith("../") ? void 0 : resolved;
781
- }
782
- /**
783
- * The page tree and compiled pages of one docs folder. It watches the folder,
784
- * so edits show in the dashboard as they are saved.
785
- */
786
- var DevDocs = class {
787
- #root;
788
- #documentation;
789
- /** Relative paths in `documentation` start here: the app entry's folder. */
790
- #base;
791
- #fumadocs;
792
- #warn;
793
- #listeners = /* @__PURE__ */ new Set();
794
- #watchers = [];
795
- #loader;
796
- #pages = /* @__PURE__ */ new Map();
797
- #byPath = /* @__PURE__ */ new Map();
798
- #compiled = /* @__PURE__ */ new Map();
799
- #search;
800
- #timer;
801
- #refreshing = Promise.resolve();
802
- #closed = false;
803
- #title = "Docs";
804
- revision = 0;
805
- constructor(base, documentation, fumadocs, warn) {
806
- this.#base = base;
807
- this.#documentation = documentation;
808
- this.#root = resolve(base, documentation.dir);
809
- this.#fumadocs = fumadocs;
810
- this.#warn = warn;
811
- }
812
- /** Read the folder again and tell listeners. */
813
- async refresh() {
814
- this.#refreshing = this.#refreshing.then(() => this.#scan());
815
- await this.#refreshing;
816
- }
817
- async #scan() {
818
- const { pages, metas } = await scan(this.#root, this.#fumadocs, this.#warn);
819
- if (this.#closed) return;
820
- const source = this.#fumadocs.loader({
821
- baseUrl: "/",
822
- source: { files: [...pages.map((page) => ({
823
- type: "page",
824
- path: page.path,
825
- data: {
826
- ...page.data,
827
- title: page.title,
828
- description: page.description
829
- }
830
- })), ...metas.map((meta) => ({
831
- type: "meta",
832
- path: meta.path,
833
- data: meta.data
834
- }))] }
835
- });
836
- this.#loader = source;
837
- this.#pages = /* @__PURE__ */ new Map();
838
- this.#byPath = /* @__PURE__ */ new Map();
839
- for (const page of this.#loader.getPages()) {
840
- const slug = page.slugs.join("/");
841
- const file = pages.find((candidate) => candidate.path === page.path);
842
- if (!file) continue;
843
- this.#pages.set(slug, file);
844
- this.#byPath.set(file.path, slug);
845
- }
846
- this.#compiled.clear();
847
- this.#search = void 0;
848
- const tree = this.#loader.getPageTree();
849
- this.#title = typeof tree.name === "string" ? tree.name : "Docs";
850
- this.revision++;
851
- for (const listener of this.#listeners) listener();
852
- }
853
- /** Start watching the folder, and the project's components module. */
854
- watch() {
855
- const changed = () => {
856
- clearTimeout(this.#timer);
857
- this.#timer = setTimeout(() => {
858
- this.refresh().catch((error) => this.#warn(`[Brick-TS] Docs: ${errorMessage(error)}`));
859
- }, REFRESH_DELAY_MS);
860
- };
861
- const folders = [this.#root];
862
- if (this.#documentation.components) folders.push(dirname(this.#componentsPath()));
863
- for (const [index, folder] of folders.entries()) try {
864
- this.#watchers.push(watch(folder, { recursive: index === 0 }, () => changed()));
865
- } catch {
866
- try {
867
- this.#watchers.push(watch(folder, () => changed()));
868
- } catch {}
869
- }
870
- }
871
- onChange(listener) {
872
- this.#listeners.add(listener);
873
- return () => {
874
- this.#listeners.delete(listener);
637
+ }
638
+ onChange(listener) {
639
+ this.#listeners.add(listener);
640
+ return () => {
641
+ this.#listeners.delete(listener);
875
642
  };
876
643
  }
877
644
  snapshot() {
@@ -950,19 +717,18 @@ var DevDocs = class {
950
717
  * This covers markdown links and the `href` of components such as `<Card>`.
951
718
  */
952
719
  #rewriteLinks(tree, from) {
953
- const file = (resolved) => `/api/docs/files/${resolved.split("/").map(encodeURIComponent).join("/")}`;
954
720
  walk(tree, (node) => {
955
721
  if (node.type === "link" && node.url !== void 0) node.url = this.#route(from, node.url) ?? node.url;
956
722
  else if (node.type === "image" && node.url !== void 0) {
957
723
  const resolved = resolveInside(from, node.url);
958
- if (resolved !== void 0) node.url = file(resolved);
724
+ if (resolved !== void 0) node.url = docsFileUrl(resolved);
959
725
  } else if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") for (const attribute of node.attributes ?? []) {
960
726
  if (attribute.type !== "mdxJsxAttribute") continue;
961
727
  if (typeof attribute.value !== "string") continue;
962
728
  if (attribute.name === "href") attribute.value = this.#route(from, attribute.value) ?? attribute.value;
963
729
  else if (attribute.name === "src" && node.name === "img") {
964
730
  const resolved = resolveInside(from, attribute.value);
965
- if (resolved !== void 0) attribute.value = file(resolved);
731
+ if (resolved !== void 0) attribute.value = docsFileUrl(resolved);
966
732
  }
967
733
  }
968
734
  });
@@ -975,10 +741,10 @@ var DevDocs = class {
975
741
  */
976
742
  #route(from, href) {
977
743
  const hashAt = href.indexOf("#");
978
- const hash = hashAt >= 0 ? href.slice(hashAt) : "";
744
+ const anchor = hashAt >= 0 ? decode(href.slice(hashAt + 1)) : void 0;
979
745
  const target = (hashAt >= 0 ? href.slice(0, hashAt) : href).split("?")[0] ?? "";
980
- const route = (slug) => `#/docs${slug ? `/${slug}` : ""}${hash}`;
981
- if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("#") || !target) return void 0;
746
+ const route = (slug) => docsHref(slug ? slug.split("/") : [], anchor);
747
+ if (isExternalHref(href) || !target) return void 0;
982
748
  if (target.startsWith("/")) {
983
749
  const slug = target.replace(/^\/+|\/+$/g, "");
984
750
  return this.#pages.has(slug) ? route(slug) : void 0;
@@ -1041,54 +807,6 @@ var DevDocs = class {
1041
807
  this.#listeners.clear();
1042
808
  }
1043
809
  };
1044
- const SHARED = [
1045
- "react",
1046
- "react/jsx-runtime",
1047
- "react/jsx-dev-runtime",
1048
- "react-dom",
1049
- "react-dom/client",
1050
- "@brickkit/cli/dashboard"
1051
- ];
1052
- /** Bundle a module of React components for the dashboard to import. */
1053
- async function bundleComponents(entry) {
1054
- if (typeof Bun !== "undefined") {
1055
- const result = await Bun.build({
1056
- entrypoints: [entry],
1057
- target: "browser",
1058
- format: "esm",
1059
- external: SHARED,
1060
- minify: false,
1061
- throw: false
1062
- });
1063
- if (!result.success) throw new Error(result.logs.map((log) => log.message).join("\n"));
1064
- return (result.outputs.find((item) => item.kind === "entry-point") ?? result.outputs[0]).text();
1065
- }
1066
- const { build } = await import("vite");
1067
- const output = await build({
1068
- configFile: false,
1069
- logLevel: "silent",
1070
- root: dirname(entry),
1071
- oxc: { jsx: { runtime: "automatic" } },
1072
- esbuild: { jsx: "automatic" },
1073
- define: { "process.env.NODE_ENV": "\"development\"" },
1074
- build: {
1075
- write: false,
1076
- minify: false,
1077
- lib: {
1078
- entry,
1079
- formats: ["es"],
1080
- fileName: "components"
1081
- },
1082
- rollupOptions: { external: SHARED }
1083
- }
1084
- });
1085
- const bundles = Array.isArray(output) ? output : [output];
1086
- for (const bundle of bundles) {
1087
- const chunk = ("output" in bundle ? bundle.output : []).find((item) => item.type === "chunk" && item.isEntry);
1088
- if (chunk && "code" in chunk) return chunk.code;
1089
- }
1090
- throw new Error("Brick: the docs components module produced no output.");
1091
- }
1092
810
  /** Flatten what MDX gives for a heading to text. */
1093
811
  function plainText(value) {
1094
812
  if (typeof value === "string") return value;
@@ -1126,7 +844,7 @@ function simplify(tree) {
1126
844
  };
1127
845
  };
1128
846
  return {
1129
- name: text(tree?.name) || "Docs",
847
+ name: text(tree?.name) || DEFAULT_TITLE,
1130
848
  children: (tree?.children ?? []).flatMap((child) => convert(child) ?? [])
1131
849
  };
1132
850
  }
@@ -1159,14 +877,14 @@ async function openDocs(options) {
1159
877
  * are, replaced when that changes, and closed when it stops asking for them.
1160
878
  */
1161
879
  var DocsHost = class {
1162
- #store;
880
+ #publish;
1163
881
  #warn;
1164
882
  #docs;
1165
883
  #stopListening;
1166
884
  #key;
1167
885
  #pending = Promise.resolve();
1168
- constructor(store, warn) {
1169
- this.#store = store;
886
+ constructor(publish, warn) {
887
+ this.#publish = publish;
1170
888
  this.#warn = warn;
1171
889
  }
1172
890
  get current() {
@@ -1186,7 +904,7 @@ var DocsHost = class {
1186
904
  this.#key = key;
1187
905
  this.#release();
1188
906
  if (!documentation) {
1189
- this.#store.setDocs(null);
907
+ this.#publish(null);
1190
908
  return;
1191
909
  }
1192
910
  const opened = await openDocs({
@@ -1197,19 +915,19 @@ var DocsHost = class {
1197
915
  if (opened.status !== "ready") {
1198
916
  const message = opened.status === "missing" ? `The docs need ${opened.packages.join(" and ")}. Install with: bun add -d ${opened.packages.join(" ")}` : opened.message;
1199
917
  this.#warn(`[Brick-TS] Docs are off. ${message}`);
1200
- this.#store.setDocs({
1201
- revision: 1,
1202
- status: opened.status,
1203
- title: "Docs",
1204
- components: false,
1205
- message,
1206
- ...opened.status === "missing" ? { packages: opened.packages } : {}
918
+ this.#publish(opened.status === "missing" ? {
919
+ status: "missing",
920
+ packages: opened.packages,
921
+ message
922
+ } : {
923
+ status: "error",
924
+ message
1207
925
  });
1208
926
  return;
1209
927
  }
1210
928
  this.#docs = opened.docs;
1211
- this.#stopListening = opened.docs.onChange(() => this.#store.setDocs(opened.docs.snapshot()));
1212
- this.#store.setDocs(opened.docs.snapshot());
929
+ this.#stopListening = opened.docs.onChange(() => this.#publish(opened.docs.snapshot()));
930
+ this.#publish(opened.docs.snapshot());
1213
931
  }
1214
932
  #release() {
1215
933
  this.#stopListening?.();
@@ -1222,385 +940,278 @@ var DocsHost = class {
1222
940
  this.#release();
1223
941
  }
1224
942
  };
1225
- // src/dashboard-extension.ts
1226
- /** The colour tokens of `dashboard/theme.css`; a test keeps the two in step. */
1227
- const THEME_TOKENS = [
1228
- "background",
1229
- "foreground",
1230
- "card",
1231
- "card-foreground",
1232
- "popover",
1233
- "popover-foreground",
1234
- "primary",
1235
- "primary-foreground",
1236
- "secondary",
1237
- "secondary-foreground",
1238
- "muted",
1239
- "muted-foreground",
1240
- "accent",
1241
- "accent-foreground",
1242
- "destructive",
1243
- "destructive-foreground",
1244
- "positive",
1245
- "border",
1246
- "input",
1247
- "ring",
1248
- "chart-1",
1249
- "chart-2",
1250
- "chart-3",
1251
- "chart-4",
1252
- "chart-5",
1253
- "span-request",
1254
- "span-action",
1255
- "span-rpc",
1256
- "span-sql",
1257
- "span-event",
1258
- "span-other"
1259
- ];
1260
- const THEME_KEYS = /* @__PURE__ */ new Set([
1261
- "light",
1262
- "dark",
1263
- "radius",
1264
- "fonts"
1265
- ]);
1266
- const FONT_KEYS = /* @__PURE__ */ new Set(["sans", "mono"]);
1267
- const TOKENS = new Set(THEME_TOKENS);
1268
- /** A value that cannot close the rule it sits in. */
1269
- function cssValue(where, value) {
1270
- if (typeof value !== "string" || !value.trim() || /[;{}<>\\]/.test(value)) throw new Error(`Brick: dashboard.theme.${where} must be a CSS value without ; { } < > or \\.`);
1271
- return value.trim();
1272
- }
1273
- /**
1274
- * The stylesheet for a theme, loaded after the dashboard's own; empty when the
1275
- * theme sets nothing. Throws on a token name theme.css does not have.
1276
- */
1277
- function themeCss(theme) {
1278
- if (!theme) return "";
1279
- for (const key of Object.keys(theme)) if (!THEME_KEYS.has(key)) throw new Error(`Brick: dashboard.theme has no "${key}". It takes light, dark, radius and fonts.`);
1280
- const rules = [];
1281
- const root = [];
1282
- if (theme.radius !== void 0) root.push(`--radius: ${cssValue("radius", theme.radius)};`);
1283
- for (const [name, value] of Object.entries(theme.fonts ?? {})) {
1284
- if (!FONT_KEYS.has(name)) throw new Error(`Brick: dashboard.theme.fonts has no "${name}". It takes sans and mono.`);
1285
- root.push(`--font-${name}: ${cssValue(`fonts.${name}`, value)};`);
1286
- }
1287
- if (root.length) rules.push(`:root {\n ${root.join("\n ")}\n}`);
1288
- for (const [mode, selector] of [["light", ":root:not(.dark)"], ["dark", ":root.dark"]]) {
1289
- const tokens = theme[mode];
1290
- if (!tokens) continue;
1291
- const lines = Object.entries(tokens).map(([name, value]) => {
1292
- if (!TOKENS.has(name)) throw new Error(`Brick: dashboard.theme.${mode} has no token "${name}". Tokens: ${THEME_TOKENS.join(", ")}.`);
1293
- return `--${name}: ${cssValue(`${mode}.${name}`, value)};`;
1294
- });
1295
- if (lines.length) rules.push(`${selector} {\n ${lines.join("\n ")}\n}`);
1296
- }
1297
- return rules.length ? `${rules.join("\n")}\n` : "";
1298
- }
1299
- /** The built React app, next to `src/` in the repo and next to `dist/` when published. */
1300
- function assetsDirectory() {
1301
- for (const relative of ["../dashboard-dist/", "../../dashboard-dist/"]) {
1302
- const directory = fileURLToPath(new URL(relative, import.meta.url));
1303
- if (existsSync(join(directory, "app.js"))) return directory;
1304
- }
943
+ function outcomeOf(row) {
944
+ const http = row.httpStatus ?? 0;
945
+ if (row.status === "error" || http >= 500) return "server";
946
+ if (http >= 400) return "client";
947
+ return "ok";
1305
948
  }
1306
- let warnedTailwind = false;
1307
- /**
1308
- * Tailwind for the classes in the extension's bundle, compiled against the
1309
- * dashboard's theme.css so `bg-primary` and the rest match. Only utilities are
1310
- * emitted: the dashboard's stylesheet already has the base styles and tokens.
1311
- * Tailwind is an optional peer, found from the project first.
1312
- */
1313
- async function extensionCss(entry, js, warn) {
1314
- let tailwind;
1315
- let main;
1316
- for (const from of [entry, fileURLToPath(import.meta.url)]) try {
1317
- const require = createRequire(from);
1318
- tailwind = require.resolve("tailwindcss/package.json");
1319
- main = require.resolve("tailwindcss");
1320
- break;
1321
- } catch {}
1322
- const assets = assetsDirectory();
1323
- const themeFile = assets ? join(assets, "theme.css") : fileURLToPath(new URL("../dashboard/theme.css", import.meta.url));
1324
- if (!tailwind || !main) {
1325
- if (!warnedTailwind) warn("[Brick-TS] tailwindcss is not installed, so the dashboard extension's own Tailwind classes are not compiled. The UI kit is styled either way.");
1326
- warnedTailwind = true;
1327
- return "";
1328
- }
1329
- const root = dirname(tailwind);
1330
- const { compile } = await import(pathToFileURL(main).href);
1331
- const compiler = await compile(`@layer theme, base, components, utilities;
1332
- @import "tailwindcss/theme.css" theme(reference inline);
1333
- @import "tailwindcss/utilities.css" layer(utilities);
1334
- @reference "brick/theme.css";
1335
- `, {
1336
- base: root,
1337
- async loadStylesheet(id) {
1338
- const path = id === "brick/theme.css" ? themeFile : join(root, id.replace(/^tailwindcss\//, ""));
1339
- return {
1340
- path,
1341
- base: dirname(path),
1342
- content: await readFile(path, "utf8")
1343
- };
1344
- }
1345
- });
1346
- const candidates = new Set(js.split(/[\s"'`]+/).filter(Boolean));
1347
- const css = compiler.build([...candidates]);
1348
- return /\{/.test(css) ? css : "";
949
+ function endpointOf(trace) {
950
+ return trace.method && trace.route ? `${trace.method} ${trace.route}` : trace.name;
1349
951
  }
1350
- /** Bundle the extension and its styles for the dashboard page. */
1351
- async function buildDashboardExtension(entry, options = {}) {
1352
- const js = await bundleComponents(entry);
952
+ const OUTCOMES = [
953
+ "ok",
954
+ "client",
955
+ "server"
956
+ ];
957
+ /** The history query in a query string, parsed defensively: what `encodeHistoryQuery` wrote. */
958
+ function decodeHistoryQuery(params, now = Date.now()) {
959
+ const integer = (name) => {
960
+ const raw = params.get(name);
961
+ if (raw === null || raw.trim() === "") return void 0;
962
+ const value = Number(raw);
963
+ return Number.isFinite(value) ? Math.trunc(value) : void 0;
964
+ };
965
+ const all = (name) => {
966
+ const values = params.getAll(name).filter((value) => value !== "");
967
+ return values.length > 0 ? values : void 0;
968
+ };
969
+ const to = integer("to") ?? now;
1353
970
  return {
1354
- js,
1355
- css: await extensionCss(entry, js, options.warn ?? ((message) => console.warn(message)))
971
+ to,
972
+ from: integer("from") ?? to - 6048e5,
973
+ endpoints: all("endpoint"),
974
+ methods: all("method"),
975
+ services: all("service"),
976
+ outcomes: all("outcome")?.filter((value) => OUTCOMES.includes(value)),
977
+ minMs: integer("minMs"),
978
+ query: params.get("q") || void 0,
979
+ sort: params.get("sort") === "slowest" ? "slowest" : "recent",
980
+ limit: integer("limit"),
981
+ offset: integer("offset")
1356
982
  };
1357
983
  }
1358
- /**
1359
- * Write the app's extension and its plugins' into `outdir`, where `brick start`
1360
- * can serve them: the app's alone as it is, or with plugins each part apart
1361
- * and `extension.js` loading them, as `brick dev` serves them. Returns false
1362
- * when there is none to write. A plugin's that fails to build throws.
1363
- */
1364
- async function writeDashboardExtension(entry, plugins, outdir) {
1365
- const parts = [...entry ? [{
1366
- name: "app",
1367
- path: entry,
1368
- plugin: false
1369
- }] : [], ...[...pluginDashboards(plugins)].map(([path, name]) => ({
1370
- name,
1371
- path,
1372
- plugin: true
1373
- }))];
1374
- if (!parts.length) return false;
1375
- const built = await Promise.all(parts.map((part) => buildDashboardExtension(part.path).catch((error) => {
1376
- if (!part.plugin) throw error;
1377
- throw new Error(`Brick compiler: the dashboard extension of plugin ${part.name} failed to build: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1378
- })));
1379
- await mkdir(outdir, { recursive: true });
1380
- if (parts.length === 1 && entry) {
1381
- await writeFile(join(outdir, "extension.js"), built[0].js);
1382
- await writeFile(join(outdir, "extension.css"), built[0].css);
1383
- return true;
1384
- }
1385
- for (const [index, part] of built.entries()) await writeFile(join(outdir, `extension-${index}.js`), part.js);
1386
- await writeFile(join(outdir, "extension.js"), extensionLoader(parts.map((part, index) => ({
1387
- name: part.name,
1388
- src: `./extension-${index}.js`,
1389
- plugin: part.plugin
1390
- }))));
1391
- await writeFile(join(outdir, "extension.css"), built.map((part) => part.css).join(""));
1392
- return true;
984
+ /** The fields the search box looks in. */
985
+ const SEARCHED = [
986
+ "endpoint",
987
+ "path",
988
+ "name",
989
+ "action",
990
+ "message"
991
+ ];
992
+ /** The width of each of `count` buckets across [from, to]: whole milliseconds, at least one. */
993
+ const bucketSize = (from, to, count) => Math.max(Math.ceil((to - from) / count), 1);
994
+ /** Linear-interpolated percentile of an ascending list; 0 for an empty list. */
995
+ function percentile(sorted, fraction) {
996
+ if (sorted.length === 0) return 0;
997
+ const position = (sorted.length - 1) * fraction;
998
+ const lower = Math.floor(position);
999
+ const upper = Math.ceil(position);
1000
+ return sorted[lower] + (sorted[upper] - sorted[lower]) * (position - lower);
1393
1001
  }
1394
- /**
1395
- * The extension as the dashboard serves it. From source it is built here, and
1396
- * rebuilt as its folder changes when watching; from a `brick build` folder it
1397
- * is read as it is. A failed build keeps the error to show on the page.
1398
- */
1399
- var DashboardExtensionHost = class {
1400
- #path;
1401
- #warn;
1402
- #listeners = /* @__PURE__ */ new Set();
1403
- #watcher;
1404
- #timer;
1405
- #pending = Promise.resolve();
1406
- revision = 0;
1407
- built;
1408
- error;
1409
- constructor(path, warn) {
1410
- this.#path = resolve(path);
1411
- this.#warn = warn;
1412
- }
1413
- load() {
1414
- this.#pending = this.#pending.then(async () => {
1415
- const before = JSON.stringify([this.built, this.error]);
1416
- try {
1417
- const prebuilt = join(this.#path, "extension.js");
1418
- if (existsSync(prebuilt)) {
1419
- const css = join(this.#path, "extension.css");
1420
- const parts = {};
1421
- for (const name of await readdir(this.#path)) if (/^extension-\d+\.js$/.test(name)) parts[name] = await readFile(join(this.#path, name), "utf8");
1422
- this.built = {
1423
- js: await readFile(prebuilt, "utf8"),
1424
- css: existsSync(css) ? await readFile(css, "utf8") : "",
1425
- parts
1426
- };
1427
- } else {
1428
- if (!existsSync(this.#path)) throw new Error(`Brick: the dashboard extension ${this.#path} does not exist.`);
1429
- this.built = await buildDashboardExtension(this.#path, { warn: this.#warn });
1430
- }
1431
- this.error = void 0;
1432
- } catch (error) {
1433
- this.built = void 0;
1434
- this.error = error instanceof Error ? error.message : String(error);
1435
- this.#warn(`[Brick-TS] Dashboard extension: ${this.error}`);
1436
- }
1437
- if (JSON.stringify([this.built, this.error]) === before) return;
1438
- this.revision++;
1439
- for (const listener of this.#listeners) listener();
1440
- });
1441
- return this.#pending;
1442
- }
1443
- /** Rebuild when a file in the extension's folder changes. */
1444
- watch() {
1445
- try {
1446
- this.#watcher = watch(dirname(this.#path), { recursive: true }, (_event, file) => {
1447
- if (file && /(^|[\\/])(node_modules|\.)/.test(file)) return;
1448
- clearTimeout(this.#timer);
1449
- this.#timer = setTimeout(() => void this.load(), 100);
1450
- });
1451
- } catch {}
1452
- }
1453
- onChange(listener) {
1454
- this.#listeners.add(listener);
1455
- return () => {
1456
- this.#listeners.delete(listener);
1457
- };
1458
- }
1459
- close() {
1460
- clearTimeout(this.#timer);
1461
- this.#watcher?.close();
1462
- this.#listeners.clear();
1463
- }
1464
- };
1465
- /** The plugins' extensions by path, each once, in install order. */
1466
- function pluginDashboards(plugins) {
1467
- const wanted = /* @__PURE__ */ new Map();
1468
- for (const plugin of plugins) if (plugin.dashboard && !wanted.has(resolve(plugin.dashboard))) wanted.set(resolve(plugin.dashboard), plugin.name);
1469
- return wanted;
1002
+ const CSV_COLUMNS = [
1003
+ "time",
1004
+ "method",
1005
+ "route",
1006
+ "path",
1007
+ "status",
1008
+ "outcome",
1009
+ "duration_ms",
1010
+ "service",
1011
+ "action",
1012
+ "message",
1013
+ "trace_id"
1014
+ ];
1015
+ function csvCell(value) {
1016
+ if (value === void 0) return "";
1017
+ const text = String(value);
1018
+ const safe = /^[=+\-@\t\r]/.test(text) ? `'${text}` : text;
1019
+ return /[",\n\r]/.test(safe) ? `"${safe.replace(/"/g, "\"\"")}"` : safe;
1470
1020
  }
1471
- /**
1472
- * The module the page loads when several extensions take part: it imports
1473
- * each one apart, so one that throws leaves the others, and merges them. The
1474
- * app's own comes first and keeps its slots; pages whose id is taken are
1475
- * skipped; roots nest in order; a plugin's pages without a place go under a
1476
- * section named after it.
1477
- */
1478
- function extensionLoader(parts) {
1479
- return `const parts = ${JSON.stringify(parts)};
1480
- const loaded = await Promise.allSettled(parts.map((part) => import(part.src)));
1481
- const merged = { pages: [], sidebar: [], slots: {} };
1482
- const roots = [];
1483
- loaded.forEach((result, index) => {
1484
- const { name, plugin } = parts[index];
1485
- const extension = result.status === "fulfilled" ? result.value.default : undefined;
1486
- if (!extension || typeof extension !== "object") {
1487
- console.error("[Brick dashboard] Extension " + name + " failed to load:", result.status === "rejected" ? result.reason : "it must default-export defineDashboard({ ... })");
1488
- return;
1489
- }
1490
- for (const page of extension.pages ?? []) {
1491
- if (merged.pages.some((item) => item.id === page.id)) {
1492
- console.error("[Brick dashboard] Extension " + name + ": page id " + page.id + " is taken; skipped.");
1493
- continue;
1494
- }
1495
- merged.pages.push(plugin && !page.after && !page.section ? { ...page, section: name } : page);
1496
- }
1497
- merged.sidebar.push(...(extension.sidebar ?? []));
1498
- for (const [slot, value] of Object.entries(extension.slots ?? {})) {
1499
- if (slot === "request.drawer.tabs") merged.slots[slot] = [...(merged.slots[slot] ?? []), ...value];
1500
- else if (!(slot in merged.slots)) merged.slots[slot] = value;
1501
- }
1502
- if (extension.root) roots.push(extension.root);
1503
- });
1504
- if (roots.length) {
1505
- const { createElement } = await import("react");
1506
- merged.root = ({ children }) => roots.reduceRight((inner, Root) => createElement(Root, null, inner), children);
1021
+ /** Requests as CSV with a header row, for the dashboard's export. */
1022
+ function tracesToCsv(traces) {
1023
+ const lines = traces.map((trace) => [
1024
+ new Date(trace.startMs).toISOString(),
1025
+ trace.method,
1026
+ trace.route,
1027
+ trace.path,
1028
+ trace.httpStatus ?? trace.status,
1029
+ outcomeOf(trace),
1030
+ trace.durationMs === void 0 ? void 0 : trace.durationMs.toFixed(3),
1031
+ trace.service,
1032
+ trace.action,
1033
+ trace.message,
1034
+ trace.traceId
1035
+ ].map(csvCell).join(","));
1036
+ return [CSV_COLUMNS.join(","), ...lines].join("\n") + "\n";
1507
1037
  }
1508
- export default merged;
1509
- `;
1038
+ /** A string attribute, or undefined when it is missing or of another type. */
1039
+ function stringAttribute(attributes, key) {
1040
+ const value = attributes?.[key];
1041
+ return typeof value === "string" ? value : void 0;
1042
+ }
1043
+ /** The attributes of the exception a span recorded, if it recorded one. */
1044
+ function findException(events) {
1045
+ return events.find((event) => event.name === SPAN.exceptionEvent)?.attributes;
1046
+ }
1047
+ /** The span that ran the request's action, when it ran one. */
1048
+ function actionSpan(spans) {
1049
+ return spans.find((span) => span.name.startsWith(SPAN.actionPrefix));
1510
1050
  }
1051
+ // src/dev-dashboard-shell.ts
1052
+ const IMPORT_MAP = JSON.stringify({ imports: Object.fromEntries(SHARED_MODULES.map((module) => [module.specifier, assetUrl(module.file)])) });
1511
1053
  /**
1512
- * The app's extension and those of its plugins, served as one. With only the
1513
- * app's, it is served as it is; with plugins, each is built apart (a failed
1514
- * build leaves the others) and `extension.js` loads them all.
1054
+ * The page the dashboard serves at `/`. The React app and its styles load from
1055
+ * `/assets/`; the inline script applies the saved theme before first paint. The
1056
+ * import map hands the project's own modules (its docs components and its
1057
+ * dashboard extension), bundled apart from the dashboard, the dashboard's copy
1058
+ * of React and its UI kit, so there is one of each on the page.
1059
+ *
1060
+ * `extension` describes the project's extension: `revision` changes with every
1061
+ * rebuild (the page reloads when it does), `js` and `css` say what it built.
1062
+ * `theme` is whether `/assets/brick-theme.css` has token values to apply.
1515
1063
  */
1516
- var DashboardExtensions = class {
1517
- #warn;
1518
- #listeners = /* @__PURE__ */ new Set();
1519
- #parts = [];
1520
- #own;
1521
- revision = 0;
1522
- constructor(path, warn) {
1523
- this.#warn = warn;
1524
- this.#own = path !== void 0;
1525
- if (path) this.#add("app", path);
1526
- }
1527
- #add(name, path) {
1528
- const host = new DashboardExtensionHost(path, this.#warn);
1529
- host.onChange(() => this.#changed());
1530
- this.#parts.push({
1531
- name,
1532
- path: resolve(path),
1533
- host
1534
- });
1535
- return host;
1536
- }
1537
- #changed() {
1538
- this.revision++;
1539
- for (const listener of this.#listeners) listener();
1540
- }
1541
- /** Whether any extension takes part. */
1542
- get active() {
1543
- return this.#parts.length > 0;
1544
- }
1545
- get built() {
1546
- const built = this.#parts.filter((part) => part.host.built);
1547
- if (!built.length) return void 0;
1548
- if (this.#own && this.#parts.length === 1) return built[0].host.built;
1549
- return {
1550
- js: extensionLoader(this.#parts.flatMap((part, index) => part.host.built ? [{
1551
- name: part.name,
1552
- src: `./extension-${index}.js?v=${this.revision}`,
1553
- plugin: !(this.#own && index === 0)
1554
- }] : [])),
1555
- css: built.map((part) => part.host.built.css).join("")
1556
- };
1557
- }
1558
- get error() {
1559
- const errors = this.#parts.flatMap((part) => part.host.error ? [this.#own && this.#parts.length === 1 ? part.host.error : `${part.name}: ${part.host.error}`] : []);
1560
- return errors.length ? errors.join("\n") : void 0;
1561
- }
1562
- /** A file under `/assets/` this serves, or undefined. */
1563
- asset(name) {
1564
- if (name === "extension.js") return this.built?.js;
1565
- if (name === "extension.css") return this.built?.css;
1566
- const match = /^extension-(\d+)\.js$/.exec(name);
1567
- if (!match) return void 0;
1568
- if (this.#own && this.#parts.length === 1) return this.#parts[0].host.built?.parts?.[name];
1569
- return this.#parts[Number(match[1])]?.host.built?.js;
1570
- }
1571
- /** Follow the app's plugins: build the extensions they ship, drop the rest. */
1572
- async setPlugins(plugins) {
1573
- if (this.#own && existsSync(join(this.#parts[0].path, "extension.js"))) return;
1574
- const wanted = pluginDashboards(plugins);
1575
- const start = this.#own ? 1 : 0;
1576
- const current = this.#parts.slice(start);
1577
- if (current.length === wanted.size && current.every((part) => wanted.get(part.path) === part.name)) return;
1578
- for (const part of current) part.host.close();
1579
- this.#parts.splice(start);
1580
- const loads = [...wanted].map(([path, name]) => this.#add(name, path).load());
1581
- await Promise.all(loads);
1582
- this.#changed();
1583
- }
1584
- load() {
1585
- return Promise.all(this.#parts.map((part) => part.host.load())).then(() => void 0);
1064
+ function dashboardShell(options = {}) {
1065
+ const { extension, theme, mode } = options;
1066
+ const version = extension ? `?v=${extension.revision}` : "";
1067
+ return `<!doctype html>
1068
+ <html lang="en">
1069
+ <head>
1070
+ <meta charset="utf-8">
1071
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1072
+ <title>${mode === "production" ? "Brick" : "Brick dev"}</title>
1073
+ <link rel="icon" href="data:,">
1074
+ <script>
1075
+ (function () {
1076
+ try {
1077
+ var theme = localStorage.getItem(${JSON.stringify(THEME_STORAGE_KEY)});
1078
+ var dark = theme === "dark" || (theme !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches);
1079
+ if (dark) document.documentElement.classList.add("dark");
1080
+ } catch (error) {}
1081
+ })();
1082
+ <\/script>
1083
+ <link rel="stylesheet" href="${assetUrl(ASSETS.appCss)}">
1084
+ ${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">
1085
+ ${IMPORT_MAP}
1086
+ <\/script>
1087
+ </head>
1088
+ <body>
1089
+ <div id="root"></div>
1090
+ <script type="module" src="${assetUrl(ASSETS.app)}"><\/script>
1091
+ </body>
1092
+ </html>
1093
+ `;
1094
+ }
1095
+ // src/dashboard-access.ts
1096
+ /** How long the app's `authorize` may take before the request is refused. */
1097
+ const AUTHORIZE_TIMEOUT_MS = 5e3;
1098
+ function isLoopbackHost(host) {
1099
+ const name = host.toLowerCase();
1100
+ return name === "localhost" || name === "::1" || name === "[::1]" || /^127(\.\d{1,3}){3}$/.test(name);
1101
+ }
1102
+ const NOT_COPIED = /* @__PURE__ */ new Set([
1103
+ "set-cookie",
1104
+ "content-length",
1105
+ "content-encoding",
1106
+ "transfer-encoding",
1107
+ "connection",
1108
+ "keep-alive"
1109
+ ]);
1110
+ const digest = (value) => createHash("sha256").update(value).digest();
1111
+ /** Whether `candidate` is one of `tokens`, in the same time whichever it is. */
1112
+ function isToken(candidate, tokens) {
1113
+ if (candidate === void 0) return false;
1114
+ const given = digest(candidate);
1115
+ let match = false;
1116
+ for (const token of tokens) if (timingSafeEqual(given, digest(token))) match = true;
1117
+ return match;
1118
+ }
1119
+ /** The secret in an `Authorization` header: a Bearer token, or a Basic password. */
1120
+ function credential(request) {
1121
+ const header = request.headers.authorization;
1122
+ if (!header) return void 0;
1123
+ const space = header.indexOf(" ");
1124
+ if (space < 0) return void 0;
1125
+ const scheme = header.slice(0, space).toLowerCase();
1126
+ const value = header.slice(space + 1).trim();
1127
+ if (scheme === "bearer") return value;
1128
+ if (scheme === "basic") {
1129
+ const decoded = Buffer.from(value, "base64").toString("utf8");
1130
+ const colon = decoded.indexOf(":");
1131
+ return colon < 0 ? void 0 : decoded.slice(colon + 1);
1586
1132
  }
1587
- /** Rebuild the app's own as its folder changes; plugins' are packages. */
1588
- watch() {
1589
- if (this.#own) this.#parts[0].host.watch();
1133
+ }
1134
+ /** The protocol the client used: https when a proxy in front terminated TLS and says so. */
1135
+ function requestProtocol(request) {
1136
+ const forwarded = request.headers["x-forwarded-proto"];
1137
+ return (Array.isArray(forwarded) ? forwarded[0] : forwarded)?.split(",")[0]?.trim() === "https" ? "https" : "http";
1138
+ }
1139
+ /** The request as the app's `authorize` sees it: standard, with no body. */
1140
+ function webRequest(request) {
1141
+ const headers = new Headers();
1142
+ for (const [name, value] of Object.entries(request.headers)) {
1143
+ if (value === void 0) continue;
1144
+ try {
1145
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
1146
+ } catch {}
1590
1147
  }
1591
- onChange(listener) {
1592
- this.#listeners.add(listener);
1593
- return () => {
1594
- this.#listeners.delete(listener);
1595
- };
1148
+ const protocol = requestProtocol(request);
1149
+ const host = request.headers.host ?? "localhost";
1150
+ let url;
1151
+ try {
1152
+ url = new URL(request.url ?? "/", `${protocol}://${host}`).href;
1153
+ } catch {
1154
+ url = `${protocol}://localhost${request.url ?? "/"}`;
1596
1155
  }
1597
- close() {
1598
- for (const part of this.#parts) part.host.close();
1599
- this.#listeners.clear();
1156
+ return new Request(url, {
1157
+ method: request.method ?? "GET",
1158
+ headers
1159
+ });
1160
+ }
1161
+ const refusal = (status, body, headers = {}) => ({
1162
+ allowed: false,
1163
+ status,
1164
+ body,
1165
+ headers: {
1166
+ "content-type": "text/plain; charset=utf-8",
1167
+ ...headers
1600
1168
  }
1601
- };
1169
+ });
1170
+ /**
1171
+ * The check for the dashboard's requests. A request passes with a valid token,
1172
+ * or when the app's `authorize` returns `true`. Anything else is answered:
1173
+ * what `authorize` returned if it returned a `Response`, else 401 (with a
1174
+ * browser sign-in prompt when tokens are in use), and 503 when `authorize`
1175
+ * threw or ran out of time, since a check that cannot answer must not let
1176
+ * anyone in.
1177
+ */
1178
+ function createAccess(auth, onError = () => {}, timeoutMs = AUTHORIZE_TIMEOUT_MS) {
1179
+ const tokens = auth.token === void 0 ? [] : typeof auth.token === "string" ? [auth.token] : [...auth.token];
1180
+ const prompt = tokens.length > 0 ? { "www-authenticate": "Basic realm=\"Brick dashboard\", charset=\"UTF-8\"" } : {};
1181
+ return async (request) => {
1182
+ if (tokens.length > 0 && isToken(credential(request), tokens)) return { allowed: true };
1183
+ if (!auth.authorize) return refusal(401, "Unauthorized", prompt);
1184
+ let decision;
1185
+ let timer;
1186
+ try {
1187
+ decision = await Promise.race([Promise.resolve(auth.authorize(webRequest(request))), new Promise((_, reject) => {
1188
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error("dashboard authorize timed out")), timeoutMs);
1189
+ })]);
1190
+ } catch (error) {
1191
+ onError(error);
1192
+ return refusal(503, "Sign-in is unavailable.");
1193
+ } finally {
1194
+ clearTimeout(timer);
1195
+ }
1196
+ if (decision === true) return { allowed: true };
1197
+ if (decision instanceof Response) {
1198
+ const headers = {};
1199
+ decision.headers.forEach((value, name) => {
1200
+ if (!NOT_COPIED.has(name)) headers[name] = value;
1201
+ });
1202
+ const cookies = decision.headers.getSetCookie();
1203
+ if (cookies.length > 0) headers["set-cookie"] = cookies;
1204
+ return {
1205
+ allowed: false,
1206
+ status: decision.status,
1207
+ headers,
1208
+ body: new Uint8Array(await decision.arrayBuffer())
1209
+ };
1210
+ }
1211
+ return refusal(401, "Unauthorized", prompt);
1212
+ };
1213
+ }
1602
1214
  // src/dev-dashboard.ts
1603
- const DEFAULT_DASHBOARD_PORT = 9400;
1604
1215
  const KEEPALIVE_MS = 15e3;
1605
1216
  const MAX_INGEST_BYTES = 5242880;
1606
1217
  const MAX_PROXY_BYTES = 10485760;
@@ -1627,17 +1238,6 @@ const NOT_RETURNED = /* @__PURE__ */ new Set([
1627
1238
  "content-encoding",
1628
1239
  "set-cookie"
1629
1240
  ]);
1630
- /**
1631
- * What a production dashboard may show: the shell and its assets, the live
1632
- * state and its event stream, and stored history. Nothing that changes the app
1633
- * or reaches into it (restart, the API proxy, ingest) and nothing from the
1634
- * project's source (documentation, OpenAPI documents). With an extension, the
1635
- * `/app` proxy its pages read the app through.
1636
- */
1637
- const isMonitoringRoute = (method, pathname, extension) => extension && isAppRoute(pathname) || method === "GET" && (pathname === "/" || pathname.startsWith("/assets/") || pathname === "/api/state" || pathname === "/api/events" || pathname.startsWith("/api/history"));
1638
- /** `/app/*` reaches the app itself, for the extension's `useAppFetch`. */
1639
- const APP_PATH = "/app";
1640
- const isAppRoute = (pathname) => pathname === APP_PATH || pathname.startsWith(`${APP_PATH}/`);
1641
1241
  const PRODUCTION_HEADERS = {
1642
1242
  "x-content-type-options": "nosniff",
1643
1243
  "x-frame-options": "DENY",
@@ -1660,7 +1260,7 @@ function startDevDashboard(options) {
1660
1260
  const host = options.host ?? "127.0.0.1";
1661
1261
  const loopback = isLoopbackHost(host);
1662
1262
  const production = options.mode === "production";
1663
- if (!loopback && !options.auth) return Promise.reject(/* @__PURE__ */ new Error(`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.`));
1263
+ if (!loopback && !options.auth) return Promise.reject(new ConfigError(`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.`));
1664
1264
  let theme;
1665
1265
  try {
1666
1266
  theme = themeCss(options.dashboard?.theme);
@@ -1684,8 +1284,8 @@ function startDevDashboard(options) {
1684
1284
  return;
1685
1285
  }
1686
1286
  const url = new URL(request.url ?? "/", "http://127.0.0.1");
1687
- const { pathname } = url;
1688
- if (pathname === "/_health" && (request.method === "GET" || request.method === "HEAD")) {
1287
+ const route = matchRoute(request.method, url.pathname);
1288
+ if (route === "health") {
1689
1289
  await health(response);
1690
1290
  return;
1691
1291
  }
@@ -1696,11 +1296,19 @@ function startDevDashboard(options) {
1696
1296
  return;
1697
1297
  }
1698
1298
  }
1699
- if (production && !isMonitoringRoute(request.method, pathname, Boolean(extension?.active))) {
1299
+ if (!route || production && !servedInProduction(route)) {
1700
1300
  send(response, 404, "Not found");
1701
1301
  return;
1702
1302
  }
1703
- handle(request, response, url);
1303
+ if ("csrf" in ROUTES[route] && request.headers["x-brick-dashboard"] !== "1") {
1304
+ send(response, 403, "Forbidden");
1305
+ return;
1306
+ }
1307
+ await handlers[route](request, response, url);
1308
+ }
1309
+ function servedInProduction(route) {
1310
+ const served = ROUTES[route].production;
1311
+ return served === "extension" ? Boolean(extension?.active) : served;
1704
1312
  }
1705
1313
  /** 200 while the app answers its own health check, 503 when it does not. */
1706
1314
  async function health(response) {
@@ -1721,84 +1329,52 @@ function startDevDashboard(options) {
1721
1329
  "cache-control": "no-store"
1722
1330
  });
1723
1331
  }
1724
- function handle(request, response, url) {
1725
- const { pathname } = url;
1726
- if (request.method === "GET" && pathname === "/") {
1727
- send(response, 200, dashboardShell({
1728
- extension: extension?.active ? {
1729
- revision: extension.revision,
1730
- js: Boolean(extension.built),
1731
- css: Boolean(extension.built?.css)
1732
- } : void 0,
1733
- theme: theme !== ""
1734
- }), {
1735
- "content-type": "text/html; charset=utf-8",
1736
- "cache-control": "no-store"
1737
- });
1738
- return;
1739
- }
1740
- if (request.method === "GET" && pathname.startsWith("/assets/")) {
1741
- const name = pathname.slice(8);
1742
- const own = name === "brick-theme.css" ? theme : extension?.asset(name);
1332
+ const handlers = {
1333
+ shell: (_request, response) => send(response, 200, dashboardShell({
1334
+ extension: extension?.active ? {
1335
+ revision: extension.revision,
1336
+ js: Boolean(extension.built),
1337
+ css: Boolean(extension.built?.css)
1338
+ } : void 0,
1339
+ theme: theme !== "",
1340
+ mode: production ? "production" : "dev"
1341
+ }), {
1342
+ "content-type": "text/html; charset=utf-8",
1343
+ "cache-control": "no-store"
1344
+ }),
1345
+ assets(_request, response, url) {
1346
+ const name = url.pathname.slice(ROUTES.assets.path.length + 1);
1347
+ const own = name === ASSETS.theme ? theme : extension?.asset(name);
1743
1348
  if (own !== void 0) send(response, 200, own, {
1744
- "content-type": ASSET_TYPES[extname(name)],
1349
+ "content-type": assetType(name),
1745
1350
  "cache-control": "no-store"
1746
1351
  });
1747
1352
  else serveAsset(response, name);
1748
- return;
1749
- }
1750
- if (isAppRoute(pathname)) {
1751
- app(request, response, url);
1752
- return;
1753
- }
1754
- if (request.method === "GET" && pathname === "/api/state") {
1755
- send(response, 200, JSON.stringify(snapshot()), { "content-type": "application/json" });
1756
- return;
1757
- }
1758
- if (request.method === "GET" && pathname === "/api/events") {
1759
- eventStream(request, response);
1760
- return;
1761
- }
1762
- if (request.method === "GET" && pathname.startsWith("/api/history") && options.history) {
1763
- history(options.history, pathname, url.searchParams, response);
1764
- return;
1765
- }
1766
- if (request.method === "GET" && pathname.startsWith("/api/docs")) {
1767
- docsRoute(response, pathname, url.searchParams);
1768
- return;
1769
- }
1770
- if (request.method === "GET" && pathname === "/api/openapi") {
1771
- send(response, 200, JSON.stringify(options.store.apiDocuments()), {
1772
- "content-type": "application/json",
1773
- "cache-control": "no-store"
1774
- });
1775
- return;
1776
- }
1777
- if (pathname === "/api/proxy") {
1778
- proxy(request, response, url);
1779
- return;
1780
- }
1781
- if (pathname === "/workflows" || pathname.startsWith(`/workflows/`)) {
1782
- response.setHeader("content-security-policy", "frame-ancestors 'self'");
1783
- response.setHeader("x-frame-options", "SAMEORIGIN");
1784
- inspector(request, response, url);
1785
- return;
1786
- }
1787
- if (request.method === "POST" && pathname === "/api/ingest") {
1788
- ingest(request, response);
1789
- return;
1790
- }
1791
- if (request.method === "POST" && pathname === "/api/restart" && options.restart) {
1792
- if (request.headers["x-brick-dashboard"] !== "1") {
1793
- send(response, 403, "Forbidden");
1353
+ },
1354
+ app,
1355
+ state: (_request, response) => json(response, snapshot()),
1356
+ events: eventStream,
1357
+ history(_request, response, url) {
1358
+ if (options.history) history(options.history, url.pathname, url.searchParams, response);
1359
+ else send(response, 404, "Not found");
1360
+ },
1361
+ docs: (_request, response, url) => docsRoute(response, url.pathname, url.searchParams),
1362
+ openapi: (_request, response) => json(response, options.store.apiDocuments()),
1363
+ proxy,
1364
+ workflows(request, response, url) {
1365
+ frameOnlyHere(response);
1366
+ return inspector(request, response, url);
1367
+ },
1368
+ ingest,
1369
+ restart(request, response) {
1370
+ if (!options.restart) {
1371
+ send(response, 404, "Not found");
1794
1372
  return;
1795
1373
  }
1796
1374
  options.restart();
1797
1375
  send(response, 202, "");
1798
- return;
1799
1376
  }
1800
- send(response, 404, "Not found");
1801
- }
1377
+ };
1802
1378
  function snapshot() {
1803
1379
  return {
1804
1380
  ...options.store.snapshot(),
@@ -1816,50 +1392,36 @@ function startDevDashboard(options) {
1816
1392
  * the dashboard, such as a dev server worker: span batches, and a notice when
1817
1393
  * the app loads.
1818
1394
  */
1819
- function ingest(request, response) {
1820
- if (request.headers["x-brick-dashboard"] !== "1") {
1821
- send(response, 403, "Forbidden");
1395
+ async function ingest(request, response) {
1396
+ const body = await readBytes(request, MAX_INGEST_BYTES);
1397
+ if (!body) {
1398
+ tooLarge(response);
1822
1399
  return;
1823
1400
  }
1824
- let body = "";
1825
- let rejected = false;
1826
- request.setEncoding("utf8");
1827
- request.on("data", (chunk) => {
1828
- if (rejected) return;
1829
- body += chunk;
1830
- if (body.length > MAX_INGEST_BYTES) {
1831
- rejected = true;
1832
- send(response, 413, "Payload too large");
1833
- request.destroy();
1834
- }
1835
- });
1836
- request.on("end", () => {
1837
- if (rejected) return;
1838
- try {
1839
- const payload = JSON.parse(body);
1840
- if (Array.isArray(payload.records)) options.store.ingest(payload.records, options.store.latestGeneration);
1841
- if (typeof payload.worker === "string") options.store.startGeneration(payload.worker);
1842
- send(response, 204, "");
1843
- } catch {
1844
- send(response, 400, "Bad request");
1845
- }
1846
- });
1401
+ let payload;
1402
+ try {
1403
+ payload = JSON.parse(Buffer.from(body).toString("utf8"));
1404
+ } catch {
1405
+ payload = null;
1406
+ }
1407
+ if (payload === null || typeof payload !== "object") {
1408
+ send(response, 400, "Bad request");
1409
+ return;
1410
+ }
1411
+ if (Array.isArray(payload.records)) options.store.ingest(payload.records, options.store.latestGeneration);
1412
+ if (typeof payload.worker === "string") options.store.startGeneration(payload.worker);
1413
+ send(response, 204, "");
1847
1414
  }
1848
- /** The Docs tab's data: tree, compiled pages, search, images, components. */
1849
1415
  async function docsRoute(response, pathname, params) {
1850
1416
  const docs = options.docs?.();
1851
1417
  if (!docs) {
1852
1418
  send(response, 404, "The app has no documentation.");
1853
1419
  return;
1854
1420
  }
1855
- const json = (body) => send(response, 200, JSON.stringify(body), {
1856
- "content-type": "application/json",
1857
- "cache-control": "no-store"
1858
- });
1859
1421
  try {
1860
- if (pathname === "/api/docs") return json(docs.info());
1861
- if (pathname === "/api/docs/search") return json(await docs.search(params.get("q") ?? ""));
1862
- if (pathname === "/api/docs/components.js") {
1422
+ if (pathname === DOCS_PATHS.info) return json(response, docs.info());
1423
+ if (pathname === DOCS_PATHS.search) return json(response, await docs.search(params.get("q") ?? ""));
1424
+ if (pathname === DOCS_PATHS.components) {
1863
1425
  const code = await docs.components();
1864
1426
  if (code === void 0) return send(response, 404, "No components.");
1865
1427
  return send(response, 200, code, {
@@ -1867,14 +1429,15 @@ function startDevDashboard(options) {
1867
1429
  "cache-control": "no-store"
1868
1430
  });
1869
1431
  }
1870
- const pagePrefix = "/api/docs/page";
1432
+ const pagePrefix = DOCS_PATHS.page;
1871
1433
  if (pathname === pagePrefix || pathname.startsWith(`${pagePrefix}/`)) {
1872
- const slugs = pathname.slice(14).split("/").filter(Boolean).map(decodeURIComponent);
1434
+ const slugs = pathname.slice(pagePrefix.length).split("/").filter(Boolean).map(decodeURIComponent);
1873
1435
  const page = await docs.page(slugs);
1874
- return page ? json(page) : send(response, 404, "No such page.");
1436
+ return page ? json(response, page) : send(response, 404, "No such page.");
1875
1437
  }
1876
- if (pathname.startsWith("/api/docs/files/")) {
1877
- const file = await docs.file(pathname.slice(16).split("/").map(decodeURIComponent).join("/"));
1438
+ const filePrefix = `${DOCS_PATHS.files}/`;
1439
+ if (pathname.startsWith(filePrefix)) {
1440
+ const file = await docs.file(pathname.slice(filePrefix.length).split("/").map(decodeURIComponent).join("/"));
1878
1441
  if (!file) return send(response, 404, "No such file.");
1879
1442
  return send(response, 200, file.body, {
1880
1443
  "content-type": file.type,
@@ -1888,13 +1451,6 @@ function startDevDashboard(options) {
1888
1451
  }
1889
1452
  }
1890
1453
  /**
1891
- * Send a request on to the app for the APIs view, which cannot call the app
1892
- * directly: it is another origin. Only the dashboard's own page may use this,
1893
- * and only to reach the app being shown. The address to call is `?url=`; a
1894
- * `?cookie=` is the cookie parameters the reader typed into Try it, and the
1895
- * only cookie the app is sent (the dashboard's own are never forwarded).
1896
- */
1897
- /**
1898
1454
  * Pass a request to the workflow inspector, which the app serves on a port of
1899
1455
  * its own, and stream its answer back (it follows a run's output as it
1900
1456
  * grows). Anyone who can open the dashboard may look, but a change must come
@@ -1907,10 +1463,7 @@ function startDevDashboard(options) {
1907
1463
  send(response, 503, "The workflow inspector is not running. The app may be restarting, or it may run no workflows.", { "content-type": "text/plain; charset=utf-8" });
1908
1464
  return;
1909
1465
  }
1910
- const bodyless = request.method === "GET" || request.method === "HEAD";
1911
- const site = request.headers["sec-fetch-site"];
1912
- const origin = request.headers.origin;
1913
- if (!bodyless && (site !== void 0 && site !== "same-origin" || origin !== void 0 && origin !== `http://${request.headers.host}`)) {
1466
+ if (!isBodyless(request) && !fromOwnPage(request)) {
1914
1467
  send(response, 403, "Forbidden");
1915
1468
  return;
1916
1469
  }
@@ -1922,9 +1475,7 @@ function startDevDashboard(options) {
1922
1475
  * API proxy. A credential for the dashboard itself is not passed on.
1923
1476
  */
1924
1477
  async function app(request, response, url) {
1925
- const site = request.headers["sec-fetch-site"];
1926
- const origin = request.headers.origin;
1927
- if (site !== void 0 && site !== "same-origin" || origin !== void 0 && origin !== `http://${request.headers.host}`) {
1478
+ if (!fromOwnPage(request)) {
1928
1479
  send(response, 403, "Forbidden");
1929
1480
  return;
1930
1481
  }
@@ -1933,21 +1484,17 @@ function startDevDashboard(options) {
1933
1484
  send(response, 503, "The app is not running yet.");
1934
1485
  return;
1935
1486
  }
1936
- response.setHeader("content-security-policy", "frame-ancestors 'self'");
1937
- response.setHeader("x-frame-options", "SAMEORIGIN");
1938
- await forward(request, response, `${new URL(appUrl).origin}${url.pathname.slice(4) || "/"}${url.search}`, (headers) => {
1487
+ frameOnlyHere(response);
1488
+ await forward(request, response, `${new URL(appUrl).origin}${url.pathname.slice(ROUTES.app.path.length) || "/"}${url.search}`, (headers) => {
1939
1489
  if (access) headers.delete("authorization");
1940
1490
  }, "Could not reach the app.");
1941
1491
  }
1942
- /** Send the request on to `target` and stream its answer back. */
1943
- async function forward(request, response, target, adjust, unreachable) {
1944
- const bodyless = request.method === "GET" || request.method === "HEAD";
1945
- const headers = new Headers();
1946
- for (const [name, value] of Object.entries(request.headers)) {
1947
- if (value === void 0 || NOT_FORWARDED.has(name)) continue;
1948
- if (name.startsWith("sec-")) continue;
1949
- headers.set(name, Array.isArray(value) ? value.join(", ") : value);
1950
- }
1492
+ /**
1493
+ * Send the request on to `target` and stream its answer back. `body`: the
1494
+ * request's body when the caller already read it; else it is streamed.
1495
+ */
1496
+ async function forward(request, response, target, adjust, unreachable, body) {
1497
+ const headers = forwardedHeaders(request);
1951
1498
  adjust(headers);
1952
1499
  const abort = new AbortController();
1953
1500
  response.on("close", () => abort.abort());
@@ -1957,16 +1504,12 @@ function startDevDashboard(options) {
1957
1504
  headers,
1958
1505
  redirect: "manual",
1959
1506
  signal: abort.signal,
1960
- ...bodyless ? {} : {
1507
+ ...isBodyless(request) ? {} : body ? { body } : {
1961
1508
  body: Readable.toWeb(request),
1962
1509
  duplex: "half"
1963
1510
  }
1964
1511
  });
1965
- const returned = {};
1966
- upstream.headers.forEach((value, name) => {
1967
- if (!NOT_RETURNED.has(name)) returned[name] = value;
1968
- });
1969
- response.writeHead(upstream.status, returned);
1512
+ response.writeHead(upstream.status, returnedHeaders(upstream));
1970
1513
  if (!upstream.body || request.method === "HEAD") {
1971
1514
  response.end();
1972
1515
  return;
@@ -1977,12 +1520,17 @@ function startDevDashboard(options) {
1977
1520
  else send(response, 502, unreachable);
1978
1521
  }
1979
1522
  }
1980
- async function proxy(request, response, url) {
1981
- const site = request.headers["sec-fetch-site"];
1982
- const origin = request.headers.origin;
1983
- if (site !== void 0 && site !== "same-origin" || origin !== void 0 && origin !== `http://${request.headers.host}`) {
1984
- send(response, 403, "Forbidden");
1985
- return;
1523
+ /**
1524
+ * Send a request on to the app for the APIs view, which cannot call the app
1525
+ * directly: it is another origin. Only the dashboard's own page may use this,
1526
+ * and only to reach the app being shown. The address to call is `?url=`; a
1527
+ * `?cookie=` is the cookie parameters the reader typed into Try it, and the
1528
+ * only cookie the app is sent (the dashboard's own are never forwarded).
1529
+ */
1530
+ async function proxy(request, response, url) {
1531
+ if (!fromOwnPage(request)) {
1532
+ send(response, 403, "Forbidden");
1533
+ return;
1986
1534
  }
1987
1535
  let target;
1988
1536
  try {
@@ -1995,154 +1543,525 @@ function startDevDashboard(options) {
1995
1543
  }
1996
1544
  const body = await readBytes(request, MAX_PROXY_BYTES);
1997
1545
  if (!body) {
1998
- send(response, 413, "Payload too large");
1546
+ tooLarge(response);
1999
1547
  return;
2000
1548
  }
2001
- const headers = new Headers();
2002
- for (const [name, value] of Object.entries(request.headers)) {
2003
- if (value === void 0 || NOT_FORWARDED.has(name)) continue;
2004
- if (name.startsWith("sec-")) continue;
2005
- headers.set(name, Array.isArray(value) ? value.join(", ") : value);
1549
+ const cookie = url.searchParams.get("cookie");
1550
+ await forward(request, response, target.href, (headers) => {
1551
+ if (cookie) headers.set("cookie", cookie);
1552
+ }, "Could not reach the app.", body);
1553
+ }
1554
+ function eventStream(request, response) {
1555
+ response.writeHead(200, {
1556
+ "content-type": "text/event-stream",
1557
+ "cache-control": "no-cache",
1558
+ connection: "keep-alive",
1559
+ "x-accel-buffering": "no"
1560
+ });
1561
+ const write = (chunk) => {
1562
+ if (response.writableEnded || response.destroyed) return;
1563
+ response.write(chunk);
1564
+ };
1565
+ const emit = (name, data) => write(`event: ${name}\ndata: ${JSON.stringify(data)}\n\n`);
1566
+ emit("snapshot", snapshot());
1567
+ const unsubscribe = options.store.subscribe((event) => emit(event.type, event));
1568
+ const unwatch = extension?.onChange(() => emit("extension", snapshot().extension));
1569
+ const keepalive = setInterval(() => write(": keepalive\n\n"), KEEPALIVE_MS);
1570
+ request.on("close", () => {
1571
+ clearInterval(keepalive);
1572
+ unsubscribe();
1573
+ unwatch?.();
1574
+ });
1575
+ }
1576
+ return (extension ? Promise.all([extension.load(), options.plugins && extension.setPlugins(options.plugins)]) : Promise.resolve()).then(() => listen());
1577
+ function listen() {
1578
+ return new Promise((resolve, reject) => {
1579
+ server.once("error", (error) => {
1580
+ extension?.close();
1581
+ reject(new Error(`Brick: dashboard port ${options.port} is unavailable.${options.portHint ? ` ${options.portHint}` : ""}`, { cause: error }));
1582
+ });
1583
+ server.listen(options.port, host, () => {
1584
+ const address = server.address();
1585
+ const port = typeof address === "object" && address !== null ? address.port : options.port;
1586
+ allowedHosts = /* @__PURE__ */ new Set([
1587
+ `127.0.0.1:${port}`,
1588
+ `localhost:${port}`,
1589
+ `[::1]:${port}`
1590
+ ]);
1591
+ if (!production) extension?.watch();
1592
+ resolve({
1593
+ port,
1594
+ setPluginExtensions: (plugins) => extension?.setPlugins(plugins) ?? Promise.resolve(),
1595
+ stop() {
1596
+ extension?.close();
1597
+ server.close();
1598
+ server.closeAllConnections();
1599
+ }
1600
+ });
1601
+ });
1602
+ });
1603
+ }
1604
+ }
1605
+ /** The whole request body, or undefined when it is larger than `limit`. */
1606
+ function readBytes(request, limit) {
1607
+ return new Promise((resolve) => {
1608
+ const chunks = [];
1609
+ let size = 0;
1610
+ request.on("data", (chunk) => {
1611
+ size += chunk.length;
1612
+ if (size > limit) {
1613
+ request.removeAllListeners("data");
1614
+ request.resume();
1615
+ resolve(void 0);
1616
+ return;
1617
+ }
1618
+ chunks.push(chunk);
1619
+ });
1620
+ request.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
1621
+ request.on("error", () => resolve(void 0));
1622
+ });
1623
+ }
1624
+ function history(store, pathname, params, response) {
1625
+ const queries = {
1626
+ summary: (query) => store.summary(query),
1627
+ traces: (query) => store.traces(query),
1628
+ facets: (query) => store.facets(query),
1629
+ volume: (query) => store.volume(query)
1630
+ };
1631
+ try {
1632
+ const endpoint = pathname.slice(ROUTES.history.path.length + 1);
1633
+ if (endpoint === "") return json(response, store.info());
1634
+ if (endpoint === "export") return send(response, 200, store.exportCsv(decodeHistoryQuery(params)), {
1635
+ "content-type": "text/csv; charset=utf-8",
1636
+ "content-disposition": "attachment; filename=\"brick-requests.csv\"",
1637
+ "cache-control": "no-store"
1638
+ });
1639
+ if (Object.hasOwn(queries, endpoint)) return json(response, queries[endpoint](decodeHistoryQuery(params)));
1640
+ if (endpoint.startsWith("traces/")) {
1641
+ const trace = store.trace(decodeURIComponent(endpoint.slice(7)));
1642
+ if (trace) return json(response, trace);
1643
+ }
1644
+ send(response, 404, "Not found");
1645
+ } catch (error) {
1646
+ if (error instanceof URIError) return send(response, 400, error.message);
1647
+ console.error("[Brick-TS] A dashboard history query failed:", error);
1648
+ send(response, 500, "History query failed");
1649
+ }
1650
+ }
1651
+ const ASSET_TYPES = {
1652
+ ".js": "text/javascript; charset=utf-8",
1653
+ ".css": "text/css; charset=utf-8",
1654
+ ".woff2": "font/woff2"
1655
+ };
1656
+ const assetType = (name) => ASSET_TYPES[extname(name)] ?? "application/octet-stream";
1657
+ function serveAsset(response, name) {
1658
+ if (!/^[\w.-]+$/.test(name) || name.startsWith(".")) {
1659
+ send(response, 404, "Not found");
1660
+ return;
1661
+ }
1662
+ const directory = assetsDirectory();
1663
+ if (!directory) {
1664
+ send(response, 503, "Dashboard assets are missing. Build them with: bun run --filter @brickkit/cli build");
1665
+ return;
1666
+ }
1667
+ readFile(join(directory, name)).then((body) => send(response, 200, body, {
1668
+ "content-type": assetType(name),
1669
+ "cache-control": "no-store"
1670
+ }), () => send(response, 404, "Not found"));
1671
+ }
1672
+ function tooLarge(response) {
1673
+ send(response, 413, "Payload too large", {
1674
+ "content-type": "text/plain; charset=utf-8",
1675
+ connection: "close"
1676
+ });
1677
+ }
1678
+ function send(response, status, body, headers = { "content-type": "text/plain; charset=utf-8" }) {
1679
+ response.writeHead(status, headers);
1680
+ response.end(body);
1681
+ }
1682
+ function json(response, body) {
1683
+ send(response, 200, JSON.stringify(body), {
1684
+ "content-type": "application/json",
1685
+ "cache-control": "no-store"
1686
+ });
1687
+ }
1688
+ const isBodyless = (request) => request.method === "GET" || request.method === "HEAD";
1689
+ /**
1690
+ * Whether a request comes from the dashboard's own page, as far as the browser
1691
+ * says: the same site, and the same origin as the address it was sent to.
1692
+ * Behind a proxy that terminates TLS that address is https.
1693
+ */
1694
+ function fromOwnPage(request) {
1695
+ const site = request.headers["sec-fetch-site"];
1696
+ const origin = request.headers.origin;
1697
+ return (site === void 0 || site === "same-origin") && (origin === void 0 || origin === `${requestProtocol(request)}://${request.headers.host}`);
1698
+ }
1699
+ function frameOnlyHere(response) {
1700
+ response.setHeader("content-security-policy", "frame-ancestors 'self'");
1701
+ response.setHeader("x-frame-options", "SAMEORIGIN");
1702
+ }
1703
+ /** The request's headers to send on, without those of this hop or this page. */
1704
+ function forwardedHeaders(request) {
1705
+ const headers = new Headers();
1706
+ for (const [name, value] of Object.entries(request.headers)) {
1707
+ if (value === void 0 || NOT_FORWARDED.has(name)) continue;
1708
+ if (name.startsWith("sec-")) continue;
1709
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
1710
+ }
1711
+ return headers;
1712
+ }
1713
+ function returnedHeaders(upstream) {
1714
+ const returned = {};
1715
+ upstream.headers.forEach((value, name) => {
1716
+ if (!NOT_RETURNED.has(name)) returned[name] = value;
1717
+ });
1718
+ return returned;
1719
+ }
1720
+ // src/dev-history.ts
1721
+ const DAY_MS = 864e5;
1722
+ const MAX_TRACES = 1e5;
1723
+ const FLUSH_MS = 250;
1724
+ const PRUNE_MS = 18e5;
1725
+ const VOLUME_BUCKETS = 48;
1726
+ const MAX_LIMIT = 500;
1727
+ const MAX_EXPORT_ROWS = 1e5;
1728
+ /**
1729
+ * SQLite from whichever runtime is running: `bun:sqlite` under Bun, and
1730
+ * `node:sqlite` under Node, which is what runs Vite's dev server. Both are
1731
+ * imported by a variable name so bundlers leave them alone.
1732
+ */
1733
+ async function openDatabase(file) {
1734
+ if (typeof Bun !== "undefined") {
1735
+ const { Database } = await import("bun:sqlite");
1736
+ return new Database(file, { create: true });
1737
+ }
1738
+ const specifier = "node:sqlite";
1739
+ const emit = process.emitWarning;
1740
+ process.emitWarning = ((warning, ...rest) => {
1741
+ if (typeof warning === "string" && warning.includes("SQLite")) return;
1742
+ return emit.call(process, warning, ...rest);
1743
+ });
1744
+ try {
1745
+ const { DatabaseSync } = await import(specifier);
1746
+ return new DatabaseSync(file);
1747
+ } finally {
1748
+ process.emitWarning = emit;
1749
+ }
1750
+ }
1751
+ /**
1752
+ * Open the request history, or return undefined when it is turned off or this
1753
+ * runtime has no SQLite. Never throws: the dashboard works without history.
1754
+ */
1755
+ async function openHistory(options) {
1756
+ if (!(options.days > 0)) return void 0;
1757
+ try {
1758
+ const folder = join(options.directory, ".brick");
1759
+ mkdirSync(folder, { recursive: true });
1760
+ const ignore = join(folder, ".gitignore");
1761
+ if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
1762
+ return new DevHistory(await openDatabase(join(folder, "telemetry.sqlite")), options.days, options.warn);
1763
+ } catch (error) {
1764
+ const reason = error instanceof Error ? error.message : String(error);
1765
+ options.warn?.(`[Brick-TS] Request history is unavailable (${reason}). It needs Bun, or Node 22.5 or later. Continuing without it.`);
1766
+ return;
1767
+ }
1768
+ }
1769
+ const text = (value) => value === null || value === void 0 ? void 0 : String(value);
1770
+ const number = (value) => value === null || value === void 0 ? void 0 : Number(value);
1771
+ /** Each row's outcome, by the rules of `outcomeOf`. */
1772
+ const OUTCOME_CASE = `CASE
1773
+ WHEN status = 'error' OR http_status >= 500 THEN 'server'
1774
+ WHEN http_status >= 400 THEN 'client'
1775
+ ELSE 'ok' END`;
1776
+ const FACET_COLUMNS = {
1777
+ outcome: OUTCOME_CASE,
1778
+ method: "method",
1779
+ service: "service",
1780
+ endpoint: "endpoint"
1781
+ };
1782
+ /** The WHERE clause for a query, leaving out one filter when counting its facet. */
1783
+ function filterSql(query, skip) {
1784
+ const clauses = ["start_ms >= ?", "start_ms <= ?"];
1785
+ const params = [query.from, query.to];
1786
+ const anyOf = (column, values) => {
1787
+ if (!values || values.length === 0) return;
1788
+ clauses.push(`${column} IN (${values.map(() => "?").join(", ")})`);
1789
+ params.push(...values);
1790
+ };
1791
+ if (skip !== "endpoint") anyOf("endpoint", query.endpoints);
1792
+ if (skip !== "method") anyOf("method", query.methods);
1793
+ if (skip !== "service") anyOf("service", query.services);
1794
+ if (skip !== "outcome") anyOf(OUTCOME_CASE, query.outcomes);
1795
+ if (query.minMs !== void 0 && query.minMs > 0) {
1796
+ clauses.push("duration_ms >= ?");
1797
+ params.push(query.minMs);
1798
+ }
1799
+ const needle = query.query?.trim();
1800
+ if (needle) {
1801
+ const pattern = `%${needle.replace(/[\\%_]/g, "\\$&")}%`;
1802
+ clauses.push(`(${SEARCHED.map((column) => `${column} LIKE ? ESCAPE '\\'`).join(" OR ")})`);
1803
+ params.push(...SEARCHED.map(() => pattern));
1804
+ }
1805
+ return {
1806
+ sql: clauses.join(" AND "),
1807
+ params
1808
+ };
1809
+ }
1810
+ const orderSql = (sort) => sort === "slowest" ? "duration_ms DESC, start_ms DESC" : "start_ms DESC";
1811
+ const LIST_COLUMNS = `trace_id, name, endpoint, method, route, path, http_status, generation,
1812
+ start_ms, end_ms, duration_ms, status, truncated, service, action, message`;
1813
+ function toHistoryTrace(row) {
1814
+ return {
1815
+ traceId: String(row.trace_id),
1816
+ name: String(row.name),
1817
+ endpoint: String(row.endpoint),
1818
+ method: text(row.method),
1819
+ route: text(row.route),
1820
+ path: text(row.path),
1821
+ httpStatus: number(row.http_status),
1822
+ generation: Number(row.generation),
1823
+ startMs: Number(row.start_ms),
1824
+ endMs: number(row.end_ms),
1825
+ durationMs: number(row.duration_ms),
1826
+ status: String(row.status),
1827
+ truncated: Number(row.truncated) === 1,
1828
+ service: text(row.service),
1829
+ action: text(row.action),
1830
+ message: text(row.message)
1831
+ };
1832
+ }
1833
+ /**
1834
+ * Requests kept on disk between runs, for looking back over weeks
1835
+ * instead of the last few minutes. Writes are batched; reads see them.
1836
+ */
1837
+ var DevHistory = class {
1838
+ days;
1839
+ #database;
1840
+ #pendingTraces = /* @__PURE__ */ new Map();
1841
+ #flushTimer;
1842
+ #pruneTimer;
1843
+ #closed = false;
1844
+ #warn;
1845
+ /** Failure kinds already reported: one warning each, not one per batch. */
1846
+ #warned = /* @__PURE__ */ new Set();
1847
+ constructor(database, days, warn) {
1848
+ this.#database = database;
1849
+ this.days = days;
1850
+ this.#warn = warn;
1851
+ database.exec(`
1852
+ PRAGMA journal_mode = WAL;
1853
+ PRAGMA synchronous = NORMAL;
1854
+ PRAGMA busy_timeout = 2000;
1855
+ CREATE TABLE IF NOT EXISTS traces (
1856
+ trace_id TEXT PRIMARY KEY,
1857
+ name TEXT NOT NULL,
1858
+ endpoint TEXT NOT NULL,
1859
+ method TEXT,
1860
+ route TEXT,
1861
+ path TEXT,
1862
+ http_status INTEGER,
1863
+ generation INTEGER NOT NULL,
1864
+ start_ms INTEGER NOT NULL,
1865
+ end_ms INTEGER,
1866
+ duration_ms REAL,
1867
+ status TEXT NOT NULL,
1868
+ truncated INTEGER NOT NULL,
1869
+ spans TEXT NOT NULL,
1870
+ service TEXT,
1871
+ action TEXT,
1872
+ message TEXT
1873
+ );
1874
+ CREATE INDEX IF NOT EXISTS traces_start ON traces (start_ms);
1875
+ CREATE INDEX IF NOT EXISTS traces_endpoint ON traces (endpoint, start_ms);
1876
+ -- Earlier versions kept failures here; nothing reads them now.
1877
+ DROP TABLE IF EXISTS failures;
1878
+ `);
1879
+ this.#addMissingColumns();
1880
+ this.prune();
1881
+ this.#pruneTimer = setInterval(() => this.prune(), PRUNE_MS);
1882
+ this.#pruneTimer.unref?.();
1883
+ }
1884
+ /** A folder from an earlier version has the table without the newer columns. */
1885
+ #addMissingColumns() {
1886
+ const present = new Set(this.#database.prepare("PRAGMA table_info(traces)").all().map((column) => String(column.name)));
1887
+ for (const column of [
1888
+ "service",
1889
+ "action",
1890
+ "message"
1891
+ ]) if (!present.has(column)) this.#database.exec(`ALTER TABLE traces ADD COLUMN ${column} TEXT`);
1892
+ }
1893
+ /** Queue a finished request. A later save of the same request replaces it. */
1894
+ saveTrace(trace) {
1895
+ if (this.#closed) return;
1896
+ this.#pendingTraces.set(trace.traceId, trace);
1897
+ this.#scheduleFlush();
1898
+ }
1899
+ #scheduleFlush() {
1900
+ if (this.#flushTimer) return;
1901
+ this.#flushTimer = setTimeout(() => this.flush(), FLUSH_MS);
1902
+ this.#flushTimer.unref?.();
1903
+ }
1904
+ flush() {
1905
+ if (this.#flushTimer) {
1906
+ clearTimeout(this.#flushTimer);
1907
+ this.#flushTimer = void 0;
1908
+ }
1909
+ if (this.#closed || this.#pendingTraces.size === 0) return;
1910
+ const traces = [...this.#pendingTraces.values()];
1911
+ this.#pendingTraces.clear();
1912
+ try {
1913
+ this.#database.exec("BEGIN");
1914
+ const saveTrace = this.#database.prepare(`INSERT OR REPLACE INTO traces (trace_id, name, endpoint, method, route, path,
1915
+ http_status, generation, start_ms, end_ms, duration_ms, status, truncated, spans,
1916
+ service, action, message)
1917
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
1918
+ for (const trace of traces) saveTrace.run(trace.traceId, trace.name, endpointOf(trace), trace.method ?? null, trace.route ?? null, trace.path ?? null, trace.httpStatus ?? null, trace.generation, trace.startMs, trace.endMs ?? null, trace.durationMs ?? null, trace.status, trace.truncated ? 1 : 0, JSON.stringify(trace.spans), trace.service ?? null, trace.action ?? null, trace.message ?? null);
1919
+ this.#database.exec("COMMIT");
1920
+ } catch (error) {
1921
+ this.#warnOnce("save requests to", error);
1922
+ try {
1923
+ this.#database.exec("ROLLBACK");
1924
+ } catch {}
2006
1925
  }
2007
- const cookie = url.searchParams.get("cookie");
2008
- if (cookie) headers.set("cookie", cookie);
2009
- const bodyless = request.method === "GET" || request.method === "HEAD";
1926
+ }
1927
+ /** Drop what is past retention, then the oldest beyond the size cap. */
1928
+ prune(now = Date.now()) {
1929
+ if (this.#closed) return;
2010
1930
  try {
2011
- const upstream = await fetch(target, {
2012
- method: request.method,
2013
- headers,
2014
- body: bodyless ? void 0 : body,
2015
- redirect: "manual"
2016
- });
2017
- const returned = {};
2018
- upstream.headers.forEach((value, name) => {
2019
- if (!NOT_RETURNED.has(name)) returned[name] = value;
2020
- });
2021
- send(response, upstream.status, new Uint8Array(await upstream.arrayBuffer()), returned);
2022
- } catch {
2023
- send(response, 502, "Could not reach the app.");
1931
+ const cutoff = now - this.days * DAY_MS;
1932
+ this.#database.prepare("DELETE FROM traces WHERE start_ms < ?").run(cutoff);
1933
+ const count = Number(this.#database.prepare("SELECT COUNT(*) AS n FROM traces").get()?.n ?? 0);
1934
+ if (count > MAX_TRACES) this.#database.prepare("DELETE FROM traces WHERE trace_id IN (SELECT trace_id FROM traces ORDER BY start_ms ASC LIMIT ?)").run(count - MAX_TRACES);
1935
+ } catch (error) {
1936
+ this.#warnOnce("prune", error);
2024
1937
  }
2025
1938
  }
2026
- function eventStream(request, response) {
2027
- response.writeHead(200, {
2028
- "content-type": "text/event-stream",
2029
- "cache-control": "no-cache",
2030
- connection: "keep-alive",
2031
- "x-accel-buffering": "no"
2032
- });
2033
- const write = (chunk) => {
2034
- if (response.writableEnded || response.destroyed) return;
2035
- response.write(chunk);
1939
+ #warnOnce(action, error) {
1940
+ if (this.#warned.has(action)) return;
1941
+ this.#warned.add(action);
1942
+ const reason = error instanceof Error ? error.message : String(error);
1943
+ this.#warn?.(`[Brick-TS] Could not ${action} the request history (${reason}).`);
1944
+ }
1945
+ info() {
1946
+ this.flush();
1947
+ const row = this.#database.prepare("SELECT COUNT(*) AS n, MIN(start_ms) AS oldest FROM traces").get();
1948
+ return {
1949
+ days: this.days,
1950
+ count: Number(row?.n ?? 0),
1951
+ oldestMs: number(row?.oldest)
2036
1952
  };
2037
- write(`event: snapshot\ndata: ${JSON.stringify(snapshot())}\n\n`);
2038
- const unsubscribe = options.store.subscribe((event) => write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`));
2039
- const unwatch = extension?.onChange(() => write(`event: extension\ndata: ${JSON.stringify(snapshot().extension)}\n\n`));
2040
- const keepalive = setInterval(() => write(": keepalive\n\n"), KEEPALIVE_MS);
2041
- request.on("close", () => {
2042
- clearInterval(keepalive);
2043
- unsubscribe();
2044
- unwatch?.();
2045
- });
2046
1953
  }
2047
- return (extension ? Promise.all([extension.load(), options.plugins && extension.setPlugins(options.plugins)]) : Promise.resolve()).then(() => listen());
2048
- function listen() {
2049
- return new Promise((resolve, reject) => {
2050
- server.once("error", (error) => {
2051
- extension?.close();
2052
- reject(new Error(production ? `Brick: dashboard port ${options.port} is unavailable. Set dashboard.port in brick() to another.` : `Brick: dashboard port ${options.port} is unavailable. Use --dashboard-port <number> or --no-dashboard.`, { cause: error }));
2053
- });
2054
- server.listen(options.port, host, () => {
2055
- const address = server.address();
2056
- const port = typeof address === "object" && address !== null ? address.port : options.port;
2057
- allowedHosts = /* @__PURE__ */ new Set([
2058
- `127.0.0.1:${port}`,
2059
- `localhost:${port}`,
2060
- `[::1]:${port}`
2061
- ]);
2062
- if (!production) extension?.watch();
2063
- resolve({
2064
- port,
2065
- setPluginExtensions: (plugins) => extension?.setPlugins(plugins) ?? Promise.resolve(),
2066
- stop() {
2067
- extension?.close();
2068
- server.close();
2069
- server.closeAllConnections();
2070
- }
2071
- });
2072
- });
2073
- });
1954
+ /** Matching requests, without spans, and how many match in total. */
1955
+ traces(query) {
1956
+ this.flush();
1957
+ const { sql, params } = filterSql(query);
1958
+ const total = Number(this.#database.prepare(`SELECT COUNT(*) AS n FROM traces WHERE ${sql}`).get(...params)?.n ?? 0);
1959
+ const limit = Math.min(Math.max(query.limit ?? 100, 1), MAX_LIMIT);
1960
+ const offset = Math.max(query.offset ?? 0, 0);
1961
+ return {
1962
+ total,
1963
+ traces: this.#database.prepare(`SELECT ${LIST_COLUMNS}
1964
+ FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} LIMIT ? OFFSET ?`).all(...params, limit, offset).map(toHistoryTrace)
1965
+ };
2074
1966
  }
2075
- }
2076
- /** The whole request body, or undefined when it is larger than `limit`. */
2077
- function readBytes(request, limit) {
2078
- return new Promise((resolve) => {
2079
- const chunks = [];
2080
- let size = 0;
2081
- request.on("data", (chunk) => {
2082
- size += chunk.length;
2083
- if (size > limit) {
2084
- resolve(void 0);
2085
- request.destroy();
2086
- return;
2087
- }
2088
- chunks.push(chunk);
2089
- });
2090
- request.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
2091
- request.on("error", () => resolve(void 0));
2092
- });
2093
- }
2094
- function history(store, pathname, params, response) {
2095
- const json = (body) => send(response, 200, JSON.stringify(body), { "content-type": "application/json" });
2096
- try {
2097
- if (pathname === "/api/history") return json(store.info());
2098
- if (pathname === "/api/history/summary") return json(store.summary(parseHistoryQuery(params)));
2099
- if (pathname === "/api/history/traces") return json(store.traces(parseHistoryQuery(params)));
2100
- if (pathname === "/api/history/facets") return json(store.facets(parseHistoryQuery(params)));
2101
- if (pathname === "/api/history/volume") return json(store.volume(parseHistoryQuery(params)));
2102
- if (pathname === "/api/history/export") return send(response, 200, store.exportCsv(parseHistoryQuery(params)), {
2103
- "content-type": "text/csv; charset=utf-8",
2104
- "content-disposition": "attachment; filename=\"brick-requests.csv\"",
2105
- "cache-control": "no-store"
2106
- });
2107
- if (pathname.startsWith("/api/history/traces/")) {
2108
- const trace = store.trace(decodeURIComponent(pathname.slice(20)));
2109
- if (trace) return json(trace);
1967
+ /** Counts for each filter over the range, ignoring that filter's own choice. */
1968
+ facets(query) {
1969
+ this.flush();
1970
+ const count = (facet) => {
1971
+ const { sql, params } = filterSql(query, facet);
1972
+ const column = FACET_COLUMNS[facet];
1973
+ return this.#database.prepare(`SELECT ${column} AS value, COUNT(*) AS n FROM traces
1974
+ WHERE ${sql} AND ${column} IS NOT NULL
1975
+ GROUP BY value ORDER BY n DESC, value ASC LIMIT ?`).all(...params, 30).map((row) => ({
1976
+ value: String(row.value),
1977
+ count: Number(row.n)
1978
+ }));
1979
+ };
1980
+ return {
1981
+ outcome: count("outcome"),
1982
+ method: count("method"),
1983
+ service: count("service"),
1984
+ endpoint: count("endpoint")
1985
+ };
1986
+ }
1987
+ /** Matching requests per time bucket across the range, by outcome. */
1988
+ volume(query, buckets = VOLUME_BUCKETS) {
1989
+ this.flush();
1990
+ const { sql, params } = filterSql(query);
1991
+ const bucketMs = bucketSize(query.from, query.to, buckets);
1992
+ const result = Array.from({ length: buckets }, (_, index) => ({
1993
+ start: query.from + index * bucketMs,
1994
+ ok: 0,
1995
+ client: 0,
1996
+ server: 0
1997
+ }));
1998
+ const rows = this.#database.prepare(`SELECT CAST((start_ms - ?) / ? AS INTEGER) AS bucket, ${OUTCOME_CASE} AS outcome,
1999
+ COUNT(*) AS n
2000
+ FROM traces WHERE ${sql} GROUP BY bucket, outcome`).all(query.from, bucketMs, ...params);
2001
+ for (const row of rows) {
2002
+ const bucket = result[Math.min(Math.max(Number(row.bucket), 0), buckets - 1)];
2003
+ const outcome = String(row.outcome);
2004
+ if (bucket) bucket[outcome] += Number(row.n);
2110
2005
  }
2111
- send(response, 404, "Not found");
2112
- } catch {
2113
- send(response, 500, "History query failed");
2006
+ return result;
2114
2007
  }
2115
- }
2116
- const ASSET_TYPES = {
2117
- ".js": "text/javascript; charset=utf-8",
2118
- ".css": "text/css; charset=utf-8",
2119
- ".woff2": "font/woff2"
2120
- };
2121
- function serveAsset(response, name) {
2122
- if (!/^[\w.-]+$/.test(name) || name.startsWith(".")) {
2123
- send(response, 404, "Not found");
2124
- return;
2008
+ /** Every matching request, newest first, as CSV for a spreadsheet. */
2009
+ exportCsv(query) {
2010
+ this.flush();
2011
+ const { sql, params } = filterSql(query);
2012
+ return tracesToCsv(this.#database.prepare(`SELECT ${LIST_COLUMNS}
2013
+ FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} LIMIT ?`).all(...params, MAX_EXPORT_ROWS).map(toHistoryTrace));
2125
2014
  }
2126
- const directory = assetsDirectory();
2127
- if (!directory) {
2128
- send(response, 503, "Dashboard assets are missing. Build them with: bun run --filter @brickkit/cli build");
2129
- return;
2015
+ trace(traceId) {
2016
+ this.flush();
2017
+ const row = this.#database.prepare(`SELECT ${LIST_COLUMNS}, spans FROM traces WHERE trace_id = ?`).get(traceId);
2018
+ if (!row) return void 0;
2019
+ const { endpoint: _endpoint, ...trace } = toHistoryTrace(row);
2020
+ return {
2021
+ ...trace,
2022
+ spans: JSON.parse(String(row.spans))
2023
+ };
2130
2024
  }
2131
- readFile(join(directory, name)).then((body) => send(response, 200, body, {
2132
- "content-type": ASSET_TYPES[extname(name)] ?? "application/octet-stream",
2133
- "cache-control": "no-store"
2134
- }), () => send(response, 404, "Not found"));
2135
- }
2136
- function send(response, status, body, headers = { "content-type": "text/plain; charset=utf-8" }) {
2137
- response.writeHead(status, headers);
2138
- response.end(body);
2139
- }
2025
+ /** How many requests match, how many failed, and how long they took. */
2026
+ summary(query) {
2027
+ this.flush();
2028
+ const { sql, params } = filterSql(query);
2029
+ let total = 0;
2030
+ let clientErrors = 0;
2031
+ let serverErrors = 0;
2032
+ const counts = this.#database.prepare(`SELECT ${OUTCOME_CASE} AS outcome, COUNT(*) AS n
2033
+ FROM traces WHERE ${sql} GROUP BY outcome`).all(...params);
2034
+ for (const row of counts) {
2035
+ const n = Number(row.n);
2036
+ total += n;
2037
+ if (row.outcome === "client") clientErrors = n;
2038
+ if (row.outcome === "server") serverErrors = n;
2039
+ }
2040
+ const durations = this.#database.prepare(`SELECT duration_ms FROM traces
2041
+ WHERE ${sql} AND duration_ms IS NOT NULL ORDER BY duration_ms`).all(...params).map((row) => Number(row.duration_ms));
2042
+ return {
2043
+ total,
2044
+ clientErrors,
2045
+ serverErrors,
2046
+ medianMs: percentile(durations, .5),
2047
+ p95Ms: percentile(durations, .95)
2048
+ };
2049
+ }
2050
+ /** Write what is queued and release the database. */
2051
+ close() {
2052
+ if (this.#closed) return;
2053
+ this.flush();
2054
+ this.#closed = true;
2055
+ clearInterval(this.#pruneTimer);
2056
+ try {
2057
+ this.#database.close();
2058
+ } catch {}
2059
+ }
2060
+ };
2140
2061
  // src/dev-telemetry-store.ts
2141
2062
  const LIMITS = {
2142
- traces: 200,
2143
- spansPerTrace: 500,
2144
- failures: 200,
2145
- reloads: 100
2063
+ ...LIVE_LIMITS,
2064
+ spansPerTrace: 500
2146
2065
  };
2147
2066
  const WORKER_FAILURE_CODES = {
2148
2067
  startup: "STARTUP_FAILED",
@@ -2166,7 +2085,7 @@ var DevTelemetryStore = class {
2166
2085
  #apiDocuments = [];
2167
2086
  #sequence = 0;
2168
2087
  #generation = 0;
2169
- /** Finished requests and failures are also kept in `history`, when given. */
2088
+ /** Finished requests are also kept in `history`, when given. */
2170
2089
  constructor(options = {}) {
2171
2090
  this.#history = options.history;
2172
2091
  }
@@ -2340,9 +2259,9 @@ var DevTelemetryStore = class {
2340
2259
  if (!(record.parentSpanId !== void 0 && entry.spans.has(record.parentSpanId)) && entry.rootSpanId === void 0) {
2341
2260
  entry.rootSpanId = record.spanId;
2342
2261
  entry.name = record.name;
2343
- entry.method = stringAttribute(record.attributes, "http.request.method");
2344
- entry.route = stringAttribute(record.attributes, "http.route");
2345
- entry.path = stringAttribute(record.attributes, "url.path");
2262
+ entry.method = stringAttribute(record.attributes, ATTR.httpMethod);
2263
+ entry.route = stringAttribute(record.attributes, ATTR.httpRoute);
2264
+ entry.path = stringAttribute(record.attributes, ATTR.urlPath);
2346
2265
  }
2347
2266
  if (entry.spans.size >= LIMITS.spansPerTrace) {
2348
2267
  entry.truncated = true;
@@ -2380,38 +2299,40 @@ var DevTelemetryStore = class {
2380
2299
  ...record.attributes
2381
2300
  };
2382
2301
  span.events = record.events;
2383
- const code = stringAttribute(record.attributes, "brick.error.code");
2302
+ const code = stringAttribute(record.attributes, ATTR.errorCode);
2384
2303
  if (code !== void 0) {
2385
2304
  const exception = findException(record.events);
2386
2305
  this.#pushFailure({
2387
2306
  phase: "request",
2388
2307
  code,
2389
- message: stringAttribute(exception, "exception.message") ?? stringAttribute(record.attributes, "brick.error.message") ?? code,
2390
- status: numberAttribute(record.attributes, "brick.error.status"),
2391
- stack: stringAttribute(exception, "exception.stacktrace"),
2308
+ message: stringAttribute(exception, ATTR.exceptionMessage) ?? stringAttribute(record.attributes, ATTR.errorMessage) ?? code,
2309
+ status: numberAttribute(record.attributes, ATTR.errorStatus),
2310
+ stack: stringAttribute(exception, ATTR.exceptionStack),
2392
2311
  traceId: entry.traceId,
2393
2312
  route: entry.route,
2394
- service: stringAttribute(record.attributes, "brick.service"),
2395
- action: stringAttribute(record.attributes, "brick.action"),
2313
+ service: stringAttribute(record.attributes, ATTR.service),
2314
+ action: stringAttribute(record.attributes, ATTR.action),
2396
2315
  generation: entry.generation
2397
2316
  });
2398
2317
  entry.failureRecorded = true;
2399
2318
  }
2400
2319
  if (record.spanId !== entry.rootSpanId) return;
2401
2320
  entry.endMs = record.endMs;
2402
- entry.httpStatus = numberAttribute(record.attributes, "http.response.status_code");
2321
+ entry.httpStatus = numberAttribute(record.attributes, ATTR.httpStatus);
2403
2322
  const status = entry.httpStatus ?? 0;
2404
- const serverFault = status >= 500;
2405
- const failed = record.status === "error" || serverFault;
2406
- entry.status = failed ? "error" : "ok";
2407
- if ((failed || status >= 400) && !entry.failureRecorded) {
2323
+ const outcome = outcomeOf({
2324
+ status: record.status === "error" ? "error" : "ok",
2325
+ httpStatus: entry.httpStatus
2326
+ });
2327
+ entry.status = outcome === "server" ? "error" : "ok";
2328
+ if (outcome !== "ok" && !entry.failureRecorded) {
2408
2329
  const exception = findException(record.events);
2409
2330
  this.#pushFailure({
2410
2331
  phase: "request",
2411
2332
  code: status >= 400 ? `HTTP_${status}` : "UNHANDLED_ERROR",
2412
- message: stringAttribute(exception, "exception.message") ?? record.statusMessage ?? describeResponse(entry, status),
2333
+ message: stringAttribute(exception, ATTR.exceptionMessage) ?? record.statusMessage ?? describeResponse(entry, status),
2413
2334
  status: entry.httpStatus,
2414
- stack: stringAttribute(exception, "exception.stacktrace"),
2335
+ stack: stringAttribute(exception, ATTR.exceptionStack),
2415
2336
  traceId: entry.traceId,
2416
2337
  route: entry.route,
2417
2338
  generation: entry.generation
@@ -2437,14 +2358,15 @@ var DevTelemetryStore = class {
2437
2358
  #emit(event) {
2438
2359
  for (const listener of this.#listeners) try {
2439
2360
  listener(event);
2440
- } catch {
2361
+ } catch (error) {
2441
2362
  this.#listeners.delete(listener);
2363
+ console.warn("[Brick-TS] A dashboard client stopped receiving updates:", error);
2442
2364
  }
2443
2365
  }
2444
2366
  };
2445
2367
  function summarize(entry) {
2446
2368
  const spans = [...entry.spans.values()].sort((a, b) => a.startMs - b.startMs);
2447
- const actionSpan = spans.find((span) => span.name.startsWith("action "));
2369
+ const action = actionSpan(spans);
2448
2370
  return {
2449
2371
  traceId: entry.traceId,
2450
2372
  name: entry.name || spans[0]?.name || entry.traceId,
@@ -2458,8 +2380,8 @@ function summarize(entry) {
2458
2380
  durationMs: entry.endMs === void 0 ? void 0 : entry.endMs - entry.startMs,
2459
2381
  status: entry.status,
2460
2382
  truncated: entry.truncated,
2461
- service: stringAttribute(actionSpan?.attributes, "brick.service"),
2462
- action: stringAttribute(actionSpan?.attributes, "brick.action"),
2383
+ service: stringAttribute(action?.attributes, ATTR.service),
2384
+ action: stringAttribute(action?.attributes, ATTR.action),
2463
2385
  message: entry.message,
2464
2386
  spans
2465
2387
  };
@@ -2469,17 +2391,54 @@ function describeResponse(entry, status) {
2469
2391
  const request = entry.method ? `${entry.method} ${target}` : target;
2470
2392
  return status ? `${request} returned ${status}` : request;
2471
2393
  }
2472
- function findException(events) {
2473
- return events.find((event) => event.name === "exception")?.attributes;
2474
- }
2475
- function stringAttribute(attributes, key) {
2476
- const value = attributes?.[key];
2477
- return typeof value === "string" ? value : void 0;
2478
- }
2479
2394
  function numberAttribute(attributes, key) {
2480
2395
  const value = attributes?.[key];
2481
2396
  return typeof value === "number" ? value : void 0;
2482
2397
  }
2483
- export { writeDashboardExtension as a, openHistory as c, themeCss as i, startInspector as l, DEFAULT_DASHBOARD_PORT as n, DocsHost as o, startDevDashboard as r, isLoopbackHost as s, DevTelemetryStore as t };
2398
+ // src/dashboard-host.ts
2399
+ /**
2400
+ * Open the dashboard with its history, store and docs, for `brick dev`, the
2401
+ * Vite plugin and the production dashboard alike. When it cannot start, what
2402
+ * it opened is closed, `warn` says why, and the host runs on without it. A
2403
+ * configuration mistake (a bad theme, a public host without auth) throws.
2404
+ */
2405
+ async function openDashboard(options) {
2406
+ const { port = DEFAULT_DASHBOARD_PORT, directory, historyDays = 90, warn, docs: withDocs, ...rest } = options;
2407
+ const history = await openHistory({
2408
+ directory,
2409
+ days: historyDays,
2410
+ warn
2411
+ });
2412
+ const store = new DevTelemetryStore({ history });
2413
+ const docs = withDocs ? new DocsHost((docs) => store.setDocs(docs), warn) : void 0;
2414
+ let server;
2415
+ try {
2416
+ server = await startDevDashboard({
2417
+ ...rest,
2418
+ port,
2419
+ store,
2420
+ history,
2421
+ docs: docs && (() => docs.current)
2422
+ });
2423
+ } catch (error) {
2424
+ docs?.close();
2425
+ history?.close();
2426
+ if (error instanceof ConfigError) throw error;
2427
+ warn(`[Brick-TS] ${error instanceof Error ? error.message : String(error)} Continuing without the dashboard.`);
2428
+ return;
2429
+ }
2430
+ return {
2431
+ port: server.port,
2432
+ store,
2433
+ docs,
2434
+ setPluginExtensions: (plugins) => server.setPluginExtensions(plugins),
2435
+ stop() {
2436
+ server.stop();
2437
+ docs?.close();
2438
+ history?.close();
2439
+ }
2440
+ };
2441
+ }
2442
+ export { themeCss as n, writeDashboardExtension as r, openDashboard as t };
2484
2443
 
2485
- //# sourceMappingURL=dev-telemetry-store.js.map
2444
+ //# sourceMappingURL=dashboard-host.js.map