@brickkit/cli 0.11.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.
- package/dashboard-dist/CollapsiblePanel-CbUysOp5.js +2 -0
- package/dashboard-dist/CompositeRoot-D4sRkYq3.js +1 -0
- package/dashboard-dist/Geist-Variable.woff2 +0 -0
- package/dashboard-dist/GeistMono-Variable.woff2 +0 -0
- package/dashboard-dist/PopoverPopup-CiI2avT_.js +1 -0
- package/dashboard-dist/api-reference-mT9VNcPb.js +265 -0
- package/dashboard-dist/app.css +2 -2
- package/dashboard-dist/app.js +12 -13
- package/dashboard-dist/ccount-CcG1m-Yh.js +1 -0
- package/dashboard-dist/client-CwATkLJa.js +1 -0
- package/dashboard-dist/core-BEUWp6B5.js +1 -0
- package/dashboard-dist/docs-BRrtyxDB.js +4 -0
- package/dashboard-dist/docs.css +1 -1
- package/dashboard-dist/kit.js +1 -1
- package/dashboard-dist/popover-Bj9x-88h.js +1 -0
- package/dist/bin.d.ts +0 -2
- package/dist/bin.js +309 -211
- package/dist/bin.js.map +1 -1
- package/dist/build.js +463 -0
- package/dist/build.js.map +1 -0
- package/dist/client-contract-file.js +356 -1
- package/dist/client-contract-file.js.map +1 -0
- package/dist/compiler.d.ts +12 -3
- package/dist/compiler.js +1 -1
- package/dist/compiler2.js +13 -7
- package/dist/compiler2.js.map +1 -1
- package/dist/config.d.ts +3 -0
- package/dist/config.js +1 -252
- package/dist/config2.d.ts +122 -0
- package/dist/config2.js +207 -0
- package/dist/config2.js.map +1 -0
- package/dist/dashboard-extension.d.ts +3 -2
- package/dist/{dev-telemetry-store.js → dashboard-host.js} +1381 -1432
- package/dist/dashboard-host.js.map +1 -0
- package/dist/dashboard-protocol.js +189 -0
- package/dist/dashboard-protocol.js.map +1 -0
- package/dist/dashboard.d.ts +8 -135
- package/dist/definitions.js +33 -0
- package/dist/definitions.js.map +1 -0
- package/dist/dev-application.js +34 -0
- package/dist/dev-application.js.map +1 -0
- package/dist/dev-protocol.js +21 -0
- package/dist/dev-protocol.js.map +1 -0
- package/dist/dev-reporter.d.ts +0 -2
- package/dist/dev-reporter.js +3 -3
- package/dist/dev-reporter.js.map +1 -1
- package/dist/dev-telemetry.js +8 -24
- package/dist/dev-telemetry.js.map +1 -1
- package/dist/dev-worker.js +80 -21
- package/dist/dev-worker.js.map +1 -1
- package/dist/index.d.ts +18 -87
- package/dist/index.js +12 -6
- package/dist/index.js.map +1 -0
- package/dist/lint/oxlint.d.ts +0 -2
- package/dist/lint/oxlint.js +6 -5
- package/dist/lint/oxlint.js.map +1 -1
- package/dist/own-module.js +7 -0
- package/dist/own-module.js.map +1 -0
- package/dist/plugin.d.ts +6 -11
- package/dist/plugin.js +6 -42
- package/dist/plugin.js.map +1 -1
- package/dist/production-dashboard.d.ts +2 -0
- package/dist/production-dashboard.js +51 -0
- package/dist/production-dashboard.js.map +1 -0
- package/dist/production-dashboard2.d.ts +34 -0
- package/dist/{presets.js → project.js} +107 -113
- package/dist/project.js.map +1 -0
- package/dist/serve.d.ts +24 -0
- package/dist/serve.js +1 -0
- package/dist/serve2.js +49 -0
- package/dist/serve2.js.map +1 -0
- package/dist/vite.d.ts +0 -2
- package/dist/vite.js +28 -51
- package/dist/vite.js.map +1 -1
- package/dist/workflows.d.ts +2 -4
- package/dist/workflows2.js +60 -39
- package/dist/workflows2.js.map +1 -1
- package/inspector-dist/client/assets/api.rpc-BvRk9kiK.js +0 -0
- package/inspector-dist/client/assets/api.stream._streamId-BvRk9kiK.js +0 -0
- package/inspector-dist/client/assets/app-CeSwVsRm.css +2 -0
- package/inspector-dist/client/assets/dist-BK8w6xOr.js +3930 -0
- package/inspector-dist/client/assets/dist-CG2aVufI.js +197 -0
- package/inspector-dist/client/assets/entry.client-D9jbgmTR.js +9391 -0
- package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-CfRnuITN.js +34 -0
- package/inspector-dist/client/assets/home-hwPlkNhv.js +4034 -0
- package/inspector-dist/client/assets/jsx-runtime-CPEah4WQ.js +7084 -0
- package/inspector-dist/client/assets/manifest-0e76e9ac.js +1 -0
- package/inspector-dist/client/assets/mermaid-3ZIDBTTL-ZDR2PNY_.js +1 -0
- package/inspector-dist/client/assets/root-ChBNTZd2.css +2 -0
- package/inspector-dist/client/assets/root-SLeEf-sT.js +320 -0
- package/inspector-dist/client/assets/run-detail-DYbVkIFH.js +1871 -0
- package/inspector-dist/client/assets/tabs-CaJisoyb.js +73751 -0
- package/inspector-dist/client/assets/tabs-L5XKzOpP.css +1 -0
- package/inspector-dist/client/assets/zstd-browser-decoder-D94wmfAU.js +41 -0
- package/inspector-dist/server/assets/app-DGlfWVUI.js +99330 -0
- package/inspector-dist/server/assets/chunk-RLXIAIE6-F0SJZlei.js +42975 -0
- package/inspector-dist/server/assets/dist-BCbwm6jl.js +10325 -0
- package/inspector-dist/server/assets/dist-CG2aVufI.js +197 -0
- package/inspector-dist/server/assets/dist-Ce0I2PUv.js +1137 -0
- package/inspector-dist/server/assets/dist-DY0UlahA.js +1642 -0
- package/inspector-dist/server/assets/encryption-DdQgC8Rk.js +886 -0
- package/inspector-dist/server/assets/event-metadata-n7E4zEmT.js +145 -0
- package/inspector-dist/server/assets/functions-CNVQtbgg.js +1170 -0
- package/inspector-dist/server/assets/global-singleton-D8sIN5du.js +80 -0
- package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-CWRzMxYD.js +34 -0
- package/inspector-dist/server/assets/mermaid-3ZIDBTTL-D0v0ngVr.js +1 -0
- package/inspector-dist/server/assets/parse-Begau9cA.js +469 -0
- package/inspector-dist/server/assets/rolldown-runtime-C1I3wEg2.js +43 -0
- package/inspector-dist/server/assets/serialization-format-BbuGfHog.js +476 -0
- package/inspector-dist/server/assets/token-BgMmJNP5.js +60 -0
- package/inspector-dist/server/assets/token-BrUX0bxz.js +55 -0
- package/inspector-dist/server/assets/token-util-DZN32qmT.js +455 -0
- package/inspector-dist/server/assets/wrapper-CIC3w0oC.js +3624 -0
- package/inspector-dist/server/assets/ws-transport-CxTYB11n.js +29476 -0
- package/inspector-dist/server/assets/zstd-browser-decoder-D7bCXbGg.js +38 -0
- package/inspector-dist/server/index.js +1 -58
- package/package.json +39 -28
- package/vite-client.d.ts +1 -1
- package/dashboard-dist/CollapsiblePanel-BX79_W-b.js +0 -2
- package/dashboard-dist/CompositeRoot-xzybXjnx.js +0 -1
- package/dashboard-dist/PopoverPopup-CvlmC7EL.js +0 -1
- package/dashboard-dist/api-reference-BcAYVYwJ.js +0 -260
- package/dashboard-dist/core-BGO9JZ1r.js +0 -1
- package/dashboard-dist/docs-DHikPD2v.js +0 -4
- package/dashboard-dist/popover-DG498XHH.js +0 -1
- package/dist/app-entry.js +0 -1
- package/dist/app-entry2.js +0 -19
- package/dist/app-entry2.js.map +0 -1
- package/dist/bin.d.ts.map +0 -1
- package/dist/client-contract-file2.js +0 -34
- package/dist/client-contract-file2.js.map +0 -1
- package/dist/client-contract.js +0 -1
- package/dist/client-contract2.js +0 -294
- package/dist/client-contract2.js.map +0 -1
- package/dist/config.js.map +0 -1
- package/dist/dashboard-extension.d.ts.map +0 -1
- package/dist/dev-reporter.d.ts.map +0 -1
- package/dist/dev-telemetry-store.js.map +0 -1
- package/dist/emit.d.ts +0 -7
- package/dist/emit.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/lint/oxlint.d.ts.map +0 -1
- package/dist/plugin.d.ts.map +0 -1
- package/dist/presets.js.map +0 -1
- package/dist/runner.js +0 -523
- package/dist/runner.js.map +0 -1
- package/dist/vite.d.ts.map +0 -1
- package/dist/workflows.d.ts.map +0 -1
- package/inspector-dist/client/assets/api.rpc-l0sNRNKZ.js +0 -1
- package/inspector-dist/client/assets/api.stream._streamId-l0sNRNKZ.js +0 -1
- package/inspector-dist/client/assets/app-CvoGgWcV.css +0 -1
- package/inspector-dist/client/assets/entry.client-BJ6G3n5t.js +0 -11697
- package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-C-3wZnxf.js +0 -19
- package/inspector-dist/client/assets/home-CSKAS4P2.js +0 -4979
- package/inspector-dist/client/assets/index-DECCyMR0.js +0 -4482
- package/inspector-dist/client/assets/index-Dot7CgrA.js +0 -9837
- package/inspector-dist/client/assets/index-HqNj_XIX.js +0 -200
- package/inspector-dist/client/assets/manifest-139c9319.js +0 -1
- package/inspector-dist/client/assets/mermaid-3ZIDBTTL-DC0K8uTy.js +0 -58626
- package/inspector-dist/client/assets/mermaid-3ZIDBTTL-F88p7PFX.css +0 -1
- package/inspector-dist/client/assets/root-BMHd_XHz.css +0 -1
- package/inspector-dist/client/assets/root-cbi6iYwg.js +0 -305
- package/inspector-dist/client/assets/run-detail-CWoGxu_0.css +0 -1
- package/inspector-dist/client/assets/run-detail-Cc7tSGNq.js +0 -6237
- package/inspector-dist/client/assets/world-config-context-BAD1QCrR.js +0 -26
- package/inspector-dist/client/assets/zstd-browser-decoder-BQoRpP7L.js +0 -28
- package/inspector-dist/server/assets/app-DUP5RybL.js +0 -174880
- package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-D2g4hL2-.js +0 -71
- package/inspector-dist/server/assets/index-BfLBLRRi.js +0 -204
- package/inspector-dist/server/assets/index-BzrGWk7J.js +0 -1164
- package/inspector-dist/server/assets/index-D71yP6AL.js +0 -191
- package/inspector-dist/server/assets/index-wGSWRns3.js +0 -1296
- package/inspector-dist/server/assets/mermaid-3ZIDBTTL-DsvuKoEV.js +0 -58
- package/inspector-dist/server/assets/token-ClUZZwXl.js +0 -95
- package/inspector-dist/server/assets/token-util-DSxMZ6nI.js +0 -33
- package/inspector-dist/server/assets/wrapper-B3vstpCO.js +0 -67
- package/inspector-dist/server/assets/zstd-browser-decoder-Dn82m2BU.js +0 -77
|
@@ -1,720 +1,485 @@
|
|
|
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
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
|
-
*
|
|
27
|
-
*
|
|
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
|
|
32
|
-
if (
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
const
|
|
36
|
-
if (
|
|
37
|
-
|
|
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
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
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
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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
|
-
|
|
68
|
-
|
|
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
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if (
|
|
89
|
-
const
|
|
90
|
-
const
|
|
91
|
-
|
|
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;
|
|
92
214
|
}
|
|
93
|
-
/**
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
});
|
|
112
|
-
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
|
+
};
|
|
113
233
|
}
|
|
114
|
-
//#endregion
|
|
115
|
-
//#region src/dev-history.ts
|
|
116
|
-
const DAY_MS = 864e5;
|
|
117
|
-
const MAX_TRACES = 1e5;
|
|
118
|
-
const FLUSH_MS = 250;
|
|
119
|
-
const PRUNE_MS = 18e5;
|
|
120
|
-
const VOLUME_BUCKETS = 48;
|
|
121
|
-
const DEFAULT_LIMIT = 100;
|
|
122
|
-
const MAX_LIMIT = 500;
|
|
123
|
-
const MAX_FACET_VALUES = 30;
|
|
124
|
-
const MAX_EXPORT_ROWS = 1e5;
|
|
125
|
-
const OUTCOMES = /* @__PURE__ */ new Set([
|
|
126
|
-
"ok",
|
|
127
|
-
"client",
|
|
128
|
-
"server"
|
|
129
|
-
]);
|
|
130
234
|
/**
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
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.
|
|
134
240
|
*/
|
|
135
|
-
|
|
136
|
-
if (
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
}
|
|
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
|
+
};
|
|
152
258
|
}
|
|
153
259
|
/**
|
|
154
|
-
*
|
|
155
|
-
*
|
|
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.
|
|
156
263
|
*/
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
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;
|
|
169
277
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
const FACET_COLUMNS = {
|
|
191
|
-
outcome: OUTCOME_CASE,
|
|
192
|
-
method: "method",
|
|
193
|
-
service: "service",
|
|
194
|
-
endpoint: "endpoint"
|
|
195
|
-
};
|
|
196
|
-
/** The WHERE clause for a query, leaving out one filter when counting its facet. */
|
|
197
|
-
function filterSql(query, skip) {
|
|
198
|
-
const clauses = ["start_ms >= ?", "start_ms <= ?"];
|
|
199
|
-
const params = [query.from, query.to];
|
|
200
|
-
const anyOf = (column, values) => {
|
|
201
|
-
if (!values || values.length === 0) return;
|
|
202
|
-
clauses.push(`${column} IN (${values.map(() => "?").join(", ")})`);
|
|
203
|
-
params.push(...values);
|
|
204
|
-
};
|
|
205
|
-
if (skip !== "endpoint") anyOf("endpoint", query.endpoints);
|
|
206
|
-
if (skip !== "method") anyOf("method", query.methods);
|
|
207
|
-
if (skip !== "service") anyOf("service", query.services);
|
|
208
|
-
if (skip !== "outcome" && query.outcomes && query.outcomes.length > 0) clauses.push(`(${query.outcomes.map((outcome) => OUTCOME_SQL[outcome]).join(" OR ")})`);
|
|
209
|
-
if (query.minMs !== void 0 && query.minMs > 0) {
|
|
210
|
-
clauses.push("duration_ms >= ?");
|
|
211
|
-
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;
|
|
212
298
|
}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
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 {}
|
|
218
307
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
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;
|
|
223
325
|
}
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
endpoint: String(row.endpoint),
|
|
231
|
-
method: text(row.method),
|
|
232
|
-
route: text(row.route),
|
|
233
|
-
path: text(row.path),
|
|
234
|
-
httpStatus: number(row.http_status),
|
|
235
|
-
generation: Number(row.generation),
|
|
236
|
-
startMs: Number(row.start_ms),
|
|
237
|
-
endMs: number(row.end_ms),
|
|
238
|
-
durationMs: number(row.duration_ms),
|
|
239
|
-
status: String(row.status),
|
|
240
|
-
truncated: Number(row.truncated) === 1,
|
|
241
|
-
service: text(row.service),
|
|
242
|
-
action: text(row.action),
|
|
243
|
-
message: text(row.message)
|
|
244
|
-
};
|
|
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`;
|
|
245
332
|
}
|
|
246
333
|
/**
|
|
247
|
-
*
|
|
248
|
-
*
|
|
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.
|
|
249
337
|
*/
|
|
250
|
-
var
|
|
251
|
-
|
|
252
|
-
#
|
|
253
|
-
|
|
254
|
-
#
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
this.#
|
|
259
|
-
this.days = days;
|
|
260
|
-
database.exec(`
|
|
261
|
-
PRAGMA journal_mode = WAL;
|
|
262
|
-
PRAGMA synchronous = NORMAL;
|
|
263
|
-
PRAGMA busy_timeout = 2000;
|
|
264
|
-
CREATE TABLE IF NOT EXISTS traces (
|
|
265
|
-
trace_id TEXT PRIMARY KEY,
|
|
266
|
-
name TEXT NOT NULL,
|
|
267
|
-
endpoint TEXT NOT NULL,
|
|
268
|
-
method TEXT,
|
|
269
|
-
route TEXT,
|
|
270
|
-
path TEXT,
|
|
271
|
-
http_status INTEGER,
|
|
272
|
-
generation INTEGER NOT NULL,
|
|
273
|
-
start_ms INTEGER NOT NULL,
|
|
274
|
-
end_ms INTEGER,
|
|
275
|
-
duration_ms REAL,
|
|
276
|
-
status TEXT NOT NULL,
|
|
277
|
-
truncated INTEGER NOT NULL,
|
|
278
|
-
spans TEXT NOT NULL,
|
|
279
|
-
service TEXT,
|
|
280
|
-
action TEXT,
|
|
281
|
-
message TEXT
|
|
282
|
-
);
|
|
283
|
-
CREATE INDEX IF NOT EXISTS traces_start ON traces (start_ms);
|
|
284
|
-
CREATE INDEX IF NOT EXISTS traces_endpoint ON traces (endpoint, start_ms);
|
|
285
|
-
-- Earlier versions kept failures here; nothing reads them now.
|
|
286
|
-
DROP TABLE IF EXISTS failures;
|
|
287
|
-
`);
|
|
288
|
-
this.#addMissingColumns();
|
|
289
|
-
this.prune();
|
|
290
|
-
this.#pruneTimer = setInterval(() => this.prune(), PRUNE_MS);
|
|
291
|
-
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);
|
|
292
347
|
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
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;
|
|
301
358
|
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
if (this.#closed) return;
|
|
305
|
-
this.#pendingTraces.set(trace.traceId, trace);
|
|
306
|
-
this.#scheduleFlush();
|
|
359
|
+
get #own() {
|
|
360
|
+
return this.#parts.find((part) => !part.plugin);
|
|
307
361
|
}
|
|
308
|
-
#
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
this.#flushTimer.unref?.();
|
|
362
|
+
#changed() {
|
|
363
|
+
this.revision++;
|
|
364
|
+
for (const listener of this.#listeners) listener();
|
|
312
365
|
}
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
if (this.#flushTimer) {
|
|
316
|
-
clearTimeout(this.#flushTimer);
|
|
317
|
-
this.#flushTimer = void 0;
|
|
318
|
-
}
|
|
319
|
-
if (this.#closed || this.#pendingTraces.size === 0) return;
|
|
320
|
-
const traces = [...this.#pendingTraces.values()];
|
|
321
|
-
this.#pendingTraces.clear();
|
|
322
|
-
try {
|
|
323
|
-
this.#database.exec("BEGIN");
|
|
324
|
-
const saveTrace = this.#database.prepare(`INSERT OR REPLACE INTO traces (trace_id, name, endpoint, method, route, path,
|
|
325
|
-
http_status, generation, start_ms, end_ms, duration_ms, status, truncated, spans,
|
|
326
|
-
service, action, message)
|
|
327
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
328
|
-
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);
|
|
329
|
-
this.#database.exec("COMMIT");
|
|
330
|
-
} catch {
|
|
331
|
-
try {
|
|
332
|
-
this.#database.exec("ROLLBACK");
|
|
333
|
-
} catch {}
|
|
334
|
-
}
|
|
366
|
+
get active() {
|
|
367
|
+
return this.#parts.length > 0;
|
|
335
368
|
}
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
const count = Number(this.#database.prepare("SELECT COUNT(*) AS n FROM traces").get()?.n ?? 0);
|
|
343
|
-
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);
|
|
344
|
-
} 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}`);
|
|
345
375
|
}
|
|
346
|
-
|
|
347
|
-
this.
|
|
348
|
-
|
|
349
|
-
return {
|
|
350
|
-
days: this.days,
|
|
351
|
-
count: Number(row?.n ?? 0),
|
|
352
|
-
oldestMs: number(row?.oldest)
|
|
353
|
-
};
|
|
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;
|
|
354
379
|
}
|
|
355
|
-
/**
|
|
356
|
-
|
|
357
|
-
this.
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
const limit = Math.min(Math.max(query.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);
|
|
361
|
-
const offset = Math.max(query.offset ?? 0, 0);
|
|
362
|
-
const order = query.sort === "slowest" ? "duration_ms DESC, start_ms DESC" : "start_ms DESC";
|
|
363
|
-
return {
|
|
364
|
-
total,
|
|
365
|
-
traces: this.#database.prepare(`SELECT ${LIST_COLUMNS}
|
|
366
|
-
FROM traces WHERE ${sql} ORDER BY ${order} LIMIT ? OFFSET ?`).all(...params, limit, offset).map(toHistoryTrace)
|
|
367
|
-
};
|
|
368
|
-
}
|
|
369
|
-
/** Counts for each filter over the range, ignoring that filter's own choice. */
|
|
370
|
-
facets(query) {
|
|
371
|
-
this.flush();
|
|
372
|
-
const count = (facet) => {
|
|
373
|
-
const { sql, params } = filterSql(query, facet);
|
|
374
|
-
const column = FACET_COLUMNS[facet];
|
|
375
|
-
return this.#database.prepare(`SELECT ${column} AS value, COUNT(*) AS n FROM traces
|
|
376
|
-
WHERE ${sql} AND ${column} IS NOT NULL
|
|
377
|
-
GROUP BY value ORDER BY n DESC, value ASC LIMIT ?`).all(...params, MAX_FACET_VALUES).map((row) => ({
|
|
378
|
-
value: String(row.value),
|
|
379
|
-
count: Number(row.n)
|
|
380
|
-
}));
|
|
381
|
-
};
|
|
382
|
-
return {
|
|
383
|
-
outcome: count("outcome"),
|
|
384
|
-
method: count("method"),
|
|
385
|
-
service: count("service"),
|
|
386
|
-
endpoint: count("endpoint")
|
|
387
|
-
};
|
|
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];
|
|
388
385
|
}
|
|
389
|
-
/**
|
|
390
|
-
|
|
391
|
-
this
|
|
392
|
-
|
|
393
|
-
const
|
|
394
|
-
const
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
COUNT(*) AS n
|
|
402
|
-
FROM traces WHERE ${sql} GROUP BY bucket, outcome`).all(query.from, bucketMs, ...params);
|
|
403
|
-
for (const row of rows) {
|
|
404
|
-
const bucket = result[Math.min(Math.max(Number(row.bucket), 0), buckets - 1)];
|
|
405
|
-
const outcome = String(row.outcome);
|
|
406
|
-
if (bucket) bucket[outcome] += Number(row.n);
|
|
407
|
-
}
|
|
408
|
-
return result;
|
|
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();
|
|
409
398
|
}
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
this.flush();
|
|
413
|
-
const { sql, params } = filterSql(query);
|
|
414
|
-
const order = query.sort === "slowest" ? "duration_ms DESC, start_ms DESC" : "start_ms DESC";
|
|
415
|
-
return tracesToCsv(this.#database.prepare(`SELECT ${LIST_COLUMNS}
|
|
416
|
-
FROM traces WHERE ${sql} ORDER BY ${order} LIMIT ?`).all(...params, MAX_EXPORT_ROWS).map(toHistoryTrace));
|
|
399
|
+
load() {
|
|
400
|
+
return Promise.all(this.#parts.map((part) => part.host.load())).then(() => void 0);
|
|
417
401
|
}
|
|
418
|
-
/**
|
|
419
|
-
|
|
420
|
-
this.
|
|
421
|
-
const row = this.#database.prepare(`SELECT ${LIST_COLUMNS}, spans FROM traces WHERE trace_id = ?`).get(traceId);
|
|
422
|
-
if (!row) return void 0;
|
|
423
|
-
const { endpoint: _endpoint, ...trace } = toHistoryTrace(row);
|
|
424
|
-
return {
|
|
425
|
-
...trace,
|
|
426
|
-
spans: JSON.parse(String(row.spans))
|
|
427
|
-
};
|
|
402
|
+
/** Rebuild the app's own as its folder changes; plugins' are packages. */
|
|
403
|
+
watch() {
|
|
404
|
+
this.#own?.host.watch();
|
|
428
405
|
}
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
let total = 0;
|
|
434
|
-
let clientErrors = 0;
|
|
435
|
-
let serverErrors = 0;
|
|
436
|
-
const counts = this.#database.prepare(`SELECT ${OUTCOME_CASE} AS outcome, COUNT(*) AS n
|
|
437
|
-
FROM traces WHERE ${sql} GROUP BY outcome`).all(...params);
|
|
438
|
-
for (const row of counts) {
|
|
439
|
-
const n = Number(row.n);
|
|
440
|
-
total += n;
|
|
441
|
-
if (row.outcome === "client") clientErrors = n;
|
|
442
|
-
if (row.outcome === "server") serverErrors = n;
|
|
443
|
-
}
|
|
444
|
-
const durations = this.#database.prepare(`SELECT duration_ms FROM traces
|
|
445
|
-
WHERE ${sql} AND duration_ms IS NOT NULL ORDER BY duration_ms`).all(...params).map((row) => Number(row.duration_ms));
|
|
446
|
-
return {
|
|
447
|
-
total,
|
|
448
|
-
clientErrors,
|
|
449
|
-
serverErrors,
|
|
450
|
-
medianMs: percentile(durations, .5),
|
|
451
|
-
p95Ms: percentile(durations, .95)
|
|
406
|
+
onChange(listener) {
|
|
407
|
+
this.#listeners.add(listener);
|
|
408
|
+
return () => {
|
|
409
|
+
this.#listeners.delete(listener);
|
|
452
410
|
};
|
|
453
411
|
}
|
|
454
|
-
/** Write what is queued and release the database. */
|
|
455
412
|
close() {
|
|
456
|
-
|
|
457
|
-
this.
|
|
458
|
-
this.#closed = true;
|
|
459
|
-
clearInterval(this.#pruneTimer);
|
|
460
|
-
try {
|
|
461
|
-
this.#database.close();
|
|
462
|
-
} catch {}
|
|
413
|
+
for (const part of this.#parts) part.host.close();
|
|
414
|
+
this.#listeners.clear();
|
|
463
415
|
}
|
|
464
416
|
};
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
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
|
+
]);
|
|
442
|
+
return {
|
|
443
|
+
loader: source.loader,
|
|
444
|
+
frontmatter: matter.frontmatter,
|
|
445
|
+
plugins,
|
|
446
|
+
createSearchAPI: search.createSearchAPI,
|
|
447
|
+
compile: mdx.compile
|
|
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;
|
|
452
|
+
}
|
|
491
453
|
}
|
|
492
|
-
|
|
493
|
-
|
|
454
|
+
const humanize = (name) => {
|
|
455
|
+
const spaced = name.replace(/[-_]+/g, " ").trim();
|
|
456
|
+
return spaced.charAt(0).toUpperCase() + spaced.slice(1);
|
|
457
|
+
};
|
|
458
|
+
const H1 = /^#\s+(.+?)\s*#*\s*$/;
|
|
494
459
|
/**
|
|
495
|
-
* The
|
|
496
|
-
*
|
|
497
|
-
*
|
|
498
|
-
* dashboard extension), bundled apart from the dashboard, the dashboard's copy
|
|
499
|
-
* of React and its UI kit, so there is one of each on the page.
|
|
500
|
-
*
|
|
501
|
-
* `extension` describes the project's extension: `revision` changes with every
|
|
502
|
-
* rebuild (the page reloads when it does), `js` and `css` say what it built.
|
|
503
|
-
* `theme` is whether `/assets/brick-theme.css` has token values to apply.
|
|
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.
|
|
504
463
|
*/
|
|
505
|
-
function
|
|
506
|
-
const
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
(
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
<link rel="stylesheet" href="/assets/app.css">
|
|
525
|
-
${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">
|
|
526
|
-
{"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"}}
|
|
527
|
-
<\/script>
|
|
528
|
-
</head>
|
|
529
|
-
<body>
|
|
530
|
-
<div id="root"></div>
|
|
531
|
-
<script type="module" src="/assets/app.js"><\/script>
|
|
532
|
-
</body>
|
|
533
|
-
</html>
|
|
534
|
-
`;
|
|
535
|
-
}
|
|
536
|
-
//#endregion
|
|
537
|
-
//#region src/dashboard-access.ts
|
|
538
|
-
/** How long the app's `authorize` may take before the request is refused. */
|
|
539
|
-
const AUTHORIZE_TIMEOUT_MS = 5e3;
|
|
540
|
-
/** Whether `host` can only be reached from the machine it runs on. */
|
|
541
|
-
function isLoopbackHost(host) {
|
|
542
|
-
const name = host.toLowerCase();
|
|
543
|
-
return name === "localhost" || name === "::1" || name === "[::1]" || /^127(\.\d{1,3}){3}$/.test(name);
|
|
544
|
-
}
|
|
545
|
-
const NOT_COPIED = /* @__PURE__ */ new Set([
|
|
546
|
-
"set-cookie",
|
|
547
|
-
"content-length",
|
|
548
|
-
"content-encoding",
|
|
549
|
-
"transfer-encoding",
|
|
550
|
-
"connection",
|
|
551
|
-
"keep-alive"
|
|
552
|
-
]);
|
|
553
|
-
const digest = (value) => createHash("sha256").update(value).digest();
|
|
554
|
-
/** Whether `candidate` is one of `tokens`, in the same time whichever it is. */
|
|
555
|
-
function isToken(candidate, tokens) {
|
|
556
|
-
if (candidate === void 0) return false;
|
|
557
|
-
const given = digest(candidate);
|
|
558
|
-
let match = false;
|
|
559
|
-
for (const token of tokens) if (timingSafeEqual(given, digest(token))) match = true;
|
|
560
|
-
return match;
|
|
561
|
-
}
|
|
562
|
-
/** The secret in an `Authorization` header: a Bearer token, or a Basic password. */
|
|
563
|
-
function credential(request) {
|
|
564
|
-
const header = request.headers.authorization;
|
|
565
|
-
if (!header) return void 0;
|
|
566
|
-
const space = header.indexOf(" ");
|
|
567
|
-
if (space < 0) return void 0;
|
|
568
|
-
const scheme = header.slice(0, space).toLowerCase();
|
|
569
|
-
const value = header.slice(space + 1).trim();
|
|
570
|
-
if (scheme === "bearer") return value;
|
|
571
|
-
if (scheme === "basic") {
|
|
572
|
-
const decoded = Buffer.from(value, "base64").toString("utf8");
|
|
573
|
-
const colon = decoded.indexOf(":");
|
|
574
|
-
return colon < 0 ? void 0 : decoded.slice(colon + 1);
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
/** The request as the app's `authorize` sees it: standard, with no body. */
|
|
578
|
-
function webRequest(request) {
|
|
579
|
-
const headers = new Headers();
|
|
580
|
-
for (const [name, value] of Object.entries(request.headers)) {
|
|
581
|
-
if (value === void 0) continue;
|
|
582
|
-
try {
|
|
583
|
-
headers.set(name, Array.isArray(value) ? value.join(", ") : value);
|
|
584
|
-
} catch {}
|
|
585
|
-
}
|
|
586
|
-
const forwarded = request.headers["x-forwarded-proto"];
|
|
587
|
-
const protocol = (Array.isArray(forwarded) ? forwarded[0] : forwarded)?.split(",")[0]?.trim() === "https" ? "https" : "http";
|
|
588
|
-
const host = request.headers.host ?? "localhost";
|
|
589
|
-
let url;
|
|
590
|
-
try {
|
|
591
|
-
url = new URL(request.url ?? "/", `${protocol}://${host}`).href;
|
|
592
|
-
} catch {
|
|
593
|
-
url = `${protocol}://localhost${request.url ?? "/"}`;
|
|
594
|
-
}
|
|
595
|
-
return new Request(url, {
|
|
596
|
-
method: request.method ?? "GET",
|
|
597
|
-
headers
|
|
598
|
-
});
|
|
599
|
-
}
|
|
600
|
-
const refusal = (status, body, headers = {}) => ({
|
|
601
|
-
allowed: false,
|
|
602
|
-
status,
|
|
603
|
-
body,
|
|
604
|
-
headers: {
|
|
605
|
-
"content-type": "text/plain; charset=utf-8",
|
|
606
|
-
...headers
|
|
607
|
-
}
|
|
608
|
-
});
|
|
609
|
-
/**
|
|
610
|
-
* The check for the dashboard's requests. A request passes with a valid token,
|
|
611
|
-
* or when the app's `authorize` returns `true`. Anything else is answered:
|
|
612
|
-
* what `authorize` returned if it returned a `Response`, else 401 (with a
|
|
613
|
-
* browser sign-in prompt when tokens are in use), and 503 when `authorize`
|
|
614
|
-
* threw or ran out of time, since a check that cannot answer must not let
|
|
615
|
-
* anyone in.
|
|
616
|
-
*/
|
|
617
|
-
function createAccess(auth, onError = () => {}, timeoutMs = AUTHORIZE_TIMEOUT_MS) {
|
|
618
|
-
const tokens = auth.token === void 0 ? [] : typeof auth.token === "string" ? [auth.token] : [...auth.token];
|
|
619
|
-
const prompt = tokens.length > 0 ? { "www-authenticate": "Basic realm=\"Brick dashboard\", charset=\"UTF-8\"" } : {};
|
|
620
|
-
return async (request) => {
|
|
621
|
-
if (tokens.length > 0 && isToken(credential(request), tokens)) return { allowed: true };
|
|
622
|
-
if (!auth.authorize) return refusal(401, "Unauthorized", prompt);
|
|
623
|
-
let decision;
|
|
624
|
-
let timer;
|
|
625
|
-
try {
|
|
626
|
-
decision = await Promise.race([Promise.resolve(auth.authorize(webRequest(request))), new Promise((_, reject) => {
|
|
627
|
-
timer = setTimeout(() => reject(/* @__PURE__ */ new Error("dashboard authorize timed out")), timeoutMs);
|
|
628
|
-
})]);
|
|
629
|
-
} catch (error) {
|
|
630
|
-
onError(error);
|
|
631
|
-
return refusal(503, "Sign-in is unavailable.");
|
|
632
|
-
} finally {
|
|
633
|
-
clearTimeout(timer);
|
|
634
|
-
}
|
|
635
|
-
if (decision === true) return { allowed: true };
|
|
636
|
-
if (decision instanceof Response) {
|
|
637
|
-
const headers = {};
|
|
638
|
-
decision.headers.forEach((value, name) => {
|
|
639
|
-
if (!NOT_COPIED.has(name)) headers[name] = value;
|
|
640
|
-
});
|
|
641
|
-
const cookies = decision.headers.getSetCookie();
|
|
642
|
-
if (cookies.length > 0) headers["set-cookie"] = cookies;
|
|
643
|
-
return {
|
|
644
|
-
allowed: false,
|
|
645
|
-
status: decision.status,
|
|
646
|
-
headers,
|
|
647
|
-
body: new Uint8Array(await decision.arrayBuffer())
|
|
648
|
-
};
|
|
649
|
-
}
|
|
650
|
-
return refusal(401, "Unauthorized", prompt);
|
|
651
|
-
};
|
|
652
|
-
}
|
|
653
|
-
//#endregion
|
|
654
|
-
//#region src/dev-docs.ts
|
|
655
|
-
const PACKAGES = ["fumadocs-core", "@mdx-js/mdx"];
|
|
656
|
-
const PAGE_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".mdx"]);
|
|
657
|
-
const IMAGE_TYPES = {
|
|
658
|
-
".png": "image/png",
|
|
659
|
-
".jpg": "image/jpeg",
|
|
660
|
-
".jpeg": "image/jpeg",
|
|
661
|
-
".gif": "image/gif",
|
|
662
|
-
".webp": "image/webp",
|
|
663
|
-
".avif": "image/avif",
|
|
664
|
-
".svg": "image/svg+xml",
|
|
665
|
-
".ico": "image/x-icon"
|
|
666
|
-
};
|
|
667
|
-
const REFRESH_DELAY_MS = 100;
|
|
668
|
-
async function loadFumadocs() {
|
|
669
|
-
try {
|
|
670
|
-
const [source, matter, plugins, search, mdx] = await Promise.all([
|
|
671
|
-
import("fumadocs-core/source"),
|
|
672
|
-
import("fumadocs-core/content/md/frontmatter"),
|
|
673
|
-
import("fumadocs-core/mdx-plugins"),
|
|
674
|
-
import("fumadocs-core/search/server"),
|
|
675
|
-
import("@mdx-js/mdx")
|
|
676
|
-
]);
|
|
677
|
-
return {
|
|
678
|
-
loader: source.loader,
|
|
679
|
-
frontmatter: matter.frontmatter,
|
|
680
|
-
plugins,
|
|
681
|
-
createSearchAPI: search.createSearchAPI,
|
|
682
|
-
compile: mdx.compile
|
|
683
|
-
};
|
|
684
|
-
} catch (error) {
|
|
685
|
-
if (error.code === "ERR_MODULE_NOT_FOUND" || /Cannot find (module|package)/.test(String(error?.message))) return [...PACKAGES];
|
|
686
|
-
throw error;
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
const humanize = (name) => {
|
|
690
|
-
const spaced = name.replace(/[-_]+/g, " ").trim();
|
|
691
|
-
return spaced.charAt(0).toUpperCase() + spaced.slice(1);
|
|
692
|
-
};
|
|
693
|
-
const H1 = /^#\s+(.+?)\s*#*\s*$/;
|
|
694
|
-
/**
|
|
695
|
-
* The first `# Heading` outside code fences: its text, and the content without
|
|
696
|
-
* it. The page shows its title above the content, so a heading that only
|
|
697
|
-
* repeats the title would appear twice.
|
|
698
|
-
*/
|
|
699
|
-
function firstHeading(content) {
|
|
700
|
-
const lines = content.split("\n");
|
|
701
|
-
let fenced = false;
|
|
702
|
-
let seenText = false;
|
|
703
|
-
for (const [index, line] of lines.entries()) if (/^\s*(```|~~~)/.test(line)) {
|
|
704
|
-
fenced = !fenced;
|
|
705
|
-
seenText = true;
|
|
706
|
-
} else if (!fenced) {
|
|
707
|
-
const match = H1.exec(line);
|
|
708
|
-
if (match) {
|
|
709
|
-
const rest = [...lines.slice(0, index), ...lines.slice(index + 1)];
|
|
710
|
-
if (rest[index]?.trim() === "") rest.splice(index, 1);
|
|
711
|
-
return {
|
|
712
|
-
text: match[1],
|
|
713
|
-
rest: rest.join("\n"),
|
|
714
|
-
leading: !seenText
|
|
715
|
-
};
|
|
716
|
-
}
|
|
717
|
-
if (line.trim() !== "") seenText = true;
|
|
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;
|
|
718
483
|
}
|
|
719
484
|
}
|
|
720
485
|
async function scan(root, fumadocs, warn) {
|
|
@@ -777,7 +542,7 @@ function walk(node, visit) {
|
|
|
777
542
|
}
|
|
778
543
|
/** Ways a link inside a page can point at another page or a local image. */
|
|
779
544
|
function resolveInside(from, href) {
|
|
780
|
-
if (
|
|
545
|
+
if (isExternalHref(href) || href.startsWith("#")) return void 0;
|
|
781
546
|
if (href.startsWith("/")) return void 0;
|
|
782
547
|
const [target] = href.split(/[?#]/);
|
|
783
548
|
if (!target) return void 0;
|
|
@@ -791,7 +556,6 @@ function resolveInside(from, href) {
|
|
|
791
556
|
var DevDocs = class {
|
|
792
557
|
#root;
|
|
793
558
|
#documentation;
|
|
794
|
-
/** Relative paths in `documentation` start here: the app entry's folder. */
|
|
795
559
|
#base;
|
|
796
560
|
#fumadocs;
|
|
797
561
|
#warn;
|
|
@@ -805,7 +569,7 @@ var DevDocs = class {
|
|
|
805
569
|
#timer;
|
|
806
570
|
#refreshing = Promise.resolve();
|
|
807
571
|
#closed = false;
|
|
808
|
-
#title =
|
|
572
|
+
#title = DEFAULT_TITLE;
|
|
809
573
|
revision = 0;
|
|
810
574
|
constructor(base, documentation, fumadocs, warn) {
|
|
811
575
|
this.#base = base;
|
|
@@ -814,7 +578,6 @@ var DevDocs = class {
|
|
|
814
578
|
this.#fumadocs = fumadocs;
|
|
815
579
|
this.#warn = warn;
|
|
816
580
|
}
|
|
817
|
-
/** Read the folder again and tell listeners. */
|
|
818
581
|
async refresh() {
|
|
819
582
|
this.#refreshing = this.#refreshing.then(() => this.#scan());
|
|
820
583
|
await this.#refreshing;
|
|
@@ -851,11 +614,10 @@ var DevDocs = class {
|
|
|
851
614
|
this.#compiled.clear();
|
|
852
615
|
this.#search = void 0;
|
|
853
616
|
const tree = this.#loader.getPageTree();
|
|
854
|
-
this.#title = typeof tree.name === "string" ? tree.name :
|
|
617
|
+
this.#title = typeof tree.name === "string" ? tree.name : DEFAULT_TITLE;
|
|
855
618
|
this.revision++;
|
|
856
619
|
for (const listener of this.#listeners) listener();
|
|
857
620
|
}
|
|
858
|
-
/** Start watching the folder, and the project's components module. */
|
|
859
621
|
watch() {
|
|
860
622
|
const changed = () => {
|
|
861
623
|
clearTimeout(this.#timer);
|
|
@@ -955,19 +717,18 @@ var DevDocs = class {
|
|
|
955
717
|
* This covers markdown links and the `href` of components such as `<Card>`.
|
|
956
718
|
*/
|
|
957
719
|
#rewriteLinks(tree, from) {
|
|
958
|
-
const file = (resolved) => `/api/docs/files/${resolved.split("/").map(encodeURIComponent).join("/")}`;
|
|
959
720
|
walk(tree, (node) => {
|
|
960
721
|
if (node.type === "link" && node.url !== void 0) node.url = this.#route(from, node.url) ?? node.url;
|
|
961
722
|
else if (node.type === "image" && node.url !== void 0) {
|
|
962
723
|
const resolved = resolveInside(from, node.url);
|
|
963
|
-
if (resolved !== void 0) node.url =
|
|
724
|
+
if (resolved !== void 0) node.url = docsFileUrl(resolved);
|
|
964
725
|
} else if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") for (const attribute of node.attributes ?? []) {
|
|
965
726
|
if (attribute.type !== "mdxJsxAttribute") continue;
|
|
966
727
|
if (typeof attribute.value !== "string") continue;
|
|
967
728
|
if (attribute.name === "href") attribute.value = this.#route(from, attribute.value) ?? attribute.value;
|
|
968
729
|
else if (attribute.name === "src" && node.name === "img") {
|
|
969
730
|
const resolved = resolveInside(from, attribute.value);
|
|
970
|
-
if (resolved !== void 0) attribute.value =
|
|
731
|
+
if (resolved !== void 0) attribute.value = docsFileUrl(resolved);
|
|
971
732
|
}
|
|
972
733
|
}
|
|
973
734
|
});
|
|
@@ -980,10 +741,10 @@ var DevDocs = class {
|
|
|
980
741
|
*/
|
|
981
742
|
#route(from, href) {
|
|
982
743
|
const hashAt = href.indexOf("#");
|
|
983
|
-
const
|
|
744
|
+
const anchor = hashAt >= 0 ? decode(href.slice(hashAt + 1)) : void 0;
|
|
984
745
|
const target = (hashAt >= 0 ? href.slice(0, hashAt) : href).split("?")[0] ?? "";
|
|
985
|
-
const route = (slug) =>
|
|
986
|
-
if (
|
|
746
|
+
const route = (slug) => docsHref(slug ? slug.split("/") : [], anchor);
|
|
747
|
+
if (isExternalHref(href) || !target) return void 0;
|
|
987
748
|
if (target.startsWith("/")) {
|
|
988
749
|
const slug = target.replace(/^\/+|\/+$/g, "");
|
|
989
750
|
return this.#pages.has(slug) ? route(slug) : void 0;
|
|
@@ -1046,54 +807,6 @@ var DevDocs = class {
|
|
|
1046
807
|
this.#listeners.clear();
|
|
1047
808
|
}
|
|
1048
809
|
};
|
|
1049
|
-
const SHARED = [
|
|
1050
|
-
"react",
|
|
1051
|
-
"react/jsx-runtime",
|
|
1052
|
-
"react/jsx-dev-runtime",
|
|
1053
|
-
"react-dom",
|
|
1054
|
-
"react-dom/client",
|
|
1055
|
-
"@brickkit/cli/dashboard"
|
|
1056
|
-
];
|
|
1057
|
-
/** Bundle a module of React components for the dashboard to import. */
|
|
1058
|
-
async function bundleComponents(entry) {
|
|
1059
|
-
if (typeof Bun !== "undefined") {
|
|
1060
|
-
const result = await Bun.build({
|
|
1061
|
-
entrypoints: [entry],
|
|
1062
|
-
target: "browser",
|
|
1063
|
-
format: "esm",
|
|
1064
|
-
external: SHARED,
|
|
1065
|
-
minify: false,
|
|
1066
|
-
throw: false
|
|
1067
|
-
});
|
|
1068
|
-
if (!result.success) throw new Error(result.logs.map((log) => log.message).join("\n"));
|
|
1069
|
-
return (result.outputs.find((item) => item.kind === "entry-point") ?? result.outputs[0]).text();
|
|
1070
|
-
}
|
|
1071
|
-
const { build } = await import("vite");
|
|
1072
|
-
const output = await build({
|
|
1073
|
-
configFile: false,
|
|
1074
|
-
logLevel: "silent",
|
|
1075
|
-
root: dirname(entry),
|
|
1076
|
-
oxc: { jsx: { runtime: "automatic" } },
|
|
1077
|
-
esbuild: { jsx: "automatic" },
|
|
1078
|
-
define: { "process.env.NODE_ENV": "\"development\"" },
|
|
1079
|
-
build: {
|
|
1080
|
-
write: false,
|
|
1081
|
-
minify: false,
|
|
1082
|
-
lib: {
|
|
1083
|
-
entry,
|
|
1084
|
-
formats: ["es"],
|
|
1085
|
-
fileName: "components"
|
|
1086
|
-
},
|
|
1087
|
-
rollupOptions: { external: SHARED }
|
|
1088
|
-
}
|
|
1089
|
-
});
|
|
1090
|
-
const bundles = Array.isArray(output) ? output : [output];
|
|
1091
|
-
for (const bundle of bundles) {
|
|
1092
|
-
const chunk = ("output" in bundle ? bundle.output : []).find((item) => item.type === "chunk" && item.isEntry);
|
|
1093
|
-
if (chunk && "code" in chunk) return chunk.code;
|
|
1094
|
-
}
|
|
1095
|
-
throw new Error("Brick: the docs components module produced no output.");
|
|
1096
|
-
}
|
|
1097
810
|
/** Flatten what MDX gives for a heading to text. */
|
|
1098
811
|
function plainText(value) {
|
|
1099
812
|
if (typeof value === "string") return value;
|
|
@@ -1131,7 +844,7 @@ function simplify(tree) {
|
|
|
1131
844
|
};
|
|
1132
845
|
};
|
|
1133
846
|
return {
|
|
1134
|
-
name: text(tree?.name) ||
|
|
847
|
+
name: text(tree?.name) || DEFAULT_TITLE,
|
|
1135
848
|
children: (tree?.children ?? []).flatMap((child) => convert(child) ?? [])
|
|
1136
849
|
};
|
|
1137
850
|
}
|
|
@@ -1164,14 +877,14 @@ async function openDocs(options) {
|
|
|
1164
877
|
* are, replaced when that changes, and closed when it stops asking for them.
|
|
1165
878
|
*/
|
|
1166
879
|
var DocsHost = class {
|
|
1167
|
-
#
|
|
880
|
+
#publish;
|
|
1168
881
|
#warn;
|
|
1169
882
|
#docs;
|
|
1170
883
|
#stopListening;
|
|
1171
884
|
#key;
|
|
1172
885
|
#pending = Promise.resolve();
|
|
1173
|
-
constructor(
|
|
1174
|
-
this.#
|
|
886
|
+
constructor(publish, warn) {
|
|
887
|
+
this.#publish = publish;
|
|
1175
888
|
this.#warn = warn;
|
|
1176
889
|
}
|
|
1177
890
|
get current() {
|
|
@@ -1191,7 +904,7 @@ var DocsHost = class {
|
|
|
1191
904
|
this.#key = key;
|
|
1192
905
|
this.#release();
|
|
1193
906
|
if (!documentation) {
|
|
1194
|
-
this.#
|
|
907
|
+
this.#publish(null);
|
|
1195
908
|
return;
|
|
1196
909
|
}
|
|
1197
910
|
const opened = await openDocs({
|
|
@@ -1202,19 +915,19 @@ var DocsHost = class {
|
|
|
1202
915
|
if (opened.status !== "ready") {
|
|
1203
916
|
const message = opened.status === "missing" ? `The docs need ${opened.packages.join(" and ")}. Install with: bun add -d ${opened.packages.join(" ")}` : opened.message;
|
|
1204
917
|
this.#warn(`[Brick-TS] Docs are off. ${message}`);
|
|
1205
|
-
this.#
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
918
|
+
this.#publish(opened.status === "missing" ? {
|
|
919
|
+
status: "missing",
|
|
920
|
+
packages: opened.packages,
|
|
921
|
+
message
|
|
922
|
+
} : {
|
|
923
|
+
status: "error",
|
|
924
|
+
message
|
|
1212
925
|
});
|
|
1213
926
|
return;
|
|
1214
927
|
}
|
|
1215
928
|
this.#docs = opened.docs;
|
|
1216
|
-
this.#stopListening = opened.docs.onChange(() => this.#
|
|
1217
|
-
this.#
|
|
929
|
+
this.#stopListening = opened.docs.onChange(() => this.#publish(opened.docs.snapshot()));
|
|
930
|
+
this.#publish(opened.docs.snapshot());
|
|
1218
931
|
}
|
|
1219
932
|
#release() {
|
|
1220
933
|
this.#stopListening?.();
|
|
@@ -1227,387 +940,278 @@ var DocsHost = class {
|
|
|
1227
940
|
this.#release();
|
|
1228
941
|
}
|
|
1229
942
|
};
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
"
|
|
1235
|
-
"foreground",
|
|
1236
|
-
"card",
|
|
1237
|
-
"card-foreground",
|
|
1238
|
-
"popover",
|
|
1239
|
-
"popover-foreground",
|
|
1240
|
-
"primary",
|
|
1241
|
-
"primary-foreground",
|
|
1242
|
-
"secondary",
|
|
1243
|
-
"secondary-foreground",
|
|
1244
|
-
"muted",
|
|
1245
|
-
"muted-foreground",
|
|
1246
|
-
"accent",
|
|
1247
|
-
"accent-foreground",
|
|
1248
|
-
"destructive",
|
|
1249
|
-
"destructive-foreground",
|
|
1250
|
-
"positive",
|
|
1251
|
-
"border",
|
|
1252
|
-
"input",
|
|
1253
|
-
"ring",
|
|
1254
|
-
"chart-1",
|
|
1255
|
-
"chart-2",
|
|
1256
|
-
"chart-3",
|
|
1257
|
-
"chart-4",
|
|
1258
|
-
"chart-5",
|
|
1259
|
-
"span-request",
|
|
1260
|
-
"span-action",
|
|
1261
|
-
"span-rpc",
|
|
1262
|
-
"span-sql",
|
|
1263
|
-
"span-event",
|
|
1264
|
-
"span-other"
|
|
1265
|
-
];
|
|
1266
|
-
const THEME_KEYS = /* @__PURE__ */ new Set([
|
|
1267
|
-
"light",
|
|
1268
|
-
"dark",
|
|
1269
|
-
"radius",
|
|
1270
|
-
"fonts"
|
|
1271
|
-
]);
|
|
1272
|
-
const FONT_KEYS = /* @__PURE__ */ new Set(["sans", "mono"]);
|
|
1273
|
-
const TOKENS = new Set(THEME_TOKENS);
|
|
1274
|
-
/** A value that cannot close the rule it sits in. */
|
|
1275
|
-
function cssValue(where, value) {
|
|
1276
|
-
if (typeof value !== "string" || !value.trim() || /[;{}<>\\]/.test(value)) throw new Error(`Brick: dashboard.theme.${where} must be a CSS value without ; { } < > or \\.`);
|
|
1277
|
-
return value.trim();
|
|
1278
|
-
}
|
|
1279
|
-
/**
|
|
1280
|
-
* The stylesheet for a theme, loaded after the dashboard's own; empty when the
|
|
1281
|
-
* theme sets nothing. Throws on a token name theme.css does not have.
|
|
1282
|
-
*/
|
|
1283
|
-
function themeCss(theme) {
|
|
1284
|
-
if (!theme) return "";
|
|
1285
|
-
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.`);
|
|
1286
|
-
const rules = [];
|
|
1287
|
-
const root = [];
|
|
1288
|
-
if (theme.radius !== void 0) root.push(`--radius: ${cssValue("radius", theme.radius)};`);
|
|
1289
|
-
for (const [name, value] of Object.entries(theme.fonts ?? {})) {
|
|
1290
|
-
if (!FONT_KEYS.has(name)) throw new Error(`Brick: dashboard.theme.fonts has no "${name}". It takes sans and mono.`);
|
|
1291
|
-
root.push(`--font-${name}: ${cssValue(`fonts.${name}`, value)};`);
|
|
1292
|
-
}
|
|
1293
|
-
if (root.length) rules.push(`:root {\n ${root.join("\n ")}\n}`);
|
|
1294
|
-
for (const [mode, selector] of [["light", ":root:not(.dark)"], ["dark", ":root.dark"]]) {
|
|
1295
|
-
const tokens = theme[mode];
|
|
1296
|
-
if (!tokens) continue;
|
|
1297
|
-
const lines = Object.entries(tokens).map(([name, value]) => {
|
|
1298
|
-
if (!TOKENS.has(name)) throw new Error(`Brick: dashboard.theme.${mode} has no token "${name}". Tokens: ${THEME_TOKENS.join(", ")}.`);
|
|
1299
|
-
return `--${name}: ${cssValue(`${mode}.${name}`, value)};`;
|
|
1300
|
-
});
|
|
1301
|
-
if (lines.length) rules.push(`${selector} {\n ${lines.join("\n ")}\n}`);
|
|
1302
|
-
}
|
|
1303
|
-
return rules.length ? `${rules.join("\n")}\n` : "";
|
|
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";
|
|
1304
948
|
}
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
for (const relative of ["../dashboard-dist/", "../../dashboard-dist/"]) {
|
|
1308
|
-
const directory = fileURLToPath(new URL(relative, import.meta.url));
|
|
1309
|
-
if (existsSync(join(directory, "app.js"))) return directory;
|
|
1310
|
-
}
|
|
949
|
+
function endpointOf(trace) {
|
|
950
|
+
return trace.method && trace.route ? `${trace.method} ${trace.route}` : trace.name;
|
|
1311
951
|
}
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
const
|
|
1330
|
-
if (!tailwind || !main) {
|
|
1331
|
-
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.");
|
|
1332
|
-
warnedTailwind = true;
|
|
1333
|
-
return "";
|
|
1334
|
-
}
|
|
1335
|
-
const root = dirname(tailwind);
|
|
1336
|
-
const { compile } = await import(pathToFileURL(main).href);
|
|
1337
|
-
const compiler = await compile(`@layer theme, base, components, utilities;
|
|
1338
|
-
@import "tailwindcss/theme.css" theme(reference inline);
|
|
1339
|
-
@import "tailwindcss/utilities.css" layer(utilities);
|
|
1340
|
-
@reference "brick/theme.css";
|
|
1341
|
-
`, {
|
|
1342
|
-
base: root,
|
|
1343
|
-
async loadStylesheet(id) {
|
|
1344
|
-
const path = id === "brick/theme.css" ? themeFile : join(root, id.replace(/^tailwindcss\//, ""));
|
|
1345
|
-
return {
|
|
1346
|
-
path,
|
|
1347
|
-
base: dirname(path),
|
|
1348
|
-
content: await readFile(path, "utf8")
|
|
1349
|
-
};
|
|
1350
|
-
}
|
|
1351
|
-
});
|
|
1352
|
-
const candidates = new Set(js.split(/[\s"'`]+/).filter(Boolean));
|
|
1353
|
-
const css = compiler.build([...candidates]);
|
|
1354
|
-
return /\{/.test(css) ? css : "";
|
|
1355
|
-
}
|
|
1356
|
-
/** Bundle the extension and its styles for the dashboard page. */
|
|
1357
|
-
async function buildDashboardExtension(entry, options = {}) {
|
|
1358
|
-
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;
|
|
1359
970
|
return {
|
|
1360
|
-
|
|
1361
|
-
|
|
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")
|
|
1362
982
|
};
|
|
1363
983
|
}
|
|
1364
|
-
/**
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
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);
|
|
1001
|
+
}
|
|
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;
|
|
1020
|
+
}
|
|
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";
|
|
1037
|
+
}
|
|
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));
|
|
1399
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)])) });
|
|
1400
1053
|
/**
|
|
1401
|
-
* The
|
|
1402
|
-
*
|
|
1403
|
-
*
|
|
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.
|
|
1404
1063
|
*/
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
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);
|
|
1448
1132
|
}
|
|
1449
|
-
|
|
1450
|
-
|
|
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;
|
|
1451
1144
|
try {
|
|
1452
|
-
|
|
1453
|
-
if (file && /(^|[\\/])(node_modules|\.)/.test(file)) return;
|
|
1454
|
-
clearTimeout(this.#timer);
|
|
1455
|
-
this.#timer = setTimeout(() => void this.load(), 100);
|
|
1456
|
-
});
|
|
1145
|
+
headers.set(name, Array.isArray(value) ? value.join(", ") : value);
|
|
1457
1146
|
} catch {}
|
|
1458
1147
|
}
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
};
|
|
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 ?? "/"}`;
|
|
1464
1155
|
}
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
}
|
|
1470
|
-
};
|
|
1471
|
-
/** The plugins' extensions by path, each once, in install order. */
|
|
1472
|
-
function pluginDashboards(plugins) {
|
|
1473
|
-
const wanted = /* @__PURE__ */ new Map();
|
|
1474
|
-
for (const plugin of plugins) if (plugin.dashboard && !wanted.has(resolve(plugin.dashboard))) wanted.set(resolve(plugin.dashboard), plugin.name);
|
|
1475
|
-
return wanted;
|
|
1156
|
+
return new Request(url, {
|
|
1157
|
+
method: request.method ?? "GET",
|
|
1158
|
+
headers
|
|
1159
|
+
});
|
|
1476
1160
|
}
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
return `const parts = ${JSON.stringify(parts)};
|
|
1486
|
-
const loaded = await Promise.allSettled(parts.map((part) => import(part.src)));
|
|
1487
|
-
const merged = { pages: [], sidebar: [], slots: {} };
|
|
1488
|
-
const roots = [];
|
|
1489
|
-
loaded.forEach((result, index) => {
|
|
1490
|
-
const { name, plugin } = parts[index];
|
|
1491
|
-
const extension = result.status === "fulfilled" ? result.value.default : undefined;
|
|
1492
|
-
if (!extension || typeof extension !== "object") {
|
|
1493
|
-
console.error("[Brick dashboard] Extension " + name + " failed to load:", result.status === "rejected" ? result.reason : "it must default-export defineDashboard({ ... })");
|
|
1494
|
-
return;
|
|
1495
|
-
}
|
|
1496
|
-
for (const page of extension.pages ?? []) {
|
|
1497
|
-
if (merged.pages.some((item) => item.id === page.id)) {
|
|
1498
|
-
console.error("[Brick dashboard] Extension " + name + ": page id " + page.id + " is taken; skipped.");
|
|
1499
|
-
continue;
|
|
1500
|
-
}
|
|
1501
|
-
merged.pages.push(plugin && !page.after && !page.section ? { ...page, section: name } : page);
|
|
1502
|
-
}
|
|
1503
|
-
merged.sidebar.push(...(extension.sidebar ?? []));
|
|
1504
|
-
for (const [slot, value] of Object.entries(extension.slots ?? {})) {
|
|
1505
|
-
if (slot === "request.drawer.tabs") merged.slots[slot] = [...(merged.slots[slot] ?? []), ...value];
|
|
1506
|
-
else if (!(slot in merged.slots)) merged.slots[slot] = value;
|
|
1507
|
-
}
|
|
1508
|
-
if (extension.root) roots.push(extension.root);
|
|
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
|
|
1168
|
+
}
|
|
1509
1169
|
});
|
|
1510
|
-
if (roots.length) {
|
|
1511
|
-
const { createElement } = await import("react");
|
|
1512
|
-
merged.root = ({ children }) => roots.reduceRight((inner, Root) => createElement(Root, null, inner), children);
|
|
1513
|
-
}
|
|
1514
|
-
export default merged;
|
|
1515
|
-
`;
|
|
1516
|
-
}
|
|
1517
1170
|
/**
|
|
1518
|
-
* The
|
|
1519
|
-
* app's
|
|
1520
|
-
*
|
|
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.
|
|
1521
1177
|
*/
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
}
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
return
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
plugin: !(this.#own && index === 0)
|
|
1560
|
-
}] : [])),
|
|
1561
|
-
css: built.map((part) => part.host.built.css).join("")
|
|
1562
|
-
};
|
|
1563
|
-
}
|
|
1564
|
-
get error() {
|
|
1565
|
-
const errors = this.#parts.flatMap((part) => part.host.error ? [this.#own && this.#parts.length === 1 ? part.host.error : `${part.name}: ${part.host.error}`] : []);
|
|
1566
|
-
return errors.length ? errors.join("\n") : void 0;
|
|
1567
|
-
}
|
|
1568
|
-
/** A file under `/assets/` this serves, or undefined. */
|
|
1569
|
-
asset(name) {
|
|
1570
|
-
if (name === "extension.js") return this.built?.js;
|
|
1571
|
-
if (name === "extension.css") return this.built?.css;
|
|
1572
|
-
const match = /^extension-(\d+)\.js$/.exec(name);
|
|
1573
|
-
if (!match) return void 0;
|
|
1574
|
-
if (this.#own && this.#parts.length === 1) return this.#parts[0].host.built?.parts?.[name];
|
|
1575
|
-
return this.#parts[Number(match[1])]?.host.built?.js;
|
|
1576
|
-
}
|
|
1577
|
-
/** Follow the app's plugins: build the extensions they ship, drop the rest. */
|
|
1578
|
-
async setPlugins(plugins) {
|
|
1579
|
-
if (this.#own && existsSync(join(this.#parts[0].path, "extension.js"))) return;
|
|
1580
|
-
const wanted = pluginDashboards(plugins);
|
|
1581
|
-
const start = this.#own ? 1 : 0;
|
|
1582
|
-
const current = this.#parts.slice(start);
|
|
1583
|
-
if (current.length === wanted.size && current.every((part) => wanted.get(part.path) === part.name)) return;
|
|
1584
|
-
for (const part of current) part.host.close();
|
|
1585
|
-
this.#parts.splice(start);
|
|
1586
|
-
const loads = [...wanted].map(([path, name]) => this.#add(name, path).load());
|
|
1587
|
-
await Promise.all(loads);
|
|
1588
|
-
this.#changed();
|
|
1589
|
-
}
|
|
1590
|
-
load() {
|
|
1591
|
-
return Promise.all(this.#parts.map((part) => part.host.load())).then(() => void 0);
|
|
1592
|
-
}
|
|
1593
|
-
/** Rebuild the app's own as its folder changes; plugins' are packages. */
|
|
1594
|
-
watch() {
|
|
1595
|
-
if (this.#own) this.#parts[0].host.watch();
|
|
1596
|
-
}
|
|
1597
|
-
onChange(listener) {
|
|
1598
|
-
this.#listeners.add(listener);
|
|
1599
|
-
return () => {
|
|
1600
|
-
this.#listeners.delete(listener);
|
|
1601
|
-
};
|
|
1602
|
-
}
|
|
1603
|
-
close() {
|
|
1604
|
-
for (const part of this.#parts) part.host.close();
|
|
1605
|
-
this.#listeners.clear();
|
|
1606
|
-
}
|
|
1607
|
-
};
|
|
1608
|
-
//#endregion
|
|
1609
|
-
//#region src/dev-dashboard.ts
|
|
1610
|
-
const DEFAULT_DASHBOARD_PORT = 9400;
|
|
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
|
+
}
|
|
1214
|
+
// src/dev-dashboard.ts
|
|
1611
1215
|
const KEEPALIVE_MS = 15e3;
|
|
1612
1216
|
const MAX_INGEST_BYTES = 5242880;
|
|
1613
1217
|
const MAX_PROXY_BYTES = 10485760;
|
|
@@ -1634,17 +1238,6 @@ const NOT_RETURNED = /* @__PURE__ */ new Set([
|
|
|
1634
1238
|
"content-encoding",
|
|
1635
1239
|
"set-cookie"
|
|
1636
1240
|
]);
|
|
1637
|
-
/**
|
|
1638
|
-
* What a production dashboard may show: the shell and its assets, the live
|
|
1639
|
-
* state and its event stream, and stored history. Nothing that changes the app
|
|
1640
|
-
* or reaches into it (restart, the API proxy, ingest) and nothing from the
|
|
1641
|
-
* project's source (documentation, OpenAPI documents). With an extension, the
|
|
1642
|
-
* `/app` proxy its pages read the app through.
|
|
1643
|
-
*/
|
|
1644
|
-
const isMonitoringRoute = (method, pathname, extension) => extension && isAppRoute(pathname) || method === "GET" && (pathname === "/" || pathname.startsWith("/assets/") || pathname === "/api/state" || pathname === "/api/events" || pathname.startsWith("/api/history"));
|
|
1645
|
-
/** `/app/*` reaches the app itself, for the extension's `useAppFetch`. */
|
|
1646
|
-
const APP_PATH = "/app";
|
|
1647
|
-
const isAppRoute = (pathname) => pathname === APP_PATH || pathname.startsWith(`${APP_PATH}/`);
|
|
1648
1241
|
const PRODUCTION_HEADERS = {
|
|
1649
1242
|
"x-content-type-options": "nosniff",
|
|
1650
1243
|
"x-frame-options": "DENY",
|
|
@@ -1667,7 +1260,7 @@ function startDevDashboard(options) {
|
|
|
1667
1260
|
const host = options.host ?? "127.0.0.1";
|
|
1668
1261
|
const loopback = isLoopbackHost(host);
|
|
1669
1262
|
const production = options.mode === "production";
|
|
1670
|
-
if (!loopback && !options.auth) return Promise.reject(
|
|
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.`));
|
|
1671
1264
|
let theme;
|
|
1672
1265
|
try {
|
|
1673
1266
|
theme = themeCss(options.dashboard?.theme);
|
|
@@ -1691,8 +1284,8 @@ function startDevDashboard(options) {
|
|
|
1691
1284
|
return;
|
|
1692
1285
|
}
|
|
1693
1286
|
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
1694
|
-
const
|
|
1695
|
-
if (
|
|
1287
|
+
const route = matchRoute(request.method, url.pathname);
|
|
1288
|
+
if (route === "health") {
|
|
1696
1289
|
await health(response);
|
|
1697
1290
|
return;
|
|
1698
1291
|
}
|
|
@@ -1703,11 +1296,19 @@ function startDevDashboard(options) {
|
|
|
1703
1296
|
return;
|
|
1704
1297
|
}
|
|
1705
1298
|
}
|
|
1706
|
-
if (production && !
|
|
1299
|
+
if (!route || production && !servedInProduction(route)) {
|
|
1707
1300
|
send(response, 404, "Not found");
|
|
1708
1301
|
return;
|
|
1709
1302
|
}
|
|
1710
|
-
|
|
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;
|
|
1711
1312
|
}
|
|
1712
1313
|
/** 200 while the app answers its own health check, 503 when it does not. */
|
|
1713
1314
|
async function health(response) {
|
|
@@ -1728,84 +1329,52 @@ function startDevDashboard(options) {
|
|
|
1728
1329
|
"cache-control": "no-store"
|
|
1729
1330
|
});
|
|
1730
1331
|
}
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
if (request.method === "GET" && pathname.startsWith("/assets/")) {
|
|
1748
|
-
const name = pathname.slice(8);
|
|
1749
|
-
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);
|
|
1750
1348
|
if (own !== void 0) send(response, 200, own, {
|
|
1751
|
-
"content-type":
|
|
1349
|
+
"content-type": assetType(name),
|
|
1752
1350
|
"cache-control": "no-store"
|
|
1753
1351
|
});
|
|
1754
1352
|
else serveAsset(response, name);
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
docsRoute(response, pathname, url.searchParams);
|
|
1775
|
-
return;
|
|
1776
|
-
}
|
|
1777
|
-
if (request.method === "GET" && pathname === "/api/openapi") {
|
|
1778
|
-
send(response, 200, JSON.stringify(options.store.apiDocuments()), {
|
|
1779
|
-
"content-type": "application/json",
|
|
1780
|
-
"cache-control": "no-store"
|
|
1781
|
-
});
|
|
1782
|
-
return;
|
|
1783
|
-
}
|
|
1784
|
-
if (pathname === "/api/proxy") {
|
|
1785
|
-
proxy(request, response, url);
|
|
1786
|
-
return;
|
|
1787
|
-
}
|
|
1788
|
-
if (pathname === "/workflows" || pathname.startsWith(`/workflows/`)) {
|
|
1789
|
-
response.setHeader("content-security-policy", "frame-ancestors 'self'");
|
|
1790
|
-
response.setHeader("x-frame-options", "SAMEORIGIN");
|
|
1791
|
-
inspector(request, response, url);
|
|
1792
|
-
return;
|
|
1793
|
-
}
|
|
1794
|
-
if (request.method === "POST" && pathname === "/api/ingest") {
|
|
1795
|
-
ingest(request, response);
|
|
1796
|
-
return;
|
|
1797
|
-
}
|
|
1798
|
-
if (request.method === "POST" && pathname === "/api/restart" && options.restart) {
|
|
1799
|
-
if (request.headers["x-brick-dashboard"] !== "1") {
|
|
1800
|
-
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");
|
|
1801
1372
|
return;
|
|
1802
1373
|
}
|
|
1803
1374
|
options.restart();
|
|
1804
1375
|
send(response, 202, "");
|
|
1805
|
-
return;
|
|
1806
1376
|
}
|
|
1807
|
-
|
|
1808
|
-
}
|
|
1377
|
+
};
|
|
1809
1378
|
function snapshot() {
|
|
1810
1379
|
return {
|
|
1811
1380
|
...options.store.snapshot(),
|
|
@@ -1823,50 +1392,36 @@ function startDevDashboard(options) {
|
|
|
1823
1392
|
* the dashboard, such as a dev server worker: span batches, and a notice when
|
|
1824
1393
|
* the app loads.
|
|
1825
1394
|
*/
|
|
1826
|
-
function ingest(request, response) {
|
|
1827
|
-
|
|
1828
|
-
|
|
1395
|
+
async function ingest(request, response) {
|
|
1396
|
+
const body = await readBytes(request, MAX_INGEST_BYTES);
|
|
1397
|
+
if (!body) {
|
|
1398
|
+
tooLarge(response);
|
|
1829
1399
|
return;
|
|
1830
1400
|
}
|
|
1831
|
-
let
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
if (rejected) return;
|
|
1845
|
-
try {
|
|
1846
|
-
const payload = JSON.parse(body);
|
|
1847
|
-
if (Array.isArray(payload.records)) options.store.ingest(payload.records, options.store.latestGeneration);
|
|
1848
|
-
if (typeof payload.worker === "string") options.store.startGeneration(payload.worker);
|
|
1849
|
-
send(response, 204, "");
|
|
1850
|
-
} catch {
|
|
1851
|
-
send(response, 400, "Bad request");
|
|
1852
|
-
}
|
|
1853
|
-
});
|
|
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, "");
|
|
1854
1414
|
}
|
|
1855
|
-
/** The Docs tab's data: tree, compiled pages, search, images, components. */
|
|
1856
1415
|
async function docsRoute(response, pathname, params) {
|
|
1857
1416
|
const docs = options.docs?.();
|
|
1858
1417
|
if (!docs) {
|
|
1859
1418
|
send(response, 404, "The app has no documentation.");
|
|
1860
1419
|
return;
|
|
1861
1420
|
}
|
|
1862
|
-
const json = (body) => send(response, 200, JSON.stringify(body), {
|
|
1863
|
-
"content-type": "application/json",
|
|
1864
|
-
"cache-control": "no-store"
|
|
1865
|
-
});
|
|
1866
1421
|
try {
|
|
1867
|
-
if (pathname ===
|
|
1868
|
-
if (pathname ===
|
|
1869
|
-
if (pathname ===
|
|
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) {
|
|
1870
1425
|
const code = await docs.components();
|
|
1871
1426
|
if (code === void 0) return send(response, 404, "No components.");
|
|
1872
1427
|
return send(response, 200, code, {
|
|
@@ -1874,14 +1429,15 @@ function startDevDashboard(options) {
|
|
|
1874
1429
|
"cache-control": "no-store"
|
|
1875
1430
|
});
|
|
1876
1431
|
}
|
|
1877
|
-
const pagePrefix =
|
|
1432
|
+
const pagePrefix = DOCS_PATHS.page;
|
|
1878
1433
|
if (pathname === pagePrefix || pathname.startsWith(`${pagePrefix}/`)) {
|
|
1879
|
-
const slugs = pathname.slice(
|
|
1434
|
+
const slugs = pathname.slice(pagePrefix.length).split("/").filter(Boolean).map(decodeURIComponent);
|
|
1880
1435
|
const page = await docs.page(slugs);
|
|
1881
|
-
return page ? json(page) : send(response, 404, "No such page.");
|
|
1436
|
+
return page ? json(response, page) : send(response, 404, "No such page.");
|
|
1882
1437
|
}
|
|
1883
|
-
|
|
1884
|
-
|
|
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("/"));
|
|
1885
1441
|
if (!file) return send(response, 404, "No such file.");
|
|
1886
1442
|
return send(response, 200, file.body, {
|
|
1887
1443
|
"content-type": file.type,
|
|
@@ -1895,13 +1451,6 @@ function startDevDashboard(options) {
|
|
|
1895
1451
|
}
|
|
1896
1452
|
}
|
|
1897
1453
|
/**
|
|
1898
|
-
* Send a request on to the app for the APIs view, which cannot call the app
|
|
1899
|
-
* directly: it is another origin. Only the dashboard's own page may use this,
|
|
1900
|
-
* and only to reach the app being shown. The address to call is `?url=`; a
|
|
1901
|
-
* `?cookie=` is the cookie parameters the reader typed into Try it, and the
|
|
1902
|
-
* only cookie the app is sent (the dashboard's own are never forwarded).
|
|
1903
|
-
*/
|
|
1904
|
-
/**
|
|
1905
1454
|
* Pass a request to the workflow inspector, which the app serves on a port of
|
|
1906
1455
|
* its own, and stream its answer back (it follows a run's output as it
|
|
1907
1456
|
* grows). Anyone who can open the dashboard may look, but a change must come
|
|
@@ -1914,10 +1463,7 @@ function startDevDashboard(options) {
|
|
|
1914
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" });
|
|
1915
1464
|
return;
|
|
1916
1465
|
}
|
|
1917
|
-
|
|
1918
|
-
const site = request.headers["sec-fetch-site"];
|
|
1919
|
-
const origin = request.headers.origin;
|
|
1920
|
-
if (!bodyless && (site !== void 0 && site !== "same-origin" || origin !== void 0 && origin !== `http://${request.headers.host}`)) {
|
|
1466
|
+
if (!isBodyless(request) && !fromOwnPage(request)) {
|
|
1921
1467
|
send(response, 403, "Forbidden");
|
|
1922
1468
|
return;
|
|
1923
1469
|
}
|
|
@@ -1929,9 +1475,7 @@ function startDevDashboard(options) {
|
|
|
1929
1475
|
* API proxy. A credential for the dashboard itself is not passed on.
|
|
1930
1476
|
*/
|
|
1931
1477
|
async function app(request, response, url) {
|
|
1932
|
-
|
|
1933
|
-
const origin = request.headers.origin;
|
|
1934
|
-
if (site !== void 0 && site !== "same-origin" || origin !== void 0 && origin !== `http://${request.headers.host}`) {
|
|
1478
|
+
if (!fromOwnPage(request)) {
|
|
1935
1479
|
send(response, 403, "Forbidden");
|
|
1936
1480
|
return;
|
|
1937
1481
|
}
|
|
@@ -1940,21 +1484,17 @@ function startDevDashboard(options) {
|
|
|
1940
1484
|
send(response, 503, "The app is not running yet.");
|
|
1941
1485
|
return;
|
|
1942
1486
|
}
|
|
1943
|
-
response
|
|
1944
|
-
response.
|
|
1945
|
-
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) => {
|
|
1946
1489
|
if (access) headers.delete("authorization");
|
|
1947
1490
|
}, "Could not reach the app.");
|
|
1948
1491
|
}
|
|
1949
|
-
/**
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
if (name.startsWith("sec-")) continue;
|
|
1956
|
-
headers.set(name, Array.isArray(value) ? value.join(", ") : value);
|
|
1957
|
-
}
|
|
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);
|
|
1958
1498
|
adjust(headers);
|
|
1959
1499
|
const abort = new AbortController();
|
|
1960
1500
|
response.on("close", () => abort.abort());
|
|
@@ -1964,16 +1504,12 @@ function startDevDashboard(options) {
|
|
|
1964
1504
|
headers,
|
|
1965
1505
|
redirect: "manual",
|
|
1966
1506
|
signal: abort.signal,
|
|
1967
|
-
...
|
|
1507
|
+
...isBodyless(request) ? {} : body ? { body } : {
|
|
1968
1508
|
body: Readable.toWeb(request),
|
|
1969
1509
|
duplex: "half"
|
|
1970
1510
|
}
|
|
1971
1511
|
});
|
|
1972
|
-
|
|
1973
|
-
upstream.headers.forEach((value, name) => {
|
|
1974
|
-
if (!NOT_RETURNED.has(name)) returned[name] = value;
|
|
1975
|
-
});
|
|
1976
|
-
response.writeHead(upstream.status, returned);
|
|
1512
|
+
response.writeHead(upstream.status, returnedHeaders(upstream));
|
|
1977
1513
|
if (!upstream.body || request.method === "HEAD") {
|
|
1978
1514
|
response.end();
|
|
1979
1515
|
return;
|
|
@@ -1984,10 +1520,15 @@ function startDevDashboard(options) {
|
|
|
1984
1520
|
else send(response, 502, unreachable);
|
|
1985
1521
|
}
|
|
1986
1522
|
}
|
|
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
|
+
*/
|
|
1987
1530
|
async function proxy(request, response, url) {
|
|
1988
|
-
|
|
1989
|
-
const origin = request.headers.origin;
|
|
1990
|
-
if (site !== void 0 && site !== "same-origin" || origin !== void 0 && origin !== `http://${request.headers.host}`) {
|
|
1531
|
+
if (!fromOwnPage(request)) {
|
|
1991
1532
|
send(response, 403, "Forbidden");
|
|
1992
1533
|
return;
|
|
1993
1534
|
}
|
|
@@ -2002,155 +1543,525 @@ function startDevDashboard(options) {
|
|
|
2002
1543
|
}
|
|
2003
1544
|
const body = await readBytes(request, MAX_PROXY_BYTES);
|
|
2004
1545
|
if (!body) {
|
|
2005
|
-
|
|
1546
|
+
tooLarge(response);
|
|
2006
1547
|
return;
|
|
2007
1548
|
}
|
|
2008
|
-
const
|
|
2009
|
-
|
|
2010
|
-
if (
|
|
2011
|
-
|
|
2012
|
-
|
|
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 {}
|
|
2013
1925
|
}
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
1926
|
+
}
|
|
1927
|
+
/** Drop what is past retention, then the oldest beyond the size cap. */
|
|
1928
|
+
prune(now = Date.now()) {
|
|
1929
|
+
if (this.#closed) return;
|
|
2017
1930
|
try {
|
|
2018
|
-
const
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
const returned = {};
|
|
2025
|
-
upstream.headers.forEach((value, name) => {
|
|
2026
|
-
if (!NOT_RETURNED.has(name)) returned[name] = value;
|
|
2027
|
-
});
|
|
2028
|
-
send(response, upstream.status, new Uint8Array(await upstream.arrayBuffer()), returned);
|
|
2029
|
-
} catch {
|
|
2030
|
-
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);
|
|
2031
1937
|
}
|
|
2032
1938
|
}
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
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)
|
|
2043
1952
|
};
|
|
2044
|
-
write(`event: snapshot\ndata: ${JSON.stringify(snapshot())}\n\n`);
|
|
2045
|
-
const unsubscribe = options.store.subscribe((event) => write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`));
|
|
2046
|
-
const unwatch = extension?.onChange(() => write(`event: extension\ndata: ${JSON.stringify(snapshot().extension)}\n\n`));
|
|
2047
|
-
const keepalive = setInterval(() => write(": keepalive\n\n"), KEEPALIVE_MS);
|
|
2048
|
-
request.on("close", () => {
|
|
2049
|
-
clearInterval(keepalive);
|
|
2050
|
-
unsubscribe();
|
|
2051
|
-
unwatch?.();
|
|
2052
|
-
});
|
|
2053
1953
|
}
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
`localhost:${port}`,
|
|
2067
|
-
`[::1]:${port}`
|
|
2068
|
-
]);
|
|
2069
|
-
if (!production) extension?.watch();
|
|
2070
|
-
resolve({
|
|
2071
|
-
port,
|
|
2072
|
-
setPluginExtensions: (plugins) => extension?.setPlugins(plugins) ?? Promise.resolve(),
|
|
2073
|
-
stop() {
|
|
2074
|
-
extension?.close();
|
|
2075
|
-
server.close();
|
|
2076
|
-
server.closeAllConnections();
|
|
2077
|
-
}
|
|
2078
|
-
});
|
|
2079
|
-
});
|
|
2080
|
-
});
|
|
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
|
+
};
|
|
2081
1966
|
}
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
}
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
}
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
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);
|
|
2117
2005
|
}
|
|
2118
|
-
|
|
2119
|
-
} catch {
|
|
2120
|
-
send(response, 500, "History query failed");
|
|
2006
|
+
return result;
|
|
2121
2007
|
}
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
};
|
|
2128
|
-
function serveAsset(response, name) {
|
|
2129
|
-
if (!/^[\w.-]+$/.test(name) || name.startsWith(".")) {
|
|
2130
|
-
send(response, 404, "Not found");
|
|
2131
|
-
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));
|
|
2132
2014
|
}
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
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
|
+
};
|
|
2137
2024
|
}
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
}
|
|
2147
|
-
|
|
2148
|
-
|
|
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
|
+
};
|
|
2061
|
+
// src/dev-telemetry-store.ts
|
|
2149
2062
|
const LIMITS = {
|
|
2150
|
-
|
|
2151
|
-
spansPerTrace: 500
|
|
2152
|
-
failures: 200,
|
|
2153
|
-
reloads: 100
|
|
2063
|
+
...LIVE_LIMITS,
|
|
2064
|
+
spansPerTrace: 500
|
|
2154
2065
|
};
|
|
2155
2066
|
const WORKER_FAILURE_CODES = {
|
|
2156
2067
|
startup: "STARTUP_FAILED",
|
|
@@ -2174,7 +2085,7 @@ var DevTelemetryStore = class {
|
|
|
2174
2085
|
#apiDocuments = [];
|
|
2175
2086
|
#sequence = 0;
|
|
2176
2087
|
#generation = 0;
|
|
2177
|
-
/** Finished requests
|
|
2088
|
+
/** Finished requests are also kept in `history`, when given. */
|
|
2178
2089
|
constructor(options = {}) {
|
|
2179
2090
|
this.#history = options.history;
|
|
2180
2091
|
}
|
|
@@ -2348,9 +2259,9 @@ var DevTelemetryStore = class {
|
|
|
2348
2259
|
if (!(record.parentSpanId !== void 0 && entry.spans.has(record.parentSpanId)) && entry.rootSpanId === void 0) {
|
|
2349
2260
|
entry.rootSpanId = record.spanId;
|
|
2350
2261
|
entry.name = record.name;
|
|
2351
|
-
entry.method = stringAttribute(record.attributes,
|
|
2352
|
-
entry.route = stringAttribute(record.attributes,
|
|
2353
|
-
entry.path = stringAttribute(record.attributes,
|
|
2262
|
+
entry.method = stringAttribute(record.attributes, ATTR.httpMethod);
|
|
2263
|
+
entry.route = stringAttribute(record.attributes, ATTR.httpRoute);
|
|
2264
|
+
entry.path = stringAttribute(record.attributes, ATTR.urlPath);
|
|
2354
2265
|
}
|
|
2355
2266
|
if (entry.spans.size >= LIMITS.spansPerTrace) {
|
|
2356
2267
|
entry.truncated = true;
|
|
@@ -2388,38 +2299,40 @@ var DevTelemetryStore = class {
|
|
|
2388
2299
|
...record.attributes
|
|
2389
2300
|
};
|
|
2390
2301
|
span.events = record.events;
|
|
2391
|
-
const code = stringAttribute(record.attributes,
|
|
2302
|
+
const code = stringAttribute(record.attributes, ATTR.errorCode);
|
|
2392
2303
|
if (code !== void 0) {
|
|
2393
2304
|
const exception = findException(record.events);
|
|
2394
2305
|
this.#pushFailure({
|
|
2395
2306
|
phase: "request",
|
|
2396
2307
|
code,
|
|
2397
|
-
message: stringAttribute(exception,
|
|
2398
|
-
status: numberAttribute(record.attributes,
|
|
2399
|
-
stack: stringAttribute(exception,
|
|
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),
|
|
2400
2311
|
traceId: entry.traceId,
|
|
2401
2312
|
route: entry.route,
|
|
2402
|
-
service: stringAttribute(record.attributes,
|
|
2403
|
-
action: stringAttribute(record.attributes,
|
|
2313
|
+
service: stringAttribute(record.attributes, ATTR.service),
|
|
2314
|
+
action: stringAttribute(record.attributes, ATTR.action),
|
|
2404
2315
|
generation: entry.generation
|
|
2405
2316
|
});
|
|
2406
2317
|
entry.failureRecorded = true;
|
|
2407
2318
|
}
|
|
2408
2319
|
if (record.spanId !== entry.rootSpanId) return;
|
|
2409
2320
|
entry.endMs = record.endMs;
|
|
2410
|
-
entry.httpStatus = numberAttribute(record.attributes,
|
|
2321
|
+
entry.httpStatus = numberAttribute(record.attributes, ATTR.httpStatus);
|
|
2411
2322
|
const status = entry.httpStatus ?? 0;
|
|
2412
|
-
const
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
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) {
|
|
2416
2329
|
const exception = findException(record.events);
|
|
2417
2330
|
this.#pushFailure({
|
|
2418
2331
|
phase: "request",
|
|
2419
2332
|
code: status >= 400 ? `HTTP_${status}` : "UNHANDLED_ERROR",
|
|
2420
|
-
message: stringAttribute(exception,
|
|
2333
|
+
message: stringAttribute(exception, ATTR.exceptionMessage) ?? record.statusMessage ?? describeResponse(entry, status),
|
|
2421
2334
|
status: entry.httpStatus,
|
|
2422
|
-
stack: stringAttribute(exception,
|
|
2335
|
+
stack: stringAttribute(exception, ATTR.exceptionStack),
|
|
2423
2336
|
traceId: entry.traceId,
|
|
2424
2337
|
route: entry.route,
|
|
2425
2338
|
generation: entry.generation
|
|
@@ -2445,14 +2358,15 @@ var DevTelemetryStore = class {
|
|
|
2445
2358
|
#emit(event) {
|
|
2446
2359
|
for (const listener of this.#listeners) try {
|
|
2447
2360
|
listener(event);
|
|
2448
|
-
} catch {
|
|
2361
|
+
} catch (error) {
|
|
2449
2362
|
this.#listeners.delete(listener);
|
|
2363
|
+
console.warn("[Brick-TS] A dashboard client stopped receiving updates:", error);
|
|
2450
2364
|
}
|
|
2451
2365
|
}
|
|
2452
2366
|
};
|
|
2453
2367
|
function summarize(entry) {
|
|
2454
2368
|
const spans = [...entry.spans.values()].sort((a, b) => a.startMs - b.startMs);
|
|
2455
|
-
const
|
|
2369
|
+
const action = actionSpan(spans);
|
|
2456
2370
|
return {
|
|
2457
2371
|
traceId: entry.traceId,
|
|
2458
2372
|
name: entry.name || spans[0]?.name || entry.traceId,
|
|
@@ -2466,10 +2380,9 @@ function summarize(entry) {
|
|
|
2466
2380
|
durationMs: entry.endMs === void 0 ? void 0 : entry.endMs - entry.startMs,
|
|
2467
2381
|
status: entry.status,
|
|
2468
2382
|
truncated: entry.truncated,
|
|
2469
|
-
service: stringAttribute(
|
|
2470
|
-
action: stringAttribute(
|
|
2383
|
+
service: stringAttribute(action?.attributes, ATTR.service),
|
|
2384
|
+
action: stringAttribute(action?.attributes, ATTR.action),
|
|
2471
2385
|
message: entry.message,
|
|
2472
|
-
...entry.spans.get(entry.rootSpanId ?? "")?.attributes["brick.legacy_route"] === true ? { legacyRoute: true } : {},
|
|
2473
2386
|
spans
|
|
2474
2387
|
};
|
|
2475
2388
|
}
|
|
@@ -2478,18 +2391,54 @@ function describeResponse(entry, status) {
|
|
|
2478
2391
|
const request = entry.method ? `${entry.method} ${target}` : target;
|
|
2479
2392
|
return status ? `${request} returned ${status}` : request;
|
|
2480
2393
|
}
|
|
2481
|
-
function findException(events) {
|
|
2482
|
-
return events.find((event) => event.name === "exception")?.attributes;
|
|
2483
|
-
}
|
|
2484
|
-
function stringAttribute(attributes, key) {
|
|
2485
|
-
const value = attributes?.[key];
|
|
2486
|
-
return typeof value === "string" ? value : void 0;
|
|
2487
|
-
}
|
|
2488
2394
|
function numberAttribute(attributes, key) {
|
|
2489
2395
|
const value = attributes?.[key];
|
|
2490
2396
|
return typeof value === "number" ? value : void 0;
|
|
2491
2397
|
}
|
|
2492
|
-
|
|
2493
|
-
|
|
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 };
|
|
2494
2443
|
|
|
2495
|
-
//# sourceMappingURL=
|
|
2444
|
+
//# sourceMappingURL=dashboard-host.js.map
|