@brickkit/cli 0.7.4 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +173 -1
  2. package/dashboard-dist/CollapsiblePanel-DM8J3g8m.js +2 -0
  3. package/dashboard-dist/Geist-Variable.woff2 +0 -0
  4. package/dashboard-dist/GeistMono-Variable.woff2 +0 -0
  5. package/dashboard-dist/PopoverPopup-B6eMOlOC.js +1 -0
  6. package/dashboard-dist/api-reference-wTdT1AVt.js +260 -0
  7. package/dashboard-dist/app.css +2 -0
  8. package/dashboard-dist/app.js +18 -0
  9. package/dashboard-dist/core-CHWYtApw.js +1 -0
  10. package/dashboard-dist/docs-DflzpIIh.js +4 -0
  11. package/dashboard-dist/docs.css +1 -0
  12. package/dashboard-dist/preload-helper-CVJ-D494.js +1 -0
  13. package/dashboard-dist/react-jsx-runtime.js +4 -0
  14. package/dashboard-dist/react.js +3 -0
  15. package/dashboard-dist/rolldown-runtime-XKyaHtl9.js +1 -0
  16. package/dist/bin.d.ts.map +1 -1
  17. package/dist/bin.js +17 -6
  18. package/dist/bin.js.map +1 -1
  19. package/dist/dev-reporter.d.ts +15 -0
  20. package/dist/dev-reporter.d.ts.map +1 -0
  21. package/dist/dev-reporter.js +28 -0
  22. package/dist/dev-reporter.js.map +1 -0
  23. package/dist/dev-telemetry-store.js +1897 -0
  24. package/dist/dev-telemetry-store.js.map +1 -0
  25. package/dist/dev-telemetry.js +199 -0
  26. package/dist/dev-telemetry.js.map +1 -0
  27. package/dist/dev-worker.js +54 -9
  28. package/dist/dev-worker.js.map +1 -1
  29. package/dist/index.d.ts +24 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/runner.js +157 -8
  32. package/dist/runner.js.map +1 -1
  33. package/dist/vite.d.ts +11 -0
  34. package/dist/vite.d.ts.map +1 -1
  35. package/dist/vite.js +104 -6
  36. package/dist/vite.js.map +1 -1
  37. package/package.json +42 -4
  38. package/dist/port-utils.js +0 -13
  39. package/dist/port-utils.js.map +0 -1
@@ -0,0 +1,1897 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { existsSync, mkdirSync, watch, writeFileSync } from "node:fs";
3
+ import { readFile, readdir, stat } from "node:fs/promises";
4
+ import { createServer } from "node:http";
5
+ import { basename, dirname, extname, join, posix, relative, resolve, sep } from "node:path";
6
+ import { createHash, timingSafeEqual } from "node:crypto";
7
+ //#region src/dev-history-csv.ts
8
+ const CSV_COLUMNS = [
9
+ "time",
10
+ "method",
11
+ "route",
12
+ "path",
13
+ "status",
14
+ "outcome",
15
+ "duration_ms",
16
+ "service",
17
+ "action",
18
+ "message",
19
+ "trace_id"
20
+ ];
21
+ function csvCell(value) {
22
+ if (value === void 0) return "";
23
+ const text = String(value);
24
+ const safe = /^[=+\-@\t\r]/.test(text) ? `'${text}` : text;
25
+ return /[",\n\r]/.test(safe) ? `"${safe.replace(/"/g, "\"\"")}"` : safe;
26
+ }
27
+ /** Requests as CSV with a header row, for the dashboard's export. */
28
+ function tracesToCsv(traces) {
29
+ const lines = traces.map((trace) => {
30
+ const failed = trace.status === "error" || (trace.httpStatus ?? 0) >= 500;
31
+ const client = (trace.httpStatus ?? 0) >= 400;
32
+ return [
33
+ new Date(trace.startMs).toISOString(),
34
+ trace.method,
35
+ trace.route,
36
+ trace.path,
37
+ trace.httpStatus ?? trace.status,
38
+ failed ? "server" : client ? "client" : "ok",
39
+ trace.durationMs === void 0 ? void 0 : trace.durationMs.toFixed(3),
40
+ trace.service,
41
+ trace.action,
42
+ trace.message,
43
+ trace.traceId
44
+ ].map(csvCell).join(",");
45
+ });
46
+ return [CSV_COLUMNS.join(","), ...lines].join("\n") + "\n";
47
+ }
48
+ //#endregion
49
+ //#region src/dev-history.ts
50
+ const DAY_MS = 864e5;
51
+ const MAX_TRACES = 1e5;
52
+ const FLUSH_MS = 250;
53
+ const PRUNE_MS = 18e5;
54
+ const VOLUME_BUCKETS = 48;
55
+ const DEFAULT_LIMIT = 100;
56
+ const MAX_LIMIT = 500;
57
+ const MAX_FACET_VALUES = 30;
58
+ const MAX_EXPORT_ROWS = 1e5;
59
+ const OUTCOMES = /* @__PURE__ */ new Set([
60
+ "ok",
61
+ "client",
62
+ "server"
63
+ ]);
64
+ /**
65
+ * SQLite from whichever runtime is running: `bun:sqlite` under Bun, and
66
+ * `node:sqlite` under Node, which is what runs Vite's dev server. Both are
67
+ * imported by a variable name so bundlers leave them alone.
68
+ */
69
+ async function openDatabase(file) {
70
+ if (typeof Bun !== "undefined") {
71
+ const { Database } = await import("bun:sqlite");
72
+ return new Database(file, { create: true });
73
+ }
74
+ const specifier = "node:sqlite";
75
+ const emit = process.emitWarning;
76
+ process.emitWarning = ((warning, ...rest) => {
77
+ if (typeof warning === "string" && warning.includes("SQLite")) return;
78
+ return emit.call(process, warning, ...rest);
79
+ });
80
+ try {
81
+ const { DatabaseSync } = await import(specifier);
82
+ return new DatabaseSync(file);
83
+ } finally {
84
+ process.emitWarning = emit;
85
+ }
86
+ }
87
+ /**
88
+ * Open the request history, or return undefined when it is turned off or this
89
+ * runtime has no SQLite. Never throws: the dashboard works without history.
90
+ */
91
+ async function openHistory(options) {
92
+ if (!(options.days > 0)) return void 0;
93
+ try {
94
+ const folder = join(options.directory, ".brick");
95
+ mkdirSync(folder, { recursive: true });
96
+ const ignore = join(folder, ".gitignore");
97
+ if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
98
+ return new DevHistory(await openDatabase(join(folder, "telemetry.sqlite")), options.days);
99
+ } catch (error) {
100
+ const reason = error instanceof Error ? error.message : String(error);
101
+ options.warn?.(`[Brick-TS] Request history is unavailable (${reason}). It needs Bun, or Node 22.5 or later. Continuing without it.`);
102
+ return;
103
+ }
104
+ }
105
+ const text = (value) => value === null || value === void 0 ? void 0 : String(value);
106
+ const number = (value) => value === null || value === void 0 ? void 0 : Number(value);
107
+ function percentile(sorted, fraction) {
108
+ if (sorted.length === 0) return 0;
109
+ const position = (sorted.length - 1) * fraction;
110
+ const lower = Math.floor(position);
111
+ const upper = Math.ceil(position);
112
+ return sorted[lower] + (sorted[upper] - sorted[lower]) * (position - lower);
113
+ }
114
+ const OUTCOME_SQL = {
115
+ server: "(status = 'error' OR http_status >= 500)",
116
+ client: "(status != 'error' AND http_status >= 400 AND http_status < 500)",
117
+ ok: "(status != 'error' AND (http_status IS NULL OR http_status < 400))"
118
+ };
119
+ /** The outcome of each row, for counting; agrees with OUTCOME_SQL. */
120
+ const OUTCOME_CASE = `CASE
121
+ WHEN status = 'error' OR http_status >= 500 THEN 'server'
122
+ WHEN http_status >= 400 AND http_status < 500 THEN 'client'
123
+ ELSE 'ok' END`;
124
+ const FACET_COLUMNS = {
125
+ outcome: OUTCOME_CASE,
126
+ method: "method",
127
+ service: "service",
128
+ endpoint: "endpoint"
129
+ };
130
+ /** The WHERE clause for a query, leaving out one filter when counting its facet. */
131
+ function filterSql(query, skip) {
132
+ const clauses = ["start_ms >= ?", "start_ms <= ?"];
133
+ const params = [query.from, query.to];
134
+ const anyOf = (column, values) => {
135
+ if (!values || values.length === 0) return;
136
+ clauses.push(`${column} IN (${values.map(() => "?").join(", ")})`);
137
+ params.push(...values);
138
+ };
139
+ if (skip !== "endpoint") anyOf("endpoint", query.endpoints);
140
+ if (skip !== "method") anyOf("method", query.methods);
141
+ if (skip !== "service") anyOf("service", query.services);
142
+ if (skip !== "outcome" && query.outcomes && query.outcomes.length > 0) clauses.push(`(${query.outcomes.map((outcome) => OUTCOME_SQL[outcome]).join(" OR ")})`);
143
+ if (query.minMs !== void 0 && query.minMs > 0) {
144
+ clauses.push("duration_ms >= ?");
145
+ params.push(query.minMs);
146
+ }
147
+ const needle = query.query?.trim();
148
+ if (needle) {
149
+ const pattern = `%${needle.replace(/[\\%_]/g, "\\$&")}%`;
150
+ clauses.push("(endpoint LIKE ? ESCAPE '\\' OR path LIKE ? ESCAPE '\\' OR name LIKE ? ESCAPE '\\' OR action LIKE ? ESCAPE '\\' OR message LIKE ? ESCAPE '\\')");
151
+ params.push(pattern, pattern, pattern, pattern, pattern);
152
+ }
153
+ return {
154
+ sql: clauses.join(" AND "),
155
+ params
156
+ };
157
+ }
158
+ const LIST_COLUMNS = `trace_id, name, endpoint, method, route, path, http_status, generation,
159
+ start_ms, end_ms, duration_ms, status, truncated, service, action, message`;
160
+ function toHistoryTrace(row) {
161
+ return {
162
+ traceId: String(row.trace_id),
163
+ name: String(row.name),
164
+ endpoint: String(row.endpoint),
165
+ method: text(row.method),
166
+ route: text(row.route),
167
+ path: text(row.path),
168
+ httpStatus: number(row.http_status),
169
+ generation: Number(row.generation),
170
+ startMs: Number(row.start_ms),
171
+ endMs: number(row.end_ms),
172
+ durationMs: number(row.duration_ms),
173
+ status: String(row.status),
174
+ truncated: Number(row.truncated) === 1,
175
+ service: text(row.service),
176
+ action: text(row.action),
177
+ message: text(row.message)
178
+ };
179
+ }
180
+ /**
181
+ * Requests kept on disk between runs, for looking back over weeks
182
+ * instead of the last few minutes. Writes are batched; reads see them.
183
+ */
184
+ var DevHistory = class {
185
+ days;
186
+ #database;
187
+ #pendingTraces = /* @__PURE__ */ new Map();
188
+ #flushTimer;
189
+ #pruneTimer;
190
+ #closed = false;
191
+ constructor(database, days) {
192
+ this.#database = database;
193
+ this.days = days;
194
+ database.exec(`
195
+ PRAGMA journal_mode = WAL;
196
+ PRAGMA synchronous = NORMAL;
197
+ PRAGMA busy_timeout = 2000;
198
+ CREATE TABLE IF NOT EXISTS traces (
199
+ trace_id TEXT PRIMARY KEY,
200
+ name TEXT NOT NULL,
201
+ endpoint TEXT NOT NULL,
202
+ method TEXT,
203
+ route TEXT,
204
+ path TEXT,
205
+ http_status INTEGER,
206
+ generation INTEGER NOT NULL,
207
+ start_ms INTEGER NOT NULL,
208
+ end_ms INTEGER,
209
+ duration_ms REAL,
210
+ status TEXT NOT NULL,
211
+ truncated INTEGER NOT NULL,
212
+ spans TEXT NOT NULL,
213
+ service TEXT,
214
+ action TEXT,
215
+ message TEXT
216
+ );
217
+ CREATE INDEX IF NOT EXISTS traces_start ON traces (start_ms);
218
+ CREATE INDEX IF NOT EXISTS traces_endpoint ON traces (endpoint, start_ms);
219
+ -- Earlier versions kept failures here; nothing reads them now.
220
+ DROP TABLE IF EXISTS failures;
221
+ `);
222
+ this.#addMissingColumns();
223
+ this.prune();
224
+ this.#pruneTimer = setInterval(() => this.prune(), PRUNE_MS);
225
+ this.#pruneTimer.unref?.();
226
+ }
227
+ /** A folder from an earlier version has the table without the newer columns. */
228
+ #addMissingColumns() {
229
+ const present = new Set(this.#database.prepare("PRAGMA table_info(traces)").all().map((column) => String(column.name)));
230
+ for (const column of [
231
+ "service",
232
+ "action",
233
+ "message"
234
+ ]) if (!present.has(column)) this.#database.exec(`ALTER TABLE traces ADD COLUMN ${column} TEXT`);
235
+ }
236
+ /** Queue a finished request. A later save of the same request replaces it. */
237
+ saveTrace(trace) {
238
+ if (this.#closed) return;
239
+ this.#pendingTraces.set(trace.traceId, trace);
240
+ this.#scheduleFlush();
241
+ }
242
+ #scheduleFlush() {
243
+ if (this.#flushTimer) return;
244
+ this.#flushTimer = setTimeout(() => this.flush(), FLUSH_MS);
245
+ this.#flushTimer.unref?.();
246
+ }
247
+ /** Write queued requests now. */
248
+ flush() {
249
+ if (this.#flushTimer) {
250
+ clearTimeout(this.#flushTimer);
251
+ this.#flushTimer = void 0;
252
+ }
253
+ if (this.#closed || this.#pendingTraces.size === 0) return;
254
+ const traces = [...this.#pendingTraces.values()];
255
+ this.#pendingTraces.clear();
256
+ try {
257
+ this.#database.exec("BEGIN");
258
+ const saveTrace = this.#database.prepare(`INSERT OR REPLACE INTO traces (trace_id, name, endpoint, method, route, path,
259
+ http_status, generation, start_ms, end_ms, duration_ms, status, truncated, spans,
260
+ service, action, message)
261
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
262
+ 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);
263
+ this.#database.exec("COMMIT");
264
+ } catch {
265
+ try {
266
+ this.#database.exec("ROLLBACK");
267
+ } catch {}
268
+ }
269
+ }
270
+ /** Drop what is past retention, then the oldest beyond the size cap. */
271
+ prune(now = Date.now()) {
272
+ if (this.#closed) return;
273
+ try {
274
+ const cutoff = now - this.days * DAY_MS;
275
+ this.#database.prepare("DELETE FROM traces WHERE start_ms < ?").run(cutoff);
276
+ const count = Number(this.#database.prepare("SELECT COUNT(*) AS n FROM traces").get()?.n ?? 0);
277
+ 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);
278
+ } catch {}
279
+ }
280
+ info() {
281
+ this.flush();
282
+ const row = this.#database.prepare("SELECT COUNT(*) AS n, MIN(start_ms) AS oldest FROM traces").get();
283
+ return {
284
+ days: this.days,
285
+ count: Number(row?.n ?? 0),
286
+ oldestMs: number(row?.oldest)
287
+ };
288
+ }
289
+ /** Matching requests, without spans, and how many match in total. */
290
+ traces(query) {
291
+ this.flush();
292
+ const { sql, params } = filterSql(query);
293
+ const total = Number(this.#database.prepare(`SELECT COUNT(*) AS n FROM traces WHERE ${sql}`).get(...params)?.n ?? 0);
294
+ const limit = Math.min(Math.max(query.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);
295
+ const offset = Math.max(query.offset ?? 0, 0);
296
+ const order = query.sort === "slowest" ? "duration_ms DESC, start_ms DESC" : "start_ms DESC";
297
+ return {
298
+ total,
299
+ traces: this.#database.prepare(`SELECT ${LIST_COLUMNS}
300
+ FROM traces WHERE ${sql} ORDER BY ${order} LIMIT ? OFFSET ?`).all(...params, limit, offset).map(toHistoryTrace)
301
+ };
302
+ }
303
+ /** Counts for each filter over the range, ignoring that filter's own choice. */
304
+ facets(query) {
305
+ this.flush();
306
+ const count = (facet) => {
307
+ const { sql, params } = filterSql(query, facet);
308
+ const column = FACET_COLUMNS[facet];
309
+ return this.#database.prepare(`SELECT ${column} AS value, COUNT(*) AS n FROM traces
310
+ WHERE ${sql} AND ${column} IS NOT NULL
311
+ GROUP BY value ORDER BY n DESC, value ASC LIMIT ?`).all(...params, MAX_FACET_VALUES).map((row) => ({
312
+ value: String(row.value),
313
+ count: Number(row.n)
314
+ }));
315
+ };
316
+ return {
317
+ outcome: count("outcome"),
318
+ method: count("method"),
319
+ service: count("service"),
320
+ endpoint: count("endpoint")
321
+ };
322
+ }
323
+ /** Matching requests per time bucket across the range, by outcome. */
324
+ volume(query, buckets = VOLUME_BUCKETS) {
325
+ this.flush();
326
+ const { sql, params } = filterSql(query);
327
+ const bucketMs = Math.max(Math.ceil((query.to - query.from) / buckets), 1);
328
+ const result = Array.from({ length: buckets }, (_, index) => ({
329
+ start: query.from + index * bucketMs,
330
+ ok: 0,
331
+ client: 0,
332
+ server: 0
333
+ }));
334
+ const rows = this.#database.prepare(`SELECT CAST((start_ms - ?) / ? AS INTEGER) AS bucket, ${OUTCOME_CASE} AS outcome,
335
+ COUNT(*) AS n
336
+ FROM traces WHERE ${sql} GROUP BY bucket, outcome`).all(query.from, bucketMs, ...params);
337
+ for (const row of rows) {
338
+ const bucket = result[Math.min(Math.max(Number(row.bucket), 0), buckets - 1)];
339
+ const outcome = String(row.outcome);
340
+ if (bucket) bucket[outcome] += Number(row.n);
341
+ }
342
+ return result;
343
+ }
344
+ /** Every matching request, newest first, as CSV for a spreadsheet. */
345
+ exportCsv(query) {
346
+ this.flush();
347
+ const { sql, params } = filterSql(query);
348
+ const order = query.sort === "slowest" ? "duration_ms DESC, start_ms DESC" : "start_ms DESC";
349
+ return tracesToCsv(this.#database.prepare(`SELECT ${LIST_COLUMNS}
350
+ FROM traces WHERE ${sql} ORDER BY ${order} LIMIT ?`).all(...params, MAX_EXPORT_ROWS).map(toHistoryTrace));
351
+ }
352
+ /** One request with all its spans. */
353
+ trace(traceId) {
354
+ this.flush();
355
+ const row = this.#database.prepare(`SELECT ${LIST_COLUMNS}, spans FROM traces WHERE trace_id = ?`).get(traceId);
356
+ if (!row) return void 0;
357
+ const { endpoint: _endpoint, ...trace } = toHistoryTrace(row);
358
+ return {
359
+ ...trace,
360
+ spans: JSON.parse(String(row.spans))
361
+ };
362
+ }
363
+ /** How many requests match, how many failed, and how long they took. */
364
+ summary(query) {
365
+ this.flush();
366
+ const { sql, params } = filterSql(query);
367
+ let total = 0;
368
+ let clientErrors = 0;
369
+ let serverErrors = 0;
370
+ const counts = this.#database.prepare(`SELECT ${OUTCOME_CASE} AS outcome, COUNT(*) AS n
371
+ FROM traces WHERE ${sql} GROUP BY outcome`).all(...params);
372
+ for (const row of counts) {
373
+ const n = Number(row.n);
374
+ total += n;
375
+ if (row.outcome === "client") clientErrors = n;
376
+ if (row.outcome === "server") serverErrors = n;
377
+ }
378
+ const durations = this.#database.prepare(`SELECT duration_ms FROM traces
379
+ WHERE ${sql} AND duration_ms IS NOT NULL ORDER BY duration_ms`).all(...params).map((row) => Number(row.duration_ms));
380
+ return {
381
+ total,
382
+ clientErrors,
383
+ serverErrors,
384
+ medianMs: percentile(durations, .5),
385
+ p95Ms: percentile(durations, .95)
386
+ };
387
+ }
388
+ /** Write what is queued and release the database. */
389
+ close() {
390
+ if (this.#closed) return;
391
+ this.flush();
392
+ this.#closed = true;
393
+ clearInterval(this.#pruneTimer);
394
+ try {
395
+ this.#database.close();
396
+ } catch {}
397
+ }
398
+ };
399
+ /** Query-string values the dashboard sends, parsed defensively. */
400
+ function parseHistoryQuery(params, now = Date.now()) {
401
+ const integer = (name) => {
402
+ const raw = params.get(name);
403
+ if (raw === null || raw.trim() === "") return void 0;
404
+ const value = Number(raw);
405
+ return Number.isFinite(value) ? value : void 0;
406
+ };
407
+ const all = (name) => {
408
+ const values = params.getAll(name).filter((value) => value !== "");
409
+ return values.length > 0 ? values : void 0;
410
+ };
411
+ const to = integer("to") ?? now;
412
+ return {
413
+ to,
414
+ from: integer("from") ?? to - 7 * DAY_MS,
415
+ endpoints: all("endpoint"),
416
+ methods: all("method"),
417
+ services: all("service"),
418
+ outcomes: all("outcome")?.filter((value) => OUTCOMES.has(value)),
419
+ minMs: integer("minMs"),
420
+ query: params.get("q") || void 0,
421
+ sort: params.get("sort") === "slowest" ? "slowest" : "recent",
422
+ limit: integer("limit"),
423
+ offset: integer("offset")
424
+ };
425
+ }
426
+ //#endregion
427
+ //#region src/dev-dashboard-shell.ts
428
+ /**
429
+ * The page the dashboard serves at `/`. The React app and its styles load from
430
+ * `/assets/`; the inline script applies the saved theme before first paint. The
431
+ * import map lets the project's own docs components, bundled apart from the
432
+ * dashboard, share its copy of React.
433
+ */
434
+ const DEV_DASHBOARD_SHELL = `<!doctype html>
435
+ <html lang="en">
436
+ <head>
437
+ <meta charset="utf-8">
438
+ <meta name="viewport" content="width=device-width, initial-scale=1">
439
+ <title>Brick dev</title>
440
+ <link rel="icon" href="data:,">
441
+ <script>
442
+ (function () {
443
+ try {
444
+ var theme = localStorage.getItem("brick-dashboard-theme");
445
+ var dark = theme === "dark" || (theme !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches);
446
+ if (dark) document.documentElement.classList.add("dark");
447
+ } catch (error) {}
448
+ })();
449
+ <\/script>
450
+ <link rel="stylesheet" href="/assets/app.css">
451
+ <script type="importmap">
452
+ {"imports":{"react":"/assets/react.js","react/jsx-runtime":"/assets/react-jsx-runtime.js","react/jsx-dev-runtime":"/assets/react-jsx-runtime.js"}}
453
+ <\/script>
454
+ </head>
455
+ <body>
456
+ <div id="root"></div>
457
+ <script type="module" src="/assets/app.js"><\/script>
458
+ </body>
459
+ </html>
460
+ `;
461
+ //#endregion
462
+ //#region src/dashboard-access.ts
463
+ /** How long the app's `authorize` may take before the request is refused. */
464
+ const AUTHORIZE_TIMEOUT_MS = 5e3;
465
+ /** Whether `host` can only be reached from the machine it runs on. */
466
+ function isLoopbackHost(host) {
467
+ const name = host.toLowerCase();
468
+ return name === "localhost" || name === "::1" || name === "[::1]" || /^127(\.\d{1,3}){3}$/.test(name);
469
+ }
470
+ const NOT_COPIED = /* @__PURE__ */ new Set([
471
+ "set-cookie",
472
+ "content-length",
473
+ "content-encoding",
474
+ "transfer-encoding",
475
+ "connection",
476
+ "keep-alive"
477
+ ]);
478
+ const digest = (value) => createHash("sha256").update(value).digest();
479
+ /** Whether `candidate` is one of `tokens`, in the same time whichever it is. */
480
+ function isToken(candidate, tokens) {
481
+ if (candidate === void 0) return false;
482
+ const given = digest(candidate);
483
+ let match = false;
484
+ for (const token of tokens) if (timingSafeEqual(given, digest(token))) match = true;
485
+ return match;
486
+ }
487
+ /** The secret in an `Authorization` header: a Bearer token, or a Basic password. */
488
+ function credential(request) {
489
+ const header = request.headers.authorization;
490
+ if (!header) return void 0;
491
+ const space = header.indexOf(" ");
492
+ if (space < 0) return void 0;
493
+ const scheme = header.slice(0, space).toLowerCase();
494
+ const value = header.slice(space + 1).trim();
495
+ if (scheme === "bearer") return value;
496
+ if (scheme === "basic") {
497
+ const decoded = Buffer.from(value, "base64").toString("utf8");
498
+ const colon = decoded.indexOf(":");
499
+ return colon < 0 ? void 0 : decoded.slice(colon + 1);
500
+ }
501
+ }
502
+ /** The request as the app's `authorize` sees it: standard, with no body. */
503
+ function webRequest(request) {
504
+ const headers = new Headers();
505
+ for (const [name, value] of Object.entries(request.headers)) {
506
+ if (value === void 0) continue;
507
+ try {
508
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
509
+ } catch {}
510
+ }
511
+ const forwarded = request.headers["x-forwarded-proto"];
512
+ const protocol = (Array.isArray(forwarded) ? forwarded[0] : forwarded)?.split(",")[0]?.trim() === "https" ? "https" : "http";
513
+ const host = request.headers.host ?? "localhost";
514
+ let url;
515
+ try {
516
+ url = new URL(request.url ?? "/", `${protocol}://${host}`).href;
517
+ } catch {
518
+ url = `${protocol}://localhost${request.url ?? "/"}`;
519
+ }
520
+ return new Request(url, {
521
+ method: request.method ?? "GET",
522
+ headers
523
+ });
524
+ }
525
+ const refusal = (status, body, headers = {}) => ({
526
+ allowed: false,
527
+ status,
528
+ body,
529
+ headers: {
530
+ "content-type": "text/plain; charset=utf-8",
531
+ ...headers
532
+ }
533
+ });
534
+ /**
535
+ * The check for the dashboard's requests. A request passes with a valid token,
536
+ * or when the app's `authorize` returns `true`. Anything else is answered:
537
+ * what `authorize` returned if it returned a `Response`, else 401 (with a
538
+ * browser sign-in prompt when tokens are in use), and 503 when `authorize`
539
+ * threw or ran out of time, since a check that cannot answer must not let
540
+ * anyone in.
541
+ */
542
+ function createAccess(auth, onError = () => {}, timeoutMs = AUTHORIZE_TIMEOUT_MS) {
543
+ const tokens = auth.token === void 0 ? [] : typeof auth.token === "string" ? [auth.token] : [...auth.token];
544
+ const prompt = tokens.length > 0 ? { "www-authenticate": "Basic realm=\"Brick dashboard\", charset=\"UTF-8\"" } : {};
545
+ return async (request) => {
546
+ if (tokens.length > 0 && isToken(credential(request), tokens)) return { allowed: true };
547
+ if (!auth.authorize) return refusal(401, "Unauthorized", prompt);
548
+ let decision;
549
+ let timer;
550
+ try {
551
+ decision = await Promise.race([Promise.resolve(auth.authorize(webRequest(request))), new Promise((_, reject) => {
552
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error("dashboard authorize timed out")), timeoutMs);
553
+ })]);
554
+ } catch (error) {
555
+ onError(error);
556
+ return refusal(503, "Sign-in is unavailable.");
557
+ } finally {
558
+ clearTimeout(timer);
559
+ }
560
+ if (decision === true) return { allowed: true };
561
+ if (decision instanceof Response) {
562
+ const headers = {};
563
+ decision.headers.forEach((value, name) => {
564
+ if (!NOT_COPIED.has(name)) headers[name] = value;
565
+ });
566
+ const cookies = decision.headers.getSetCookie();
567
+ if (cookies.length > 0) headers["set-cookie"] = cookies;
568
+ return {
569
+ allowed: false,
570
+ status: decision.status,
571
+ headers,
572
+ body: new Uint8Array(await decision.arrayBuffer())
573
+ };
574
+ }
575
+ return refusal(401, "Unauthorized", prompt);
576
+ };
577
+ }
578
+ //#endregion
579
+ //#region src/dev-dashboard.ts
580
+ const DEFAULT_DASHBOARD_PORT = 9400;
581
+ const KEEPALIVE_MS = 15e3;
582
+ const MAX_INGEST_BYTES = 5242880;
583
+ const MAX_PROXY_BYTES = 10485760;
584
+ const NOT_FORWARDED = /* @__PURE__ */ new Set([
585
+ "host",
586
+ "connection",
587
+ "keep-alive",
588
+ "proxy-connection",
589
+ "transfer-encoding",
590
+ "te",
591
+ "trailer",
592
+ "upgrade",
593
+ "content-length",
594
+ "accept-encoding",
595
+ "origin",
596
+ "referer",
597
+ "cookie"
598
+ ]);
599
+ const NOT_RETURNED = /* @__PURE__ */ new Set([
600
+ "connection",
601
+ "keep-alive",
602
+ "transfer-encoding",
603
+ "content-length",
604
+ "content-encoding",
605
+ "set-cookie"
606
+ ]);
607
+ /**
608
+ * What a production dashboard may show: the shell and its assets, the live
609
+ * state and its event stream, and stored history. Nothing that changes the app
610
+ * or reaches into it (restart, the API proxy, ingest) and nothing from the
611
+ * project's source (documentation, OpenAPI documents).
612
+ */
613
+ const isMonitoringRoute = (method, pathname) => method === "GET" && (pathname === "/" || pathname.startsWith("/assets/") || pathname === "/api/state" || pathname === "/api/events" || pathname.startsWith("/api/history"));
614
+ const PRODUCTION_HEADERS = {
615
+ "x-content-type-options": "nosniff",
616
+ "x-frame-options": "DENY",
617
+ "referrer-policy": "no-referrer",
618
+ "cross-origin-opener-policy": "same-origin",
619
+ "cross-origin-resource-policy": "same-origin",
620
+ "cache-control": "no-store",
621
+ "content-security-policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
622
+ };
623
+ /** How long `/_health` waits for the app before calling it down. */
624
+ const PROBE_TIMEOUT_MS = 3e3;
625
+ /**
626
+ * Serve the dashboard, on loopback unless told otherwise. On loopback requests
627
+ * must name a local host (blocks DNS rebinding), and restart requires a header
628
+ * that cross-origin pages cannot send without a preflight. Elsewhere `auth` is
629
+ * required and decides who gets in. Uses node:http, so it runs under Bun and
630
+ * under Node (Vite's dev server runs under Node).
631
+ */
632
+ function startDevDashboard(options) {
633
+ const host = options.host ?? "127.0.0.1";
634
+ const loopback = isLoopbackHost(host);
635
+ const production = options.mode === "production";
636
+ if (!loopback && !options.auth) return Promise.reject(/* @__PURE__ */ new Error(`Brick: the dashboard would listen on ${host}, where others can reach it, so it needs access control. Set dashboard.auth with a token or an authorize function.`));
637
+ const access = options.auth ? createAccess(options.auth, (error) => console.error("[Brick-TS] The dashboard sign-in check failed:", error)) : void 0;
638
+ let allowedHosts = /* @__PURE__ */ new Set();
639
+ const server = createServer((request, response) => {
640
+ respond(request, response).catch((error) => {
641
+ console.error("[Brick-TS] The dashboard failed to answer:", error);
642
+ if (response.headersSent) response.end();
643
+ else send(response, 500, "Server error");
644
+ });
645
+ });
646
+ async function respond(request, response) {
647
+ if (production) for (const [name, value] of Object.entries(PRODUCTION_HEADERS)) response.setHeader(name, value);
648
+ if (loopback && !allowedHosts.has(request.headers.host ?? "")) {
649
+ send(response, 403, "Forbidden");
650
+ return;
651
+ }
652
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
653
+ const { pathname } = url;
654
+ if (pathname === "/_health" && (request.method === "GET" || request.method === "HEAD")) {
655
+ await health(response);
656
+ return;
657
+ }
658
+ if (access) {
659
+ const decision = await access(request);
660
+ if (!decision.allowed) {
661
+ send(response, decision.status, decision.body, decision.headers);
662
+ return;
663
+ }
664
+ }
665
+ if (production && !isMonitoringRoute(request.method, pathname)) {
666
+ send(response, 404, "Not found");
667
+ return;
668
+ }
669
+ handle(request, response, url);
670
+ }
671
+ /** 200 while the app answers its own health check, 503 when it does not. */
672
+ async function health(response) {
673
+ const probe = options.probe;
674
+ let up = true;
675
+ if (probe) {
676
+ let timer;
677
+ up = await Promise.race([probe().catch(() => false), new Promise((resolve) => {
678
+ timer = setTimeout(() => resolve(false), PROBE_TIMEOUT_MS);
679
+ })]);
680
+ clearTimeout(timer);
681
+ }
682
+ send(response, up ? 200 : 503, JSON.stringify({
683
+ status: up ? "ok" : "degraded",
684
+ ...probe ? { app: up ? "up" : "down" } : {}
685
+ }), {
686
+ "content-type": "application/json",
687
+ "cache-control": "no-store"
688
+ });
689
+ }
690
+ function handle(request, response, url) {
691
+ const { pathname } = url;
692
+ if (request.method === "GET" && pathname === "/") {
693
+ send(response, 200, DEV_DASHBOARD_SHELL, {
694
+ "content-type": "text/html; charset=utf-8",
695
+ "cache-control": "no-store"
696
+ });
697
+ return;
698
+ }
699
+ if (request.method === "GET" && pathname.startsWith("/assets/")) {
700
+ serveAsset(response, pathname.slice(8));
701
+ return;
702
+ }
703
+ if (request.method === "GET" && pathname === "/api/state") {
704
+ send(response, 200, JSON.stringify(snapshot()), { "content-type": "application/json" });
705
+ return;
706
+ }
707
+ if (request.method === "GET" && pathname === "/api/events") {
708
+ eventStream(request, response);
709
+ return;
710
+ }
711
+ if (request.method === "GET" && pathname.startsWith("/api/history") && options.history) {
712
+ history(options.history, pathname, url.searchParams, response);
713
+ return;
714
+ }
715
+ if (request.method === "GET" && pathname.startsWith("/api/docs")) {
716
+ docsRoute(response, pathname, url.searchParams);
717
+ return;
718
+ }
719
+ if (request.method === "GET" && pathname === "/api/openapi") {
720
+ send(response, 200, JSON.stringify(options.store.apiDocuments()), {
721
+ "content-type": "application/json",
722
+ "cache-control": "no-store"
723
+ });
724
+ return;
725
+ }
726
+ if (pathname === "/api/proxy") {
727
+ proxy(request, response, url);
728
+ return;
729
+ }
730
+ if (request.method === "POST" && pathname === "/api/ingest") {
731
+ ingest(request, response);
732
+ return;
733
+ }
734
+ if (request.method === "POST" && pathname === "/api/restart" && options.restart) {
735
+ if (request.headers["x-brick-dashboard"] !== "1") {
736
+ send(response, 403, "Forbidden");
737
+ return;
738
+ }
739
+ options.restart();
740
+ send(response, 202, "");
741
+ return;
742
+ }
743
+ send(response, 404, "Not found");
744
+ }
745
+ function snapshot() {
746
+ return {
747
+ ...options.store.snapshot(),
748
+ canRestart: Boolean(options.restart),
749
+ historyDays: options.history?.days ?? 0,
750
+ mode: production ? "production" : "dev"
751
+ };
752
+ }
753
+ /**
754
+ * Accept telemetry from an application process that cannot share memory with
755
+ * the dashboard, such as a dev server worker: span batches, and a notice when
756
+ * the app loads.
757
+ */
758
+ function ingest(request, response) {
759
+ if (request.headers["x-brick-dashboard"] !== "1") {
760
+ send(response, 403, "Forbidden");
761
+ return;
762
+ }
763
+ let body = "";
764
+ let rejected = false;
765
+ request.setEncoding("utf8");
766
+ request.on("data", (chunk) => {
767
+ if (rejected) return;
768
+ body += chunk;
769
+ if (body.length > MAX_INGEST_BYTES) {
770
+ rejected = true;
771
+ send(response, 413, "Payload too large");
772
+ request.destroy();
773
+ }
774
+ });
775
+ request.on("end", () => {
776
+ if (rejected) return;
777
+ try {
778
+ const payload = JSON.parse(body);
779
+ if (Array.isArray(payload.records)) options.store.ingest(payload.records, options.store.latestGeneration);
780
+ if (typeof payload.worker === "string") options.store.startGeneration(payload.worker);
781
+ send(response, 204, "");
782
+ } catch {
783
+ send(response, 400, "Bad request");
784
+ }
785
+ });
786
+ }
787
+ /** The Docs tab's data: tree, compiled pages, search, images, components. */
788
+ async function docsRoute(response, pathname, params) {
789
+ const docs = options.docs?.();
790
+ if (!docs) {
791
+ send(response, 404, "The app has no documentation.");
792
+ return;
793
+ }
794
+ const json = (body) => send(response, 200, JSON.stringify(body), {
795
+ "content-type": "application/json",
796
+ "cache-control": "no-store"
797
+ });
798
+ try {
799
+ if (pathname === "/api/docs") return json(docs.info());
800
+ if (pathname === "/api/docs/search") return json(await docs.search(params.get("q") ?? ""));
801
+ if (pathname === "/api/docs/components.js") {
802
+ const code = await docs.components();
803
+ if (code === void 0) return send(response, 404, "No components.");
804
+ return send(response, 200, code, {
805
+ "content-type": "text/javascript; charset=utf-8",
806
+ "cache-control": "no-store"
807
+ });
808
+ }
809
+ const pagePrefix = "/api/docs/page";
810
+ if (pathname === pagePrefix || pathname.startsWith(`${pagePrefix}/`)) {
811
+ const slugs = pathname.slice(14).split("/").filter(Boolean).map(decodeURIComponent);
812
+ const page = await docs.page(slugs);
813
+ return page ? json(page) : send(response, 404, "No such page.");
814
+ }
815
+ if (pathname.startsWith("/api/docs/files/")) {
816
+ const file = await docs.file(pathname.slice(16).split("/").map(decodeURIComponent).join("/"));
817
+ if (!file) return send(response, 404, "No such file.");
818
+ return send(response, 200, file.body, {
819
+ "content-type": file.type,
820
+ "cache-control": "no-store",
821
+ "content-security-policy": "sandbox"
822
+ });
823
+ }
824
+ send(response, 404, "Not found");
825
+ } catch (error) {
826
+ send(response, error instanceof URIError ? 400 : 500, error instanceof Error ? error.message : String(error));
827
+ }
828
+ }
829
+ /**
830
+ * Send a request on to the app for the APIs view, which cannot call the app
831
+ * directly: it is another origin. Only the dashboard's own page may use this,
832
+ * and only to reach the app being shown. The address to call is `?url=`; a
833
+ * `?cookie=` is the cookie parameters the reader typed into Try it, and the
834
+ * only cookie the app is sent (the dashboard's own are never forwarded).
835
+ */
836
+ async function proxy(request, response, url) {
837
+ const site = request.headers["sec-fetch-site"];
838
+ const origin = request.headers.origin;
839
+ if (site !== void 0 && site !== "same-origin" || origin !== void 0 && origin !== `http://${request.headers.host}`) {
840
+ send(response, 403, "Forbidden");
841
+ return;
842
+ }
843
+ let target;
844
+ try {
845
+ target = new URL(url.searchParams.get("url") ?? "");
846
+ } catch {}
847
+ const appUrl = options.store.apiSnapshot()?.appUrl;
848
+ if (!target || !appUrl || target.origin !== new URL(appUrl).origin) {
849
+ send(response, 403, "Only the app shown in the dashboard can be reached.");
850
+ return;
851
+ }
852
+ const body = await readBytes(request, MAX_PROXY_BYTES);
853
+ if (!body) {
854
+ send(response, 413, "Payload too large");
855
+ return;
856
+ }
857
+ const headers = new Headers();
858
+ for (const [name, value] of Object.entries(request.headers)) {
859
+ if (value === void 0 || NOT_FORWARDED.has(name)) continue;
860
+ if (name.startsWith("sec-")) continue;
861
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
862
+ }
863
+ const cookie = url.searchParams.get("cookie");
864
+ if (cookie) headers.set("cookie", cookie);
865
+ const bodyless = request.method === "GET" || request.method === "HEAD";
866
+ try {
867
+ const upstream = await fetch(target, {
868
+ method: request.method,
869
+ headers,
870
+ body: bodyless ? void 0 : body,
871
+ redirect: "manual"
872
+ });
873
+ const returned = {};
874
+ upstream.headers.forEach((value, name) => {
875
+ if (!NOT_RETURNED.has(name)) returned[name] = value;
876
+ });
877
+ send(response, upstream.status, new Uint8Array(await upstream.arrayBuffer()), returned);
878
+ } catch {
879
+ send(response, 502, "Could not reach the app.");
880
+ }
881
+ }
882
+ function eventStream(request, response) {
883
+ response.writeHead(200, {
884
+ "content-type": "text/event-stream",
885
+ "cache-control": "no-cache",
886
+ connection: "keep-alive",
887
+ "x-accel-buffering": "no"
888
+ });
889
+ const write = (chunk) => {
890
+ if (response.writableEnded || response.destroyed) return;
891
+ response.write(chunk);
892
+ };
893
+ write(`event: snapshot\ndata: ${JSON.stringify(snapshot())}\n\n`);
894
+ const unsubscribe = options.store.subscribe((event) => write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`));
895
+ const keepalive = setInterval(() => write(": keepalive\n\n"), KEEPALIVE_MS);
896
+ request.on("close", () => {
897
+ clearInterval(keepalive);
898
+ unsubscribe();
899
+ });
900
+ }
901
+ return new Promise((resolve, reject) => {
902
+ server.once("error", (error) => {
903
+ reject(new Error(production ? `Brick: dashboard port ${options.port} is unavailable. Set dashboard.port in brick() to another.` : `Brick: dashboard port ${options.port} is unavailable. Use --dashboard-port <number> or --no-dashboard.`, { cause: error }));
904
+ });
905
+ server.listen(options.port, host, () => {
906
+ const address = server.address();
907
+ const port = typeof address === "object" && address !== null ? address.port : options.port;
908
+ allowedHosts = /* @__PURE__ */ new Set([
909
+ `127.0.0.1:${port}`,
910
+ `localhost:${port}`,
911
+ `[::1]:${port}`
912
+ ]);
913
+ resolve({
914
+ port,
915
+ stop() {
916
+ server.close();
917
+ server.closeAllConnections();
918
+ }
919
+ });
920
+ });
921
+ });
922
+ }
923
+ /** The whole request body, or undefined when it is larger than `limit`. */
924
+ function readBytes(request, limit) {
925
+ return new Promise((resolve) => {
926
+ const chunks = [];
927
+ let size = 0;
928
+ request.on("data", (chunk) => {
929
+ size += chunk.length;
930
+ if (size > limit) {
931
+ resolve(void 0);
932
+ request.destroy();
933
+ return;
934
+ }
935
+ chunks.push(chunk);
936
+ });
937
+ request.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
938
+ request.on("error", () => resolve(void 0));
939
+ });
940
+ }
941
+ function history(store, pathname, params, response) {
942
+ const json = (body) => send(response, 200, JSON.stringify(body), { "content-type": "application/json" });
943
+ try {
944
+ if (pathname === "/api/history") return json(store.info());
945
+ if (pathname === "/api/history/summary") return json(store.summary(parseHistoryQuery(params)));
946
+ if (pathname === "/api/history/traces") return json(store.traces(parseHistoryQuery(params)));
947
+ if (pathname === "/api/history/facets") return json(store.facets(parseHistoryQuery(params)));
948
+ if (pathname === "/api/history/volume") return json(store.volume(parseHistoryQuery(params)));
949
+ if (pathname === "/api/history/export") return send(response, 200, store.exportCsv(parseHistoryQuery(params)), {
950
+ "content-type": "text/csv; charset=utf-8",
951
+ "content-disposition": "attachment; filename=\"brick-requests.csv\"",
952
+ "cache-control": "no-store"
953
+ });
954
+ if (pathname.startsWith("/api/history/traces/")) {
955
+ const trace = store.trace(decodeURIComponent(pathname.slice(20)));
956
+ if (trace) return json(trace);
957
+ }
958
+ send(response, 404, "Not found");
959
+ } catch {
960
+ send(response, 500, "History query failed");
961
+ }
962
+ }
963
+ const ASSET_TYPES = {
964
+ ".js": "text/javascript; charset=utf-8",
965
+ ".css": "text/css; charset=utf-8",
966
+ ".woff2": "font/woff2"
967
+ };
968
+ /** The built React app, next to `src/` in the repo and next to `dist/` when published. */
969
+ function assetsDirectory() {
970
+ for (const relative of ["../dashboard-dist/", "../../dashboard-dist/"]) {
971
+ const directory = fileURLToPath(new URL(relative, import.meta.url));
972
+ if (existsSync(join(directory, "app.js"))) return directory;
973
+ }
974
+ }
975
+ function serveAsset(response, name) {
976
+ if (!/^[\w.-]+$/.test(name) || name.startsWith(".")) {
977
+ send(response, 404, "Not found");
978
+ return;
979
+ }
980
+ const directory = assetsDirectory();
981
+ if (!directory) {
982
+ send(response, 503, "Dashboard assets are missing. Build them with: bun run --filter @brickkit/cli build");
983
+ return;
984
+ }
985
+ readFile(join(directory, name)).then((body) => send(response, 200, body, {
986
+ "content-type": ASSET_TYPES[extname(name)] ?? "application/octet-stream",
987
+ "cache-control": "no-store"
988
+ }), () => send(response, 404, "Not found"));
989
+ }
990
+ function send(response, status, body, headers = { "content-type": "text/plain; charset=utf-8" }) {
991
+ response.writeHead(status, headers);
992
+ response.end(body);
993
+ }
994
+ //#endregion
995
+ //#region src/dev-docs.ts
996
+ const PACKAGES = ["fumadocs-core", "@mdx-js/mdx"];
997
+ const PAGE_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".mdx"]);
998
+ const IMAGE_TYPES = {
999
+ ".png": "image/png",
1000
+ ".jpg": "image/jpeg",
1001
+ ".jpeg": "image/jpeg",
1002
+ ".gif": "image/gif",
1003
+ ".webp": "image/webp",
1004
+ ".avif": "image/avif",
1005
+ ".svg": "image/svg+xml",
1006
+ ".ico": "image/x-icon"
1007
+ };
1008
+ const REFRESH_DELAY_MS = 100;
1009
+ async function loadFumadocs() {
1010
+ try {
1011
+ const [source, matter, plugins, search, mdx] = await Promise.all([
1012
+ import("fumadocs-core/source"),
1013
+ import("fumadocs-core/content/md/frontmatter"),
1014
+ import("fumadocs-core/mdx-plugins"),
1015
+ import("fumadocs-core/search/server"),
1016
+ import("@mdx-js/mdx")
1017
+ ]);
1018
+ return {
1019
+ loader: source.loader,
1020
+ frontmatter: matter.frontmatter,
1021
+ plugins,
1022
+ createSearchAPI: search.createSearchAPI,
1023
+ compile: mdx.compile
1024
+ };
1025
+ } catch (error) {
1026
+ if (error.code === "ERR_MODULE_NOT_FOUND" || /Cannot find (module|package)/.test(String(error?.message))) return [...PACKAGES];
1027
+ throw error;
1028
+ }
1029
+ }
1030
+ const humanize = (name) => {
1031
+ const spaced = name.replace(/[-_]+/g, " ").trim();
1032
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
1033
+ };
1034
+ const H1 = /^#\s+(.+?)\s*#*\s*$/;
1035
+ /**
1036
+ * The first `# Heading` outside code fences: its text, and the content without
1037
+ * it. The page shows its title above the content, so a heading that only
1038
+ * repeats the title would appear twice.
1039
+ */
1040
+ function firstHeading(content) {
1041
+ const lines = content.split("\n");
1042
+ let fenced = false;
1043
+ let seenText = false;
1044
+ for (const [index, line] of lines.entries()) if (/^\s*(```|~~~)/.test(line)) {
1045
+ fenced = !fenced;
1046
+ seenText = true;
1047
+ } else if (!fenced) {
1048
+ const match = H1.exec(line);
1049
+ if (match) {
1050
+ const rest = [...lines.slice(0, index), ...lines.slice(index + 1)];
1051
+ if (rest[index]?.trim() === "") rest.splice(index, 1);
1052
+ return {
1053
+ text: match[1],
1054
+ rest: rest.join("\n"),
1055
+ leading: !seenText
1056
+ };
1057
+ }
1058
+ if (line.trim() !== "") seenText = true;
1059
+ }
1060
+ }
1061
+ async function scan(root, fumadocs, warn) {
1062
+ const pages = [];
1063
+ const metas = [];
1064
+ async function visit(directory) {
1065
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
1066
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
1067
+ const absolute = join(directory, entry.name);
1068
+ const path = relative(root, absolute).split(sep).join("/");
1069
+ if (entry.isDirectory()) await visit(absolute);
1070
+ else if (entry.name === "meta.json") try {
1071
+ const data = JSON.parse(await readFile(absolute, "utf8"));
1072
+ if (data && typeof data === "object") metas.push({
1073
+ path,
1074
+ data
1075
+ });
1076
+ } catch (error) {
1077
+ warn(`[Brick-TS] Skipping docs ${path}: ${errorMessage(error)}`);
1078
+ }
1079
+ else if (PAGE_EXTENSIONS.has(extname(entry.name))) {
1080
+ const text = await readFile(absolute, "utf8");
1081
+ let data = {};
1082
+ let content = text;
1083
+ try {
1084
+ const parsed = fumadocs.frontmatter(text);
1085
+ data = parsed.data;
1086
+ content = parsed.content;
1087
+ } catch (error) {
1088
+ warn(`[Brick-TS] Ignoring the frontmatter of docs ${path}: ${errorMessage(error)}`);
1089
+ }
1090
+ const name = basename(entry.name, extname(entry.name));
1091
+ const heading = firstHeading(content);
1092
+ const given = typeof data.title === "string" && data.title ? data.title : void 0;
1093
+ const title = given ?? heading?.text ?? humanize(name === "index" ? basename(dirname(path)) || "Home" : name);
1094
+ if (heading && (!given || heading.leading && heading.text === given)) content = heading.rest;
1095
+ pages.push({
1096
+ path,
1097
+ absolute,
1098
+ title,
1099
+ description: typeof data.description === "string" ? data.description : void 0,
1100
+ content,
1101
+ data
1102
+ });
1103
+ }
1104
+ }
1105
+ }
1106
+ await visit(root);
1107
+ return {
1108
+ pages,
1109
+ metas
1110
+ };
1111
+ }
1112
+ function errorMessage(error) {
1113
+ return error instanceof Error ? error.message : String(error);
1114
+ }
1115
+ function walk(node, visit) {
1116
+ visit(node);
1117
+ for (const child of node.children ?? []) walk(child, visit);
1118
+ }
1119
+ /** Ways a link inside a page can point at another page or a local image. */
1120
+ function resolveInside(from, href) {
1121
+ if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("#")) return void 0;
1122
+ if (href.startsWith("/")) return void 0;
1123
+ const [target] = href.split(/[?#]/);
1124
+ if (!target) return void 0;
1125
+ const resolved = posix.normalize(posix.join(posix.dirname(from), target));
1126
+ return resolved.startsWith("../") ? void 0 : resolved;
1127
+ }
1128
+ /**
1129
+ * The page tree and compiled pages of one docs folder. It watches the folder,
1130
+ * so edits show in the dashboard as they are saved.
1131
+ */
1132
+ var DevDocs = class {
1133
+ #root;
1134
+ #documentation;
1135
+ /** Relative paths in `documentation` start here: the app entry's folder. */
1136
+ #base;
1137
+ #fumadocs;
1138
+ #warn;
1139
+ #listeners = /* @__PURE__ */ new Set();
1140
+ #watchers = [];
1141
+ #loader;
1142
+ #pages = /* @__PURE__ */ new Map();
1143
+ #byPath = /* @__PURE__ */ new Map();
1144
+ #compiled = /* @__PURE__ */ new Map();
1145
+ #search;
1146
+ #timer;
1147
+ #refreshing = Promise.resolve();
1148
+ #closed = false;
1149
+ #title = "Docs";
1150
+ revision = 0;
1151
+ constructor(base, documentation, fumadocs, warn) {
1152
+ this.#base = base;
1153
+ this.#documentation = documentation;
1154
+ this.#root = resolve(base, documentation.dir);
1155
+ this.#fumadocs = fumadocs;
1156
+ this.#warn = warn;
1157
+ }
1158
+ /** Read the folder again and tell listeners. */
1159
+ async refresh() {
1160
+ this.#refreshing = this.#refreshing.then(() => this.#scan());
1161
+ await this.#refreshing;
1162
+ }
1163
+ async #scan() {
1164
+ const { pages, metas } = await scan(this.#root, this.#fumadocs, this.#warn);
1165
+ if (this.#closed) return;
1166
+ const source = this.#fumadocs.loader({
1167
+ baseUrl: "/",
1168
+ source: { files: [...pages.map((page) => ({
1169
+ type: "page",
1170
+ path: page.path,
1171
+ data: {
1172
+ ...page.data,
1173
+ title: page.title,
1174
+ description: page.description
1175
+ }
1176
+ })), ...metas.map((meta) => ({
1177
+ type: "meta",
1178
+ path: meta.path,
1179
+ data: meta.data
1180
+ }))] }
1181
+ });
1182
+ this.#loader = source;
1183
+ this.#pages = /* @__PURE__ */ new Map();
1184
+ this.#byPath = /* @__PURE__ */ new Map();
1185
+ for (const page of this.#loader.getPages()) {
1186
+ const slug = page.slugs.join("/");
1187
+ const file = pages.find((candidate) => candidate.path === page.path);
1188
+ if (!file) continue;
1189
+ this.#pages.set(slug, file);
1190
+ this.#byPath.set(file.path, slug);
1191
+ }
1192
+ this.#compiled.clear();
1193
+ this.#search = void 0;
1194
+ const tree = this.#loader.getPageTree();
1195
+ this.#title = typeof tree.name === "string" ? tree.name : "Docs";
1196
+ this.revision++;
1197
+ for (const listener of this.#listeners) listener();
1198
+ }
1199
+ /** Start watching the folder, and the project's components module. */
1200
+ watch() {
1201
+ const changed = () => {
1202
+ clearTimeout(this.#timer);
1203
+ this.#timer = setTimeout(() => {
1204
+ this.refresh().catch((error) => this.#warn(`[Brick-TS] Docs: ${errorMessage(error)}`));
1205
+ }, REFRESH_DELAY_MS);
1206
+ };
1207
+ const folders = [this.#root];
1208
+ if (this.#documentation.components) folders.push(dirname(this.#componentsPath()));
1209
+ for (const [index, folder] of folders.entries()) try {
1210
+ this.#watchers.push(watch(folder, { recursive: index === 0 }, () => changed()));
1211
+ } catch {
1212
+ try {
1213
+ this.#watchers.push(watch(folder, () => changed()));
1214
+ } catch {}
1215
+ }
1216
+ }
1217
+ onChange(listener) {
1218
+ this.#listeners.add(listener);
1219
+ return () => {
1220
+ this.#listeners.delete(listener);
1221
+ };
1222
+ }
1223
+ snapshot() {
1224
+ return {
1225
+ revision: this.revision,
1226
+ status: "ready",
1227
+ title: this.#title,
1228
+ components: Boolean(this.#documentation.components)
1229
+ };
1230
+ }
1231
+ info() {
1232
+ return {
1233
+ tree: simplify(this.#loader?.getPageTree()),
1234
+ components: Boolean(this.#documentation.components),
1235
+ revision: this.revision
1236
+ };
1237
+ }
1238
+ /** Compile one page; undefined when there is no such page. */
1239
+ async page(slugs) {
1240
+ const key = slugs.join("/");
1241
+ const file = this.#pages.get(key);
1242
+ if (!file) return void 0;
1243
+ const cached = this.#compiled.get(key);
1244
+ if (cached) return cached;
1245
+ const page = await this.#compile(file, slugs);
1246
+ if (this.#pages.get(key) === file) this.#compiled.set(key, page);
1247
+ return page;
1248
+ }
1249
+ async #compile(file, slugs) {
1250
+ const { plugins, compile } = this.#fumadocs;
1251
+ const base = {
1252
+ title: file.title,
1253
+ description: file.description,
1254
+ path: file.path,
1255
+ slugs
1256
+ };
1257
+ try {
1258
+ const result = await compile({
1259
+ path: file.absolute,
1260
+ value: file.content
1261
+ }, {
1262
+ outputFormat: "function-body",
1263
+ development: false,
1264
+ remarkPlugins: [
1265
+ plugins.remarkGfm,
1266
+ plugins.remarkHeading,
1267
+ plugins.remarkCodeTab,
1268
+ plugins.remarkNpm,
1269
+ plugins.remarkAdmonition,
1270
+ () => (tree) => this.#rewriteLinks(tree, file.path)
1271
+ ],
1272
+ rehypePlugins: [plugins.rehypeCode]
1273
+ });
1274
+ const toc = result.data.toc ?? [];
1275
+ return {
1276
+ ...base,
1277
+ toc: toc.map((item) => ({
1278
+ title: plainText(item.title),
1279
+ url: item.url,
1280
+ depth: item.depth
1281
+ })),
1282
+ code: String(result)
1283
+ };
1284
+ } catch (error) {
1285
+ return {
1286
+ ...base,
1287
+ toc: [],
1288
+ code: "",
1289
+ error: errorMessage(error)
1290
+ };
1291
+ }
1292
+ }
1293
+ /**
1294
+ * Links to other pages become dashboard routes, and local images are served
1295
+ * from the docs folder, so a folder reads the same here as on a docs site.
1296
+ * This covers markdown links and the `href` of components such as `<Card>`.
1297
+ */
1298
+ #rewriteLinks(tree, from) {
1299
+ const file = (resolved) => `/api/docs/files/${resolved.split("/").map(encodeURIComponent).join("/")}`;
1300
+ walk(tree, (node) => {
1301
+ if (node.type === "link" && node.url !== void 0) node.url = this.#route(from, node.url) ?? node.url;
1302
+ else if (node.type === "image" && node.url !== void 0) {
1303
+ const resolved = resolveInside(from, node.url);
1304
+ if (resolved !== void 0) node.url = file(resolved);
1305
+ } else if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") for (const attribute of node.attributes ?? []) {
1306
+ if (attribute.type !== "mdxJsxAttribute") continue;
1307
+ if (typeof attribute.value !== "string") continue;
1308
+ if (attribute.name === "href") attribute.value = this.#route(from, attribute.value) ?? attribute.value;
1309
+ else if (attribute.name === "src" && node.name === "img") {
1310
+ const resolved = resolveInside(from, attribute.value);
1311
+ if (resolved !== void 0) attribute.value = file(resolved);
1312
+ }
1313
+ }
1314
+ });
1315
+ }
1316
+ /**
1317
+ * The dashboard route for a link to a page of these docs, or undefined for
1318
+ * anything else (other sites, in-page anchors, files). A link to a page that
1319
+ * does not exist still becomes a route, so it says "No such page" here
1320
+ * instead of leaving the dashboard.
1321
+ */
1322
+ #route(from, href) {
1323
+ const hashAt = href.indexOf("#");
1324
+ const hash = hashAt >= 0 ? href.slice(hashAt) : "";
1325
+ const target = (hashAt >= 0 ? href.slice(0, hashAt) : href).split("?")[0] ?? "";
1326
+ const route = (slug) => `#/docs${slug ? `/${slug}` : ""}${hash}`;
1327
+ if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("#") || !target) return void 0;
1328
+ if (target.startsWith("/")) {
1329
+ const slug = target.replace(/^\/+|\/+$/g, "");
1330
+ return this.#pages.has(slug) ? route(slug) : void 0;
1331
+ }
1332
+ const resolved = resolveInside(from, target);
1333
+ if (resolved === void 0) return void 0;
1334
+ const known = this.#byPath.get(resolved);
1335
+ if (known !== void 0) return route(known);
1336
+ if (!PAGE_EXTENSIONS.has(extname(resolved))) return void 0;
1337
+ return route(resolved.slice(0, -extname(resolved).length).replace(/(^|\/)index$/, ""));
1338
+ }
1339
+ async search(query) {
1340
+ if (!query.trim()) return [];
1341
+ this.#search ??= this.#buildSearch();
1342
+ return (await this.#search).search(query);
1343
+ }
1344
+ async #buildSearch() {
1345
+ const { plugins, createSearchAPI } = this.#fumadocs;
1346
+ const api = createSearchAPI("advanced", { indexes: [...this.#pages.entries()].map(([slug, file]) => ({
1347
+ id: file.path,
1348
+ title: file.title,
1349
+ description: file.description,
1350
+ url: `/${slug}`,
1351
+ structuredData: plugins.structure(file.content)
1352
+ })) });
1353
+ return { async search(query) {
1354
+ return await api.search(query);
1355
+ } };
1356
+ }
1357
+ /** A file from the docs folder that a page can show, such as an image. */
1358
+ async file(relativePath) {
1359
+ const type = IMAGE_TYPES[extname(relativePath).toLowerCase()];
1360
+ if (!type) return void 0;
1361
+ const absolute = resolve(this.#root, relativePath);
1362
+ if (absolute !== this.#root && !absolute.startsWith(this.#root + sep)) return void 0;
1363
+ try {
1364
+ if (!(await stat(absolute)).isFile()) return void 0;
1365
+ return {
1366
+ body: new Uint8Array(await readFile(absolute)),
1367
+ type
1368
+ };
1369
+ } catch {
1370
+ return;
1371
+ }
1372
+ }
1373
+ #componentsPath() {
1374
+ const { components } = this.#documentation;
1375
+ return components ? resolve(this.#base, components) : void 0;
1376
+ }
1377
+ /** The project's components as one browser module; undefined when it has none. */
1378
+ async components() {
1379
+ const entry = this.#componentsPath();
1380
+ return entry ? bundleComponents(entry) : void 0;
1381
+ }
1382
+ close() {
1383
+ this.#closed = true;
1384
+ clearTimeout(this.#timer);
1385
+ for (const watcher of this.#watchers) watcher.close();
1386
+ this.#watchers.length = 0;
1387
+ this.#listeners.clear();
1388
+ }
1389
+ };
1390
+ const SHARED = [
1391
+ "react",
1392
+ "react/jsx-runtime",
1393
+ "react/jsx-dev-runtime"
1394
+ ];
1395
+ /** Bundle a module of React components for the dashboard to import. */
1396
+ async function bundleComponents(entry) {
1397
+ if (typeof Bun !== "undefined") {
1398
+ const result = await Bun.build({
1399
+ entrypoints: [entry],
1400
+ target: "browser",
1401
+ format: "esm",
1402
+ external: SHARED,
1403
+ minify: false
1404
+ });
1405
+ if (!result.success) throw new Error(result.logs.map((log) => log.message).join("\n"));
1406
+ return result.outputs[0].text();
1407
+ }
1408
+ const { build } = await import("vite");
1409
+ const output = await build({
1410
+ configFile: false,
1411
+ logLevel: "silent",
1412
+ root: dirname(entry),
1413
+ oxc: { jsx: { runtime: "automatic" } },
1414
+ esbuild: { jsx: "automatic" },
1415
+ define: { "process.env.NODE_ENV": "\"development\"" },
1416
+ build: {
1417
+ write: false,
1418
+ minify: false,
1419
+ lib: {
1420
+ entry,
1421
+ formats: ["es"],
1422
+ fileName: "components"
1423
+ },
1424
+ rollupOptions: { external: SHARED }
1425
+ }
1426
+ });
1427
+ const bundles = Array.isArray(output) ? output : [output];
1428
+ for (const bundle of bundles) {
1429
+ const chunk = ("output" in bundle ? bundle.output : []).find((item) => item.type === "chunk" && item.isEntry);
1430
+ if (chunk && "code" in chunk) return chunk.code;
1431
+ }
1432
+ throw new Error("Brick: the docs components module produced no output.");
1433
+ }
1434
+ /** Flatten what MDX gives for a heading to text. */
1435
+ function plainText(value) {
1436
+ if (typeof value === "string") return value;
1437
+ if (Array.isArray(value)) return value.map(plainText).join("");
1438
+ if (value && typeof value === "object") {
1439
+ const node = value;
1440
+ if (typeof node.value === "string") return node.value;
1441
+ return plainText(node.props?.children ?? node.children);
1442
+ }
1443
+ return "";
1444
+ }
1445
+ /** The page tree as plain data for the dashboard; icons and links are left out. */
1446
+ function simplify(tree) {
1447
+ const text = (value) => typeof value === "string" ? value : plainText(value);
1448
+ const convert = (node) => {
1449
+ if (node.type === "page" && node.url !== void 0) return {
1450
+ type: "page",
1451
+ name: text(node.name),
1452
+ url: node.url,
1453
+ ...typeof node.description === "string" ? { description: node.description } : {}
1454
+ };
1455
+ if (node.type === "separator") return {
1456
+ type: "separator",
1457
+ ...node.name ? { name: text(node.name) } : {}
1458
+ };
1459
+ if (node.type === "folder") return {
1460
+ type: "folder",
1461
+ name: text(node.name),
1462
+ ...node.index?.url !== void 0 ? { index: {
1463
+ name: text(node.index.name),
1464
+ url: node.index.url
1465
+ } } : {},
1466
+ children: (node.children ?? []).flatMap((child) => convert(child) ?? []),
1467
+ ...node.defaultOpen ? { defaultOpen: true } : {}
1468
+ };
1469
+ };
1470
+ return {
1471
+ name: text(tree?.name) || "Docs",
1472
+ children: (tree?.children ?? []).flatMap((child) => convert(child) ?? [])
1473
+ };
1474
+ }
1475
+ /** Open a docs folder; says what is missing when it cannot be shown. */
1476
+ async function openDocs(options) {
1477
+ const fumadocs = await loadFumadocs();
1478
+ if (Array.isArray(fumadocs)) return {
1479
+ status: "missing",
1480
+ packages: fumadocs
1481
+ };
1482
+ const docs = new DevDocs(options.base, options.documentation, fumadocs, options.warn);
1483
+ try {
1484
+ await docs.refresh();
1485
+ } catch (error) {
1486
+ docs.close();
1487
+ const root = resolve(options.base, options.documentation.dir);
1488
+ return {
1489
+ status: "error",
1490
+ message: error.code === "ENOENT" ? `The docs folder ${root} does not exist.` : errorMessage(error)
1491
+ };
1492
+ }
1493
+ docs.watch();
1494
+ return {
1495
+ status: "ready",
1496
+ docs
1497
+ };
1498
+ }
1499
+ /**
1500
+ * The docs of whichever app is running: opened when the app says where they
1501
+ * are, replaced when that changes, and closed when it stops asking for them.
1502
+ */
1503
+ var DocsHost = class {
1504
+ #store;
1505
+ #warn;
1506
+ #docs;
1507
+ #stopListening;
1508
+ #key;
1509
+ #pending = Promise.resolve();
1510
+ constructor(store, warn) {
1511
+ this.#store = store;
1512
+ this.#warn = warn;
1513
+ }
1514
+ get current() {
1515
+ return this.#docs;
1516
+ }
1517
+ /**
1518
+ * Follow the app's `documentation`. Relative paths in it start at `base`, the
1519
+ * folder of the app entry, as they read in the file that sets them.
1520
+ */
1521
+ configure(base, documentation) {
1522
+ this.#pending = this.#pending.then(() => this.#configure(base, documentation));
1523
+ return this.#pending;
1524
+ }
1525
+ async #configure(base, documentation) {
1526
+ const key = JSON.stringify([base, documentation ?? null]);
1527
+ if (key === this.#key) return;
1528
+ this.#key = key;
1529
+ this.#release();
1530
+ if (!documentation) {
1531
+ this.#store.setDocs(null);
1532
+ return;
1533
+ }
1534
+ const opened = await openDocs({
1535
+ base,
1536
+ documentation,
1537
+ warn: this.#warn
1538
+ });
1539
+ if (opened.status !== "ready") {
1540
+ const message = opened.status === "missing" ? `The docs need ${opened.packages.join(" and ")}. Install with: bun add -d ${opened.packages.join(" ")}` : opened.message;
1541
+ this.#warn(`[Brick-TS] Docs are off. ${message}`);
1542
+ this.#store.setDocs({
1543
+ revision: 1,
1544
+ status: opened.status,
1545
+ title: "Docs",
1546
+ components: false,
1547
+ message,
1548
+ ...opened.status === "missing" ? { packages: opened.packages } : {}
1549
+ });
1550
+ return;
1551
+ }
1552
+ this.#docs = opened.docs;
1553
+ this.#stopListening = opened.docs.onChange(() => this.#store.setDocs(opened.docs.snapshot()));
1554
+ this.#store.setDocs(opened.docs.snapshot());
1555
+ }
1556
+ #release() {
1557
+ this.#stopListening?.();
1558
+ this.#stopListening = void 0;
1559
+ this.#docs?.close();
1560
+ this.#docs = void 0;
1561
+ }
1562
+ close() {
1563
+ this.#key = void 0;
1564
+ this.#release();
1565
+ }
1566
+ };
1567
+ //#endregion
1568
+ //#region src/dev-telemetry-store.ts
1569
+ const LIMITS = {
1570
+ traces: 200,
1571
+ spansPerTrace: 500,
1572
+ failures: 200,
1573
+ reloads: 100
1574
+ };
1575
+ const WORKER_FAILURE_CODES = {
1576
+ startup: "STARTUP_FAILED",
1577
+ uncaught: "UNCAUGHT_EXCEPTION",
1578
+ "unhandled-rejection": "UNHANDLED_REJECTION"
1579
+ };
1580
+ /**
1581
+ * Supervisor-side history of requests, failures, and reloads. It lives in the
1582
+ * parent process, so it survives application restarts.
1583
+ */
1584
+ var DevTelemetryStore = class {
1585
+ #traces = /* @__PURE__ */ new Map();
1586
+ #failures = [];
1587
+ #reloads = [];
1588
+ #listeners = /* @__PURE__ */ new Set();
1589
+ #history;
1590
+ #architecture = null;
1591
+ #api = null;
1592
+ #docs = null;
1593
+ #apiDocuments = [];
1594
+ #sequence = 0;
1595
+ #generation = 0;
1596
+ /** Finished requests and failures are also kept in `history`, when given. */
1597
+ constructor(options = {}) {
1598
+ this.#history = options.history;
1599
+ }
1600
+ /** Replace the architecture with the one from the latest successful start. */
1601
+ setArchitecture(schema, generation) {
1602
+ this.#architecture = {
1603
+ generation,
1604
+ schema
1605
+ };
1606
+ this.#emit({
1607
+ type: "architecture",
1608
+ architecture: this.#architecture
1609
+ });
1610
+ }
1611
+ ingest(records, generation) {
1612
+ const touched = /* @__PURE__ */ new Set();
1613
+ for (const record of records) {
1614
+ const timeMs = record.phase === "start" ? record.startMs : record.endMs;
1615
+ const entry = this.#entry(record.traceId, generation, timeMs);
1616
+ touched.add(entry);
1617
+ if (record.phase === "start") this.#start(entry, record);
1618
+ else this.#end(entry, record);
1619
+ }
1620
+ for (const entry of touched) {
1621
+ const trace = summarize(entry);
1622
+ this.#emit({
1623
+ type: "trace",
1624
+ trace
1625
+ });
1626
+ if (entry.status === "ok" || entry.status === "error") this.#history?.saveTrace(trace);
1627
+ }
1628
+ }
1629
+ recordWorkerError(phase, error, generation) {
1630
+ this.#pushFailure({
1631
+ phase,
1632
+ code: WORKER_FAILURE_CODES[phase],
1633
+ message: error.message,
1634
+ stack: error.stack,
1635
+ generation
1636
+ });
1637
+ }
1638
+ recordReload(reload) {
1639
+ const summary = {
1640
+ id: ++this.#sequence,
1641
+ at: Date.now(),
1642
+ ...reload
1643
+ };
1644
+ this.#reloads.unshift(summary);
1645
+ if (this.#reloads.length > LIMITS.reloads) this.#reloads.length = LIMITS.reloads;
1646
+ this.#emit({
1647
+ type: "reload",
1648
+ reload: summary
1649
+ });
1650
+ }
1651
+ /** Newest generation; spans reported without a process identity belong to it. */
1652
+ get latestGeneration() {
1653
+ return this.#generation;
1654
+ }
1655
+ /** Begin a generation when an application process loads, and record the reload. */
1656
+ startGeneration(detail) {
1657
+ this.#generation += 1;
1658
+ this.recordReload({
1659
+ kind: "started",
1660
+ generation: this.#generation,
1661
+ detail
1662
+ });
1663
+ return this.#generation;
1664
+ }
1665
+ /** Mark requests still running in a process that has exited as interrupted. */
1666
+ interruptGeneration(generation) {
1667
+ const now = Date.now();
1668
+ for (const entry of this.#traces.values()) {
1669
+ if (entry.generation !== generation || entry.status !== "running") continue;
1670
+ entry.status = "interrupted";
1671
+ entry.endMs = now;
1672
+ for (const span of entry.spans.values()) {
1673
+ if (span.status !== "running") continue;
1674
+ span.status = "interrupted";
1675
+ span.endMs = now;
1676
+ }
1677
+ this.#emit({
1678
+ type: "trace",
1679
+ trace: summarize(entry)
1680
+ });
1681
+ }
1682
+ }
1683
+ /** Replace the OpenAPI documents with the ones from the latest start. */
1684
+ setApiDocuments(documents, appUrl) {
1685
+ this.#apiDocuments = documents;
1686
+ this.#api = {
1687
+ revision: (this.#api?.revision ?? 0) + 1,
1688
+ ...appUrl ? { appUrl } : {},
1689
+ titles: documents.map((item) => item.title)
1690
+ };
1691
+ this.#emit({
1692
+ type: "api",
1693
+ api: this.#api
1694
+ });
1695
+ }
1696
+ /** Set what the Docs tab shows; null when the app has no documentation. */
1697
+ setDocs(docs) {
1698
+ this.#docs = docs;
1699
+ this.#emit({
1700
+ type: "docs",
1701
+ docs
1702
+ });
1703
+ }
1704
+ /** What the APIs view knows about the documents, without the documents. */
1705
+ apiSnapshot() {
1706
+ return this.#api;
1707
+ }
1708
+ /** The documents themselves; the snapshot carries only their names. */
1709
+ apiDocuments() {
1710
+ return this.#apiDocuments;
1711
+ }
1712
+ snapshot() {
1713
+ return {
1714
+ traces: [...this.#traces.values()].reverse().map(summarize),
1715
+ failures: [...this.#failures],
1716
+ reloads: [...this.#reloads],
1717
+ architecture: this.#architecture,
1718
+ api: this.#api,
1719
+ docs: this.#docs
1720
+ };
1721
+ }
1722
+ subscribe(listener) {
1723
+ this.#listeners.add(listener);
1724
+ return () => {
1725
+ this.#listeners.delete(listener);
1726
+ };
1727
+ }
1728
+ #entry(traceId, generation, timeMs) {
1729
+ let entry = this.#traces.get(traceId);
1730
+ if (!entry) {
1731
+ entry = {
1732
+ traceId,
1733
+ generation,
1734
+ spans: /* @__PURE__ */ new Map(),
1735
+ name: "",
1736
+ startMs: timeMs,
1737
+ status: "running",
1738
+ failureRecorded: false,
1739
+ truncated: false
1740
+ };
1741
+ this.#traces.set(traceId, entry);
1742
+ if (this.#traces.size > LIMITS.traces) {
1743
+ const oldest = this.#traces.keys().next().value;
1744
+ if (oldest !== void 0) this.#traces.delete(oldest);
1745
+ }
1746
+ }
1747
+ return entry;
1748
+ }
1749
+ #start(entry, record) {
1750
+ entry.startMs = Math.min(entry.startMs, record.startMs);
1751
+ if (!(record.parentSpanId !== void 0 && entry.spans.has(record.parentSpanId)) && entry.rootSpanId === void 0) {
1752
+ entry.rootSpanId = record.spanId;
1753
+ entry.name = record.name;
1754
+ entry.method = stringAttribute(record.attributes, "http.request.method");
1755
+ entry.route = stringAttribute(record.attributes, "http.route");
1756
+ entry.path = stringAttribute(record.attributes, "url.path");
1757
+ }
1758
+ if (entry.spans.size >= LIMITS.spansPerTrace) {
1759
+ entry.truncated = true;
1760
+ return;
1761
+ }
1762
+ entry.spans.set(record.spanId, {
1763
+ spanId: record.spanId,
1764
+ parentSpanId: record.parentSpanId,
1765
+ name: record.name,
1766
+ startMs: record.startMs,
1767
+ status: "running",
1768
+ attributes: record.attributes,
1769
+ events: []
1770
+ });
1771
+ }
1772
+ #end(entry, record) {
1773
+ const existing = entry.spans.get(record.spanId);
1774
+ const span = existing ?? {
1775
+ spanId: record.spanId,
1776
+ name: record.name,
1777
+ startMs: record.endMs,
1778
+ status: "running",
1779
+ attributes: {},
1780
+ events: []
1781
+ };
1782
+ if (!existing) {
1783
+ if (entry.spans.size < LIMITS.spansPerTrace) entry.spans.set(record.spanId, span);
1784
+ else entry.truncated = true;
1785
+ }
1786
+ span.endMs = record.endMs;
1787
+ span.status = record.status === "error" ? "error" : "ok";
1788
+ span.statusMessage = record.statusMessage;
1789
+ span.attributes = {
1790
+ ...span.attributes,
1791
+ ...record.attributes
1792
+ };
1793
+ span.events = record.events;
1794
+ const code = stringAttribute(record.attributes, "brick.error.code");
1795
+ if (code !== void 0) {
1796
+ const exception = findException(record.events);
1797
+ this.#pushFailure({
1798
+ phase: "request",
1799
+ code,
1800
+ message: stringAttribute(exception, "exception.message") ?? stringAttribute(record.attributes, "brick.error.message") ?? code,
1801
+ status: numberAttribute(record.attributes, "brick.error.status"),
1802
+ stack: stringAttribute(exception, "exception.stacktrace"),
1803
+ traceId: entry.traceId,
1804
+ route: entry.route,
1805
+ service: stringAttribute(record.attributes, "brick.service"),
1806
+ action: stringAttribute(record.attributes, "brick.action"),
1807
+ generation: entry.generation
1808
+ });
1809
+ entry.failureRecorded = true;
1810
+ }
1811
+ if (record.spanId !== entry.rootSpanId) return;
1812
+ entry.endMs = record.endMs;
1813
+ entry.httpStatus = numberAttribute(record.attributes, "http.response.status_code");
1814
+ const status = entry.httpStatus ?? 0;
1815
+ const serverFault = status >= 500;
1816
+ const failed = record.status === "error" || serverFault;
1817
+ entry.status = failed ? "error" : "ok";
1818
+ if ((failed || status >= 400) && !entry.failureRecorded) {
1819
+ const exception = findException(record.events);
1820
+ this.#pushFailure({
1821
+ phase: "request",
1822
+ code: status >= 400 ? `HTTP_${status}` : "UNHANDLED_ERROR",
1823
+ message: stringAttribute(exception, "exception.message") ?? record.statusMessage ?? describeResponse(entry, status),
1824
+ status: entry.httpStatus,
1825
+ stack: stringAttribute(exception, "exception.stacktrace"),
1826
+ traceId: entry.traceId,
1827
+ route: entry.route,
1828
+ generation: entry.generation
1829
+ });
1830
+ entry.failureRecorded = true;
1831
+ }
1832
+ }
1833
+ #pushFailure(failure) {
1834
+ const entry = {
1835
+ id: ++this.#sequence,
1836
+ at: Date.now(),
1837
+ ...failure
1838
+ };
1839
+ this.#failures.unshift(entry);
1840
+ if (this.#failures.length > LIMITS.failures) this.#failures.length = LIMITS.failures;
1841
+ const trace = failure.traceId === void 0 ? void 0 : this.#traces.get(failure.traceId);
1842
+ if (trace) trace.message ??= failure.message;
1843
+ this.#emit({
1844
+ type: "failure",
1845
+ failure: entry
1846
+ });
1847
+ }
1848
+ #emit(event) {
1849
+ for (const listener of this.#listeners) try {
1850
+ listener(event);
1851
+ } catch {
1852
+ this.#listeners.delete(listener);
1853
+ }
1854
+ }
1855
+ };
1856
+ function summarize(entry) {
1857
+ const spans = [...entry.spans.values()].sort((a, b) => a.startMs - b.startMs);
1858
+ const actionSpan = spans.find((span) => span.name.startsWith("action "));
1859
+ return {
1860
+ traceId: entry.traceId,
1861
+ name: entry.name || spans[0]?.name || entry.traceId,
1862
+ method: entry.method,
1863
+ route: entry.route,
1864
+ path: entry.path,
1865
+ httpStatus: entry.httpStatus,
1866
+ generation: entry.generation,
1867
+ startMs: entry.startMs,
1868
+ endMs: entry.endMs,
1869
+ durationMs: entry.endMs === void 0 ? void 0 : entry.endMs - entry.startMs,
1870
+ status: entry.status,
1871
+ truncated: entry.truncated,
1872
+ service: stringAttribute(actionSpan?.attributes, "brick.service"),
1873
+ action: stringAttribute(actionSpan?.attributes, "brick.action"),
1874
+ message: entry.message,
1875
+ spans
1876
+ };
1877
+ }
1878
+ function describeResponse(entry, status) {
1879
+ const target = entry.path ?? entry.route ?? entry.name;
1880
+ const request = entry.method ? `${entry.method} ${target}` : target;
1881
+ return status ? `${request} returned ${status}` : request;
1882
+ }
1883
+ function findException(events) {
1884
+ return events.find((event) => event.name === "exception")?.attributes;
1885
+ }
1886
+ function stringAttribute(attributes, key) {
1887
+ const value = attributes?.[key];
1888
+ return typeof value === "string" ? value : void 0;
1889
+ }
1890
+ function numberAttribute(attributes, key) {
1891
+ const value = attributes?.[key];
1892
+ return typeof value === "number" ? value : void 0;
1893
+ }
1894
+ //#endregion
1895
+ export { isLoopbackHost as a, startDevDashboard as i, DocsHost as n, openHistory as o, DEFAULT_DASHBOARD_PORT as r, DevTelemetryStore as t };
1896
+
1897
+ //# sourceMappingURL=dev-telemetry-store.js.map