@crvouga/mockingbird-service-slack 1.3.0 → 1.4.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.
@@ -38,30 +38,30 @@ var createClock = (source = Date.now) => {
38
38
  var Collection = class {
39
39
  sqlite;
40
40
  namespace;
41
- name;
42
- constructor(sqlite, namespace, name) {
41
+ collectionName;
42
+ constructor(sqlite, namespace, collectionName) {
43
43
  this.sqlite = sqlite;
44
44
  this.namespace = namespace;
45
- this.name = name;
45
+ this.collectionName = collectionName;
46
46
  }
47
47
  bumpCollectionSeq() {
48
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
48
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.collectionName);
49
49
  const next = (row?.value ?? 0) + 1;
50
50
  this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
51
- ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
51
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.collectionName, next);
52
52
  return next;
53
53
  }
54
54
  nextSequence() {
55
55
  return this.sqlite.transaction(() => this.bumpCollectionSeq());
56
56
  }
57
57
  get(id) {
58
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
58
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
59
59
  if (!row)
60
60
  return void 0;
61
61
  return JSON.parse(row.value).value;
62
62
  }
63
63
  has(id) {
64
- const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
64
+ const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
65
65
  return row !== void 0;
66
66
  }
67
67
  /** Insert a new record, assigning it the next sequence number. */
@@ -71,32 +71,32 @@ var Collection = class {
71
71
  const stored = { seq, value };
72
72
  this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
73
73
  VALUES (?, ?, ?, ?, ?)
74
- ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
74
+ ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.collectionName, id, seq, JSON.stringify(stored));
75
75
  return stored;
76
76
  });
77
77
  }
78
78
  /** Replace an existing record's value, keeping its position. */
79
79
  update(id, value) {
80
80
  return this.sqlite.transaction(() => {
81
- const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
81
+ const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
82
82
  if (!row)
83
83
  return void 0;
84
84
  const stored = { seq: row.seq, value };
85
- this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
85
+ this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.collectionName, id);
86
86
  return stored;
87
87
  });
88
88
  }
89
89
  delete(id) {
90
- const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
90
+ const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.collectionName, id);
91
91
  return result.changes > 0;
92
92
  }
93
93
  /** How many records the collection holds, without reading them. */
94
94
  count() {
95
- const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
95
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.collectionName);
96
96
  return Number(row?.n ?? 0);
97
97
  }
98
98
  list(options = {}) {
99
- const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
99
+ const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.collectionName);
100
100
  const out = [];
101
101
  for (const row of rows) {
102
102
  const stored = JSON.parse(row.value);
@@ -353,16 +353,18 @@ var createControlPlane = (context) => {
353
353
  uptimeMs: context.wallNow() - context.startedAt,
354
354
  clock: context.clock.state(),
355
355
  namespaces: context.namespaces().length,
356
+ adminUi: `${ADMIN_PREFIX}/ui`,
356
357
  ...context.describe()
357
358
  });
358
359
  }
359
360
  if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
360
361
  return void 0;
361
362
  }
362
- if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
364
+ const shell = request.method === "GET" && (path === "/ui" || path === "/ui/");
365
+ if (!shell && context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
366
  return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
364
367
  }
365
- const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
366
368
  for (const route of routes) {
367
369
  if (route.method !== request.method)
368
370
  continue;
@@ -1191,6 +1193,936 @@ var clearNamespace = (sqlite, namespace) => {
1191
1193
  });
1192
1194
  };
1193
1195
 
1196
+ // ../core/dist/surface.js
1197
+ var defineMock = (runtime) => runtime;
1198
+ var STANDARD_ADMIN_ROUTES = [
1199
+ "GET /",
1200
+ "POST /reset",
1201
+ "GET /namespaces",
1202
+ "GET /clock",
1203
+ "POST /clock",
1204
+ "GET /faults",
1205
+ "POST /faults",
1206
+ "DELETE /faults",
1207
+ "POST /snapshots",
1208
+ "POST /snapshots/:id/restore",
1209
+ "DELETE /snapshots/:id",
1210
+ "GET /timeline",
1211
+ "POST /checkpoints",
1212
+ "POST /branches/:name",
1213
+ "POST /branches/:name/checkout",
1214
+ "GET /requests",
1215
+ "DELETE /requests",
1216
+ "GET /metrics",
1217
+ "DELETE /metrics",
1218
+ "GET /credentials",
1219
+ "PUT /credentials",
1220
+ "DELETE /credentials",
1221
+ "GET /state",
1222
+ "GET /state/:collection",
1223
+ "GET /state/:collection/:id",
1224
+ "POST /state/:collection",
1225
+ "PUT /state/:collection/:id",
1226
+ "PATCH /state/:collection/:id",
1227
+ "DELETE /state/:collection/:id",
1228
+ "GET /ui",
1229
+ "GET /ui/",
1230
+ "GET /ui/manifest"
1231
+ ];
1232
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1233
+ var assertAdminUi = (ui) => {
1234
+ if (!ui?.panels)
1235
+ return;
1236
+ const seen = /* @__PURE__ */ new Set();
1237
+ for (const panel of ui.panels) {
1238
+ if (!PANEL_ID.test(panel.id)) {
1239
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1240
+ }
1241
+ if (seen.has(panel.id))
1242
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1243
+ seen.add(panel.id);
1244
+ if (panel.title.trim() === "")
1245
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1246
+ }
1247
+ };
1248
+
1249
+ // ../core/dist/admin-ui.js
1250
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1251
+ switch (char) {
1252
+ case "&":
1253
+ return "&amp;";
1254
+ case "<":
1255
+ return "&lt;";
1256
+ case ">":
1257
+ return "&gt;";
1258
+ case '"':
1259
+ return "&quot;";
1260
+ default:
1261
+ return "&#39;";
1262
+ }
1263
+ });
1264
+ var renderAdminDocument = (service) => {
1265
+ const name = escapeHtml(service);
1266
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1267
+ return `<!DOCTYPE html>
1268
+ <html lang="en">
1269
+ <head>
1270
+ <meta charset="utf-8">
1271
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1272
+ <meta name="color-scheme" content="light dark">
1273
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' rx='3' fill='%233d4f3a'/%3E%3C/svg%3E">
1274
+ <title>${name} admin</title>
1275
+ <style>
1276
+ :root {
1277
+ color-scheme: light;
1278
+ --bg: #f6f5f2;
1279
+ --bg-elev: #ffffff;
1280
+ --bg-muted: #eeece6;
1281
+ --bg-inset: #f3f1eb;
1282
+ --line: #e2dfd6;
1283
+ --line-strong: #d0ccc1;
1284
+ --ink: #1c1915;
1285
+ --muted: #5e584f;
1286
+ --faint: #8a8378;
1287
+ --accent: #3d4f3a;
1288
+ --accent-ink: #f7f6f2;
1289
+ --accent-soft: #e5ece2;
1290
+ --ok: #1f7a45;
1291
+ --ok-soft: #e5f4eb;
1292
+ --warn: #9a6700;
1293
+ --warn-soft: #fbf3df;
1294
+ --err: #a33b32;
1295
+ --err-soft: #fdecea;
1296
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1297
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1298
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1299
+ --radius: 14px;
1300
+ --header: 60px;
1301
+ --nav: 220px;
1302
+ }
1303
+ :root[data-theme="dark"] {
1304
+ color-scheme: dark;
1305
+ --bg: #141311;
1306
+ --bg-elev: #1e1c19;
1307
+ --bg-muted: #26231f;
1308
+ --bg-inset: #181715;
1309
+ --line: #34302b;
1310
+ --line-strong: #4a453d;
1311
+ --ink: #f4f1ea;
1312
+ --muted: #c4bdb1;
1313
+ --faint: #8f877c;
1314
+ --accent: #c5d5b8;
1315
+ --accent-ink: #1a2118;
1316
+ --accent-soft: #2a3328;
1317
+ --ok: #8fd6a8;
1318
+ --ok-soft: #1a2e22;
1319
+ --warn: #f0cc78;
1320
+ --warn-soft: #332911;
1321
+ --err: #f0a8a2;
1322
+ --err-soft: #3a201e;
1323
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1324
+ }
1325
+ @media (prefers-color-scheme: dark) {
1326
+ :root:not([data-theme="light"]) {
1327
+ color-scheme: dark;
1328
+ --bg: #141311;
1329
+ --bg-elev: #1e1c19;
1330
+ --bg-muted: #26231f;
1331
+ --bg-inset: #181715;
1332
+ --line: #34302b;
1333
+ --line-strong: #4a453d;
1334
+ --ink: #f4f1ea;
1335
+ --muted: #c4bdb1;
1336
+ --faint: #8f877c;
1337
+ --accent: #c5d5b8;
1338
+ --accent-ink: #1a2118;
1339
+ --accent-soft: #2a3328;
1340
+ --ok: #8fd6a8;
1341
+ --ok-soft: #1a2e22;
1342
+ --warn: #f0cc78;
1343
+ --warn-soft: #332911;
1344
+ --err: #f0a8a2;
1345
+ --err-soft: #3a201e;
1346
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1347
+ }
1348
+ }
1349
+ * { box-sizing: border-box; }
1350
+ html, body { margin: 0; height: 100%; }
1351
+ body {
1352
+ font-family: var(--sans);
1353
+ background: var(--bg);
1354
+ color: var(--ink);
1355
+ line-height: 1.45;
1356
+ padding-left: env(safe-area-inset-left);
1357
+ padding-right: env(safe-area-inset-right);
1358
+ -webkit-text-size-adjust: 100%;
1359
+ }
1360
+ button, input, select, textarea { font: inherit; color: inherit; }
1361
+ button { cursor: pointer; }
1362
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1363
+ @media (prefers-reduced-motion: reduce) {
1364
+ * { scroll-behavior: auto !important; transition: none !important; }
1365
+ }
1366
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1367
+ header.top {
1368
+ position: sticky; top: 0; z-index: 5;
1369
+ display: flex; align-items: center; gap: 12px;
1370
+ min-height: var(--header); padding: 10px 16px;
1371
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1372
+ border-bottom: 1px solid var(--line);
1373
+ backdrop-filter: blur(10px);
1374
+ }
1375
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1376
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1377
+ .brand span { color: var(--faint); font-size: 12px; }
1378
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1379
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1380
+ label.field input, label.field select, .controls input[type="password"] {
1381
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1382
+ padding: 7px 8px; min-height: 36px;
1383
+ }
1384
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1385
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1386
+ background: var(--bg-elev);
1387
+ }
1388
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1389
+ .btn-quiet { background: transparent; }
1390
+ .btn-danger { color: var(--err); }
1391
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1392
+ record or the full nav row would widen the page past the viewport. */
1393
+ .layout {
1394
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1395
+ flex: 1; min-height: 0; min-width: 0;
1396
+ }
1397
+ nav.side {
1398
+ border-right: 1px solid var(--line); padding: 12px;
1399
+ display: flex; flex-direction: column; gap: 4px;
1400
+ background: var(--bg-elev);
1401
+ }
1402
+ nav.side button {
1403
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1404
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1405
+ }
1406
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1407
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1408
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1409
+ .lede { margin: 0 0 16px; color: var(--muted); }
1410
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1411
+ .card {
1412
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1413
+ padding: 14px 16px; box-shadow: var(--shadow);
1414
+ }
1415
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1416
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1417
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1418
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1419
+ .collection {
1420
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1421
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1422
+ }
1423
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1424
+ .collection small { display: block; color: var(--faint); }
1425
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1426
+ .chip {
1427
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1428
+ border-radius: 999px; padding: 4px 8px;
1429
+ }
1430
+ .chip i { color: var(--faint); font-style: normal; }
1431
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1432
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1433
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1434
+ tr.clickable { cursor: pointer; }
1435
+ tr.clickable:hover { background: var(--bg-muted); }
1436
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1437
+ pre {
1438
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1439
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1440
+ }
1441
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1442
+ .banner {
1443
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1444
+ background: var(--err-soft); color: var(--err);
1445
+ }
1446
+ .banner.show { display: block; }
1447
+ .empty { color: var(--muted); padding: 24px 8px; }
1448
+ dialog {
1449
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1450
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1451
+ }
1452
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1453
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1454
+ textarea {
1455
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1456
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1457
+ font-family: var(--mono); font-size: 12px;
1458
+ }
1459
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1460
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1461
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1462
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1463
+ .status-2 { color: var(--ok); }
1464
+ .status-4, .status-5, .status-0 { color: var(--err); }
1465
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1466
+ .route {
1467
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1468
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1469
+ }
1470
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1471
+ @media (max-width: 800px) {
1472
+ header.top {
1473
+ align-items: stretch; flex-direction: column;
1474
+ padding-top: max(10px, env(safe-area-inset-top));
1475
+ }
1476
+ input, select, textarea { font-size: 16px; }
1477
+ .controls { width: 100%; }
1478
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1479
+ .layout { grid-template-columns: minmax(0, 1fr); }
1480
+ nav.side {
1481
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1482
+ border-right: 0; border-bottom: 1px solid var(--line);
1483
+ padding: 8px;
1484
+ }
1485
+ nav.side button { white-space: nowrap; flex: none; }
1486
+ .split { grid-template-columns: minmax(0, 1fr); }
1487
+ main { padding: 14px; }
1488
+ table, thead, tbody, tr, th, td { display: block; }
1489
+ thead { display: none; }
1490
+ tr {
1491
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1492
+ background: var(--bg-elev); min-width: 0;
1493
+ }
1494
+ td {
1495
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1496
+ min-width: 0; overflow-wrap: anywhere;
1497
+ }
1498
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1499
+ .route { grid-template-columns: 72px 1fr; }
1500
+ .route button { grid-column: 1 / -1; }
1501
+ }
1502
+ </style>
1503
+ </head>
1504
+ <body>
1505
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1506
+ <header class="top">
1507
+ <div class="brand">
1508
+ <strong>${name}</strong>
1509
+ <span>Mockingbird admin</span>
1510
+ </div>
1511
+ <div class="controls">
1512
+ <label class="field">Namespace
1513
+ <select id="namespace" aria-label="Namespace"></select>
1514
+ </label>
1515
+ <label class="field">Admin key
1516
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1517
+ </label>
1518
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1519
+ <button class="btn" id="refresh" type="button">Refresh</button>
1520
+ </div>
1521
+ </header>
1522
+ <div class="layout">
1523
+ <nav class="side" id="nav" aria-label="Admin sections">
1524
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1525
+ <button type="button" data-view="state">State</button>
1526
+ <button type="button" data-view="clock">Clock</button>
1527
+ <button type="button" data-view="faults">Faults</button>
1528
+ <button type="button" data-view="journal">Journal</button>
1529
+ <button type="button" data-view="routes">Routes</button>
1530
+ </nav>
1531
+ <main id="views">
1532
+ <p class="banner" id="banner" role="alert"></p>
1533
+ <section class="view" id="view-overview">
1534
+ <h2>Overview</h2>
1535
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1536
+ <div class="grid" id="overview-cards"></div>
1537
+ <h3>Recent requests</h3>
1538
+ <div id="overview-requests"></div>
1539
+ </section>
1540
+ <section class="view" id="view-state" hidden>
1541
+ <h2>State</h2>
1542
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1543
+ <div class="split">
1544
+ <div id="collections"></div>
1545
+ <div>
1546
+ <div id="schema"></div>
1547
+ <div class="row-actions">
1548
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1549
+ </div>
1550
+ <div id="records"></div>
1551
+ </div>
1552
+ </div>
1553
+ </section>
1554
+ <section class="view" id="view-clock" hidden>
1555
+ <h2>Clock</h2>
1556
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1557
+ <div class="card" id="clock-readout"></div>
1558
+ <div class="row-actions">
1559
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1560
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1561
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1562
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1563
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1564
+ <button class="btn" id="freeze" type="button">Freeze</button>
1565
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1566
+ </div>
1567
+ <form id="clock-set" class="row-actions">
1568
+ <label class="field">Set instant
1569
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1570
+ </label>
1571
+ <button class="btn-primary" type="submit">Set</button>
1572
+ </form>
1573
+ </section>
1574
+ <section class="view" id="view-faults" hidden>
1575
+ <h2>Faults</h2>
1576
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1577
+ <form id="fault-form" class="card stack">
1578
+ <label class="field">Preset
1579
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1580
+ </label>
1581
+ <label class="field">Status
1582
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1583
+ </label>
1584
+ <label class="field">Path prefix
1585
+ <input id="fault-path" placeholder="/v1">
1586
+ </label>
1587
+ <label class="field">Method
1588
+ <input id="fault-method" placeholder="GET">
1589
+ </label>
1590
+ <div class="dialog-actions">
1591
+ <button class="btn-primary" type="submit">Add fault</button>
1592
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1593
+ </div>
1594
+ </form>
1595
+ <div id="fault-list"></div>
1596
+ </section>
1597
+ <section class="view" id="view-journal" hidden>
1598
+ <h2>Journal</h2>
1599
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1600
+ <div class="row-actions">
1601
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1602
+ </div>
1603
+ <div id="journal"></div>
1604
+ </section>
1605
+ <section class="view" id="view-routes" hidden>
1606
+ <h2>Routes</h2>
1607
+ <p class="lede">Shared controls, plus any routes this mock adds. Extra routes are how a bespoke workflow shows up beside the default UI.</p>
1608
+ <div id="route-list"></div>
1609
+ <form id="route-form" class="card stack">
1610
+ <strong id="route-title">Select a route</strong>
1611
+ <label class="field">JSON body
1612
+ <textarea id="route-body" placeholder="{ }"></textarea>
1613
+ </label>
1614
+ <div class="dialog-actions">
1615
+ <button class="btn-primary" type="submit">Send</button>
1616
+ </div>
1617
+ <pre id="route-result">Response will show here.</pre>
1618
+ </form>
1619
+ </section>
1620
+ </main>
1621
+ </div>
1622
+ </div>
1623
+ <dialog id="editor">
1624
+ <form method="dialog" id="editor-form">
1625
+ <strong id="editor-title">Record</strong>
1626
+ <label class="field">Id
1627
+ <input id="editor-id" required>
1628
+ </label>
1629
+ <label class="field">JSON value
1630
+ <textarea id="editor-value"></textarea>
1631
+ </label>
1632
+ <div class="dialog-actions">
1633
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1634
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1635
+ <button class="btn-primary" type="submit" value="save">Save</button>
1636
+ </div>
1637
+ </form>
1638
+ </dialog>
1639
+ <script>
1640
+ (() => {
1641
+ const STANDARD = new Set(${standard})
1642
+ const state = {
1643
+ namespace: "default",
1644
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1645
+ view: "overview",
1646
+ collection: "",
1647
+ shape: null,
1648
+ route: null,
1649
+ editing: null
1650
+ }
1651
+ const $ = (id) => document.getElementById(id)
1652
+ const banner = $("banner")
1653
+ const keyInput = $("admin-key")
1654
+ keyInput.value = state.key
1655
+ const params = new URLSearchParams(location.search)
1656
+ if (params.get("key")) {
1657
+ state.key = params.get("key")
1658
+ keyInput.value = state.key
1659
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1660
+ params.delete("key")
1661
+ const next = params.toString()
1662
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1663
+ }
1664
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1665
+
1666
+ const showError = (error) => {
1667
+ banner.textContent = error instanceof Error ? error.message : String(error)
1668
+ banner.classList.add("show")
1669
+ }
1670
+ const clearError = () => banner.classList.remove("show")
1671
+
1672
+ async function originGet(path) {
1673
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1674
+ if (!response.ok) throw new Error(response.status + " " + path)
1675
+ return response.json()
1676
+ }
1677
+ async function api(method, path, body) {
1678
+ const headers = { accept: "application/json" }
1679
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1680
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1681
+ if (body !== undefined) headers["content-type"] = "application/json"
1682
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1683
+ method,
1684
+ headers,
1685
+ body: body === undefined ? undefined : JSON.stringify(body)
1686
+ })
1687
+ const text = await response.text()
1688
+ let data = null
1689
+ if (text) {
1690
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1691
+ }
1692
+ if (response.status === 401) {
1693
+ keyInput.focus()
1694
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1695
+ }
1696
+ if (!response.ok) {
1697
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1698
+ }
1699
+ return data
1700
+ }
1701
+ const panelApi = {
1702
+ get: (path) => api("GET", path),
1703
+ send: (method, path, body) => api(method, path, body),
1704
+ namespace: () => state.namespace
1705
+ }
1706
+
1707
+ function setTheme(theme) {
1708
+ if (theme) document.documentElement.dataset.theme = theme
1709
+ else delete document.documentElement.dataset.theme
1710
+ }
1711
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1712
+ if (storedTheme) setTheme(storedTheme)
1713
+ $("theme").addEventListener("click", () => {
1714
+ const current = document.documentElement.dataset.theme
1715
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1716
+ const next = dark ? "light" : "dark"
1717
+ localStorage.setItem("mockingbird-admin-theme", next)
1718
+ setTheme(next)
1719
+ })
1720
+
1721
+ function show(view) {
1722
+ state.view = view
1723
+ for (const button of document.querySelectorAll("#nav button")) {
1724
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1725
+ }
1726
+ for (const section of document.querySelectorAll("main .view")) {
1727
+ section.hidden = section.id !== "view-" + view
1728
+ }
1729
+ }
1730
+ document.getElementById("nav").addEventListener("click", (event) => {
1731
+ const button = event.target.closest("button[data-view]")
1732
+ if (!button) return
1733
+ show(button.dataset.view)
1734
+ refresh().catch(showError)
1735
+ })
1736
+
1737
+ function cards(items) {
1738
+ return '<div class="grid">' + items.map((item) =>
1739
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1740
+ ).join("") + "</div>"
1741
+ }
1742
+ function table(columns, rows) {
1743
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1744
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1745
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1746
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1747
+ ).join("") + "</tr>").join("")
1748
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1749
+ }
1750
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1751
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1752
+ }[char]))
1753
+ const preview = (value) => {
1754
+ const text = JSON.stringify(value)
1755
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1756
+ }
1757
+ const when = (epoch) => {
1758
+ const date = new Date(epoch)
1759
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1760
+ }
1761
+ const clockCard = (epoch) => {
1762
+ const date = new Date(epoch)
1763
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1764
+ const iso = date.toISOString()
1765
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1766
+ }
1767
+
1768
+ async function loadNamespaces() {
1769
+ const data = await api("GET", "/namespaces")
1770
+ const select = $("namespace")
1771
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1772
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1773
+ select.innerHTML = names.map((name) =>
1774
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1775
+ ).join("")
1776
+ select.value = state.namespace
1777
+ }
1778
+
1779
+ async function renderOverview() {
1780
+ const [health, shape, clock, journal] = await Promise.all([
1781
+ originGet("/health"),
1782
+ api("GET", "/state"),
1783
+ api("GET", "/clock"),
1784
+ api("GET", "/requests?limit=8")
1785
+ ])
1786
+ state.shape = shape
1787
+ $("overview-cards").innerHTML = cards([
1788
+ { k: "Service", v: esc(health.service || "${name}") },
1789
+ { k: "Status", v: esc(health.status || "ok") },
1790
+ { k: "Namespace", v: esc(state.namespace) },
1791
+ { k: "Collections", v: String(shape.collections.length) },
1792
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1793
+ { k: "Clock", v: clockCard(clock.now) }
1794
+ ])
1795
+ const requests = (journal && journal.requests) || []
1796
+ $("overview-requests").innerHTML = table(
1797
+ [
1798
+ { label: "Method", cell: (row) => esc(row.method) },
1799
+ { label: "Path", cell: (row) => esc(row.path) },
1800
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1801
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1802
+ ],
1803
+ requests
1804
+ )
1805
+ }
1806
+
1807
+ function schemaChips(collection) {
1808
+ if (!collection || collection.fields.length === 0) {
1809
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
1810
+ }
1811
+ return '<div class="chips">' + collection.fields.map((field) =>
1812
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
1813
+ ).join("") + "</div>"
1814
+ }
1815
+
1816
+ async function renderState() {
1817
+ const shape = await api("GET", "/state")
1818
+ state.shape = shape
1819
+ const host = $("collections")
1820
+ if (shape.collections.length === 0) {
1821
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
1822
+ $("schema").innerHTML = ""
1823
+ $("records").innerHTML = ""
1824
+ return
1825
+ }
1826
+ if (!shape.collections.some((item) => item.name === state.collection)) {
1827
+ state.collection = shape.collections[0].name
1828
+ }
1829
+ host.innerHTML = shape.collections.map((item) =>
1830
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
1831
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
1832
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
1833
+ ).join("")
1834
+ const selected = shape.collections.find((item) => item.name === state.collection)
1835
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
1836
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
1837
+ schemaChips(selected)
1838
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
1839
+ const rows = page.records.map((record) => ({
1840
+ ...record,
1841
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
1842
+ }))
1843
+ $("records").innerHTML = table(
1844
+ [
1845
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
1846
+ { label: "Seq", cell: (row) => esc(row.seq) },
1847
+ { label: "Value", cell: (row) => preview(row.value) }
1848
+ ],
1849
+ rows
1850
+ )
1851
+ }
1852
+
1853
+ async function renderClock() {
1854
+ const clock = await api("GET", "/clock")
1855
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
1856
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
1857
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
1858
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
1859
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
1860
+ }
1861
+
1862
+ async function renderFaults() {
1863
+ const [faults, presets] = await Promise.all([
1864
+ api("GET", "/faults"),
1865
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
1866
+ ])
1867
+ const select = $("fault-preset")
1868
+ const current = select.value
1869
+ const list = presets.presets || []
1870
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
1871
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
1872
+ ).join("")
1873
+ select.value = current
1874
+ const rules = faults.faults || []
1875
+ $("fault-list").innerHTML = table(
1876
+ [
1877
+ { label: "Id", cell: (row) => esc(row.id) },
1878
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
1879
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
1880
+ ],
1881
+ rules
1882
+ )
1883
+ }
1884
+
1885
+ async function renderJournal() {
1886
+ const journal = await api("GET", "/requests?limit=100")
1887
+ $("journal").innerHTML = table(
1888
+ [
1889
+ { label: "When", cell: (row) => esc(row.at || "") },
1890
+ { label: "Method", cell: (row) => esc(row.method) },
1891
+ { label: "Path", cell: (row) => esc(row.path) },
1892
+ { label: "Status", cell: (row) => esc(row.status) },
1893
+ { label: "ms", cell: (row) => esc(row.durationMs) }
1894
+ ],
1895
+ journal.requests || []
1896
+ )
1897
+ }
1898
+
1899
+ async function renderRoutes() {
1900
+ const data = await api("GET", "/")
1901
+ const routes = data.routes || []
1902
+ $("route-list").innerHTML = routes.map((route) => {
1903
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
1904
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
1905
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
1906
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
1907
+ }).join("")
1908
+ }
1909
+
1910
+ const renderers = {
1911
+ overview: renderOverview,
1912
+ state: renderState,
1913
+ clock: renderClock,
1914
+ faults: renderFaults,
1915
+ journal: renderJournal,
1916
+ routes: renderRoutes
1917
+ }
1918
+
1919
+ async function refresh() {
1920
+ clearError()
1921
+ if (state.view in renderers) await renderers[state.view]()
1922
+ }
1923
+
1924
+ $("namespace").addEventListener("change", () => {
1925
+ state.namespace = $("namespace").value
1926
+ refresh().catch(showError)
1927
+ })
1928
+ keyInput.addEventListener("change", () => {
1929
+ state.key = keyInput.value.trim()
1930
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1931
+ refresh().catch(showError)
1932
+ })
1933
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
1934
+
1935
+ $("collections").addEventListener("click", (event) => {
1936
+ const button = event.target.closest("[data-collection]")
1937
+ if (!button) return
1938
+ state.collection = button.dataset.collection
1939
+ renderState().catch(showError)
1940
+ })
1941
+ $("records").addEventListener("click", (event) => {
1942
+ const row = event.target.closest("[data-id]")
1943
+ if (!row) return
1944
+ openEditor(row.dataset.id).catch(showError)
1945
+ })
1946
+
1947
+ const editor = $("editor")
1948
+ async function openEditor(id) {
1949
+ state.editing = id || null
1950
+ $("editor-title").textContent = id ? "Edit record" : "New record"
1951
+ $("editor-id").value = id || ""
1952
+ $("editor-id").readOnly = Boolean(id)
1953
+ $("editor-delete").hidden = !id
1954
+ if (id) {
1955
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1956
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
1957
+ } else {
1958
+ $("editor-value").value = "{\\n \\n}"
1959
+ }
1960
+ editor.showModal()
1961
+ }
1962
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
1963
+ $("editor-form").addEventListener("submit", (event) => {
1964
+ const submitter = event.submitter
1965
+ if (!submitter || submitter.value !== "save") return
1966
+ event.preventDefault()
1967
+ let value
1968
+ try { value = JSON.parse($("editor-value").value) }
1969
+ catch { showError(new Error("Value is not JSON")); return }
1970
+ const id = $("editor-id").value.trim()
1971
+ const path = "/state/" + encodeURIComponent(state.collection)
1972
+ const request = state.editing
1973
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
1974
+ : api("POST", path, { id: id || undefined, value })
1975
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
1976
+ })
1977
+ $("editor-delete").addEventListener("click", () => {
1978
+ const id = state.editing
1979
+ if (!id) return
1980
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1981
+ .then(() => { editor.close(); return renderState() })
1982
+ .catch(showError)
1983
+ })
1984
+
1985
+ document.querySelectorAll("[data-advance]").forEach((button) => {
1986
+ button.addEventListener("click", () => {
1987
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
1988
+ })
1989
+ })
1990
+ $("freeze").addEventListener("click", () => {
1991
+ const frozen = $("freeze").dataset.frozen === "1"
1992
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
1993
+ })
1994
+ $("clock-reset").addEventListener("click", () => {
1995
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
1996
+ })
1997
+ $("clock-set").addEventListener("submit", (event) => {
1998
+ event.preventDefault()
1999
+ const raw = $("clock-instant").value.trim()
2000
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
2001
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
2002
+ })
2003
+
2004
+ $("fault-form").addEventListener("submit", (event) => {
2005
+ event.preventDefault()
2006
+ const preset = $("fault-preset").value
2007
+ const body = preset
2008
+ ? { preset }
2009
+ : {
2010
+ status: Number($("fault-status").value),
2011
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
2012
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
2013
+ }
2014
+ if (!preset && !Number.isFinite(body.status)) {
2015
+ showError(new Error("Status must be a number, or choose a preset"))
2016
+ return
2017
+ }
2018
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
2019
+ })
2020
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
2021
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
2022
+
2023
+ $("route-list").addEventListener("click", (event) => {
2024
+ const button = event.target.closest("[data-route]")
2025
+ if (!button) return
2026
+ state.route = button.dataset.route
2027
+ $("route-title").textContent = state.route
2028
+ const method = state.route.split(" ")[0]
2029
+ $("route-body").disabled = method === "GET" || method === "DELETE"
2030
+ })
2031
+ $("route-form").addEventListener("submit", async (event) => {
2032
+ event.preventDefault()
2033
+ if (!state.route) return showError(new Error("Choose a route first"))
2034
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
2035
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
2036
+ let body
2037
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
2038
+ try { body = JSON.parse($("route-body").value) }
2039
+ catch { return showError(new Error("Body is not JSON")) }
2040
+ }
2041
+ try {
2042
+ const data = await api(method, concrete, body)
2043
+ $("route-result").textContent = JSON.stringify(data, null, 2)
2044
+ } catch (error) {
2045
+ showError(error)
2046
+ }
2047
+ })
2048
+
2049
+ function mountPanels(panels) {
2050
+ const nav = $("nav")
2051
+ const views = $("views")
2052
+ for (const panel of panels) {
2053
+ const button = document.createElement("button")
2054
+ button.type = "button"
2055
+ button.dataset.view = panel.id
2056
+ button.textContent = panel.title
2057
+ nav.append(button)
2058
+ const section = document.createElement("section")
2059
+ section.className = "view"
2060
+ section.id = "view-" + panel.id
2061
+ section.hidden = true
2062
+ const title = document.createElement("h2")
2063
+ title.textContent = panel.title
2064
+ const lede = document.createElement("p")
2065
+ lede.className = "lede"
2066
+ lede.textContent = panel.description || ""
2067
+ const body = document.createElement("div")
2068
+ body.className = "panel-body"
2069
+ body.id = "panel-" + panel.id
2070
+ body.innerHTML = panel.html || ""
2071
+ section.append(title, lede, body)
2072
+ views.append(section)
2073
+ if (panel.script) {
2074
+ try {
2075
+ const run = new Function("root", "api", panel.script)
2076
+ run(body, panelApi)
2077
+ } catch (error) {
2078
+ const note = document.createElement("p")
2079
+ note.className = "banner show"
2080
+ note.textContent = error instanceof Error ? error.message : String(error)
2081
+ body.append(note)
2082
+ }
2083
+ }
2084
+ }
2085
+ }
2086
+
2087
+ loadNamespaces()
2088
+ .then(() => api("GET", "/ui/manifest"))
2089
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2090
+ .catch(showError)
2091
+ })()
2092
+ </script>
2093
+ </body>
2094
+ </html>`;
2095
+ };
2096
+ var htmlResponse = (body) => new Response(body, {
2097
+ status: 200,
2098
+ headers: {
2099
+ "content-type": "text/html; charset=utf-8",
2100
+ "cache-control": "no-store"
2101
+ }
2102
+ });
2103
+ var json3 = (body) => new Response(JSON.stringify(body), {
2104
+ status: 200,
2105
+ headers: { "content-type": "application/json; charset=utf-8" }
2106
+ });
2107
+ var adminUiRoutes = (service, ui) => {
2108
+ const shell = () => renderAdminDocument(service);
2109
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2110
+ return {
2111
+ "GET /ui": () => htmlResponse(document2()),
2112
+ "GET /ui/": () => htmlResponse(document2()),
2113
+ "GET /ui/manifest": () => json3({
2114
+ service,
2115
+ panels: (ui?.panels ?? []).map((panel) => ({
2116
+ id: panel.id,
2117
+ title: panel.title,
2118
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2119
+ html: panel.html,
2120
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2121
+ }))
2122
+ })
2123
+ };
2124
+ };
2125
+
1194
2126
  // ../../openapi/metadata/dist/types.js
1195
2127
  var EXTENSION_KEYS = {
1196
2128
  operation: "x-mockingbird",
@@ -1354,15 +2286,449 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1354
2286
  });
1355
2287
  };
1356
2288
 
2289
+ // ../core/dist/state-view.js
2290
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2291
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2292
+ var SAMPLE = 25;
2293
+ var WALK_LIMIT = 1e4;
2294
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2295
+ var fail = (status, message) => ({ ok: false, status, message });
2296
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2297
+ var kindOf = (value) => {
2298
+ if (value === null)
2299
+ return "null";
2300
+ if (Array.isArray(value))
2301
+ return "array";
2302
+ switch (typeof value) {
2303
+ case "string":
2304
+ return "string";
2305
+ case "number":
2306
+ return Number.isFinite(value) ? "number" : "unknown";
2307
+ case "boolean":
2308
+ return "boolean";
2309
+ case "object":
2310
+ return "object";
2311
+ default:
2312
+ return "unknown";
2313
+ }
2314
+ };
2315
+ var humanize = (name) => {
2316
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2317
+ if (words === "")
2318
+ return name;
2319
+ return words.charAt(0).toUpperCase() + words.slice(1);
2320
+ };
2321
+ var jsonValue = (value) => {
2322
+ if (value === void 0)
2323
+ return fail(400, "value is required");
2324
+ try {
2325
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2326
+ } catch {
2327
+ return fail(400, "value must be JSON");
2328
+ }
2329
+ };
2330
+ var ctorName = (value) => {
2331
+ const ctor = value.constructor;
2332
+ return typeof ctor?.name === "string" ? ctor.name : "";
2333
+ };
2334
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2335
+ var discoverCollections = (root) => {
2336
+ const found = [];
2337
+ const seen = /* @__PURE__ */ new Set();
2338
+ const visit = (value, depth) => {
2339
+ if (found.length + seen.size > WALK_LIMIT)
2340
+ return;
2341
+ if (value === null || typeof value !== "object")
2342
+ return;
2343
+ if (seen.has(value))
2344
+ return;
2345
+ seen.add(value);
2346
+ if (value instanceof Collection) {
2347
+ found.push(value);
2348
+ return;
2349
+ }
2350
+ if (value instanceof Map) {
2351
+ for (const child of value.values())
2352
+ visit(child, depth + 1);
2353
+ return;
2354
+ }
2355
+ if (value instanceof Set) {
2356
+ for (const child of value.values())
2357
+ visit(child, depth + 1);
2358
+ return;
2359
+ }
2360
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2361
+ return;
2362
+ if (Array.isArray(value)) {
2363
+ const cap = Math.min(value.length, 32);
2364
+ for (let i = 0; i < cap; i++)
2365
+ visit(value[i], depth + 1);
2366
+ return;
2367
+ }
2368
+ let children;
2369
+ try {
2370
+ children = Object.values(value);
2371
+ } catch {
2372
+ return;
2373
+ }
2374
+ for (const child of children)
2375
+ visit(child, depth + 1);
2376
+ };
2377
+ visit(root, 0);
2378
+ return found;
2379
+ };
2380
+ var storedNames = (sqlite, namespace) => {
2381
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2382
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2383
+ return [...records, ...sequences].map((row) => row.name);
2384
+ };
2385
+ var blankAccum = (name) => ({
2386
+ name,
2387
+ kinds: /* @__PURE__ */ new Set(),
2388
+ present: 0,
2389
+ nested: /* @__PURE__ */ new Map()
2390
+ });
2391
+ var absorb = (accum, value) => {
2392
+ const kind = kindOf(value);
2393
+ accum.kinds.add(kind);
2394
+ accum.present++;
2395
+ if (!isRecord3(value))
2396
+ return;
2397
+ for (const [key, child] of Object.entries(value)) {
2398
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2399
+ absorb(nested, child);
2400
+ accum.nested.set(key, nested);
2401
+ }
2402
+ };
2403
+ var finishField = (accum, samples) => {
2404
+ const kinds = [...accum.kinds];
2405
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2406
+ const field = {
2407
+ name: accum.name,
2408
+ kind,
2409
+ optional: accum.present < samples || kinds.includes("null")
2410
+ };
2411
+ if (accum.nested.size > 0) {
2412
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2413
+ }
2414
+ return field;
2415
+ };
2416
+ var inferFields = (records) => {
2417
+ if (records.length === 0)
2418
+ return [];
2419
+ const sample = records.slice(0, SAMPLE);
2420
+ const objects = sample.filter((record) => isRecord3(record.value));
2421
+ if (objects.length === 0) {
2422
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2423
+ const list2 = [...kinds];
2424
+ return [
2425
+ {
2426
+ name: "(value)",
2427
+ kind: list2.length === 1 ? list2[0] : "unknown",
2428
+ optional: false
2429
+ }
2430
+ ];
2431
+ }
2432
+ const root = /* @__PURE__ */ new Map();
2433
+ for (const record of objects) {
2434
+ for (const [key, value] of Object.entries(record.value)) {
2435
+ const accum = root.get(key) ?? blankAccum(key);
2436
+ absorb(accum, value);
2437
+ root.set(key, accum);
2438
+ }
2439
+ }
2440
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2441
+ };
2442
+ var mergeFields = (declared, inferred) => {
2443
+ const byName = /* @__PURE__ */ new Map();
2444
+ for (const field of inferred)
2445
+ byName.set(field.name, field);
2446
+ const ordered = [];
2447
+ const seen = /* @__PURE__ */ new Set();
2448
+ for (const field of declared ?? []) {
2449
+ const found = byName.get(field.name);
2450
+ seen.add(field.name);
2451
+ if (!found) {
2452
+ ordered.push({ ...field, optional: field.optional });
2453
+ continue;
2454
+ }
2455
+ ordered.push({
2456
+ ...found,
2457
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2458
+ optional: field.optional || found.optional,
2459
+ ...field.description !== void 0 ? { description: field.description } : {},
2460
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2461
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2462
+ });
2463
+ }
2464
+ for (const field of inferred) {
2465
+ if (!seen.has(field.name))
2466
+ ordered.push(field);
2467
+ }
2468
+ return ordered;
2469
+ };
2470
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2471
+ var readRecord = (collection, id) => {
2472
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2473
+ const row = rows.find((entry) => entry.id === id);
2474
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2475
+ };
2476
+ var inspectState = (scope) => {
2477
+ const declared = /* @__PURE__ */ new Map();
2478
+ for (const declaration of scope.declarations ?? []) {
2479
+ if (COLLECTION_NAME.test(declaration.name))
2480
+ declared.set(declaration.name, declaration);
2481
+ }
2482
+ const names = new Set(declared.keys());
2483
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2484
+ names.add(name);
2485
+ for (const collection of discoverCollections(scope.root)) {
2486
+ if (collection.namespace === scope.storageNamespace)
2487
+ names.add(collection.collectionName);
2488
+ }
2489
+ const collections = [];
2490
+ for (const name of names) {
2491
+ if (!COLLECTION_NAME.test(name))
2492
+ continue;
2493
+ const declaration = declared.get(name);
2494
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2495
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2496
+ const inferred = inferFields(records);
2497
+ const fields = mergeFields(declaration?.fields, inferred);
2498
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2499
+ collections.push({
2500
+ name,
2501
+ label: declaration?.label ?? humanize(name),
2502
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2503
+ count: collection.count(),
2504
+ source,
2505
+ fields,
2506
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2507
+ });
2508
+ }
2509
+ const order = /* @__PURE__ */ new Map();
2510
+ for (const [index, item] of (scope.declarations ?? []).entries())
2511
+ order.set(item.name, index);
2512
+ collections.sort((a, b) => {
2513
+ const left = order.get(a.name);
2514
+ const right = order.get(b.name);
2515
+ if (left !== void 0 && right !== void 0)
2516
+ return left - right;
2517
+ if (left !== void 0)
2518
+ return -1;
2519
+ if (right !== void 0)
2520
+ return 1;
2521
+ return a.name.localeCompare(b.name);
2522
+ });
2523
+ return {
2524
+ namespace: scope.namespace,
2525
+ storageNamespace: scope.storageNamespace,
2526
+ collections
2527
+ };
2528
+ };
2529
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2530
+ if (!COLLECTION_NAME.test(name))
2531
+ return fail(400, "collection name is not allowed");
2532
+ const limit = query.limit ?? 50;
2533
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2534
+ return fail(400, "limit must be an integer from 1 to 200");
2535
+ }
2536
+ const order = query.order ?? "newest";
2537
+ if (order !== "newest" && order !== "oldest")
2538
+ return fail(400, 'order must be "newest" or "oldest"');
2539
+ const collection = collectionOf(sqlite, storageNamespace, name);
2540
+ const rows = collection.list({ order }).filter((row) => {
2541
+ if (query.after === void 0)
2542
+ return true;
2543
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2544
+ });
2545
+ const slice = rows.slice(0, limit);
2546
+ const last = slice.at(-1);
2547
+ return {
2548
+ ok: true,
2549
+ value: {
2550
+ collection: name,
2551
+ count: collection.count(),
2552
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2553
+ next: rows.length > limit && last ? last.seq : null
2554
+ }
2555
+ };
2556
+ };
2557
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2558
+ var readStateRecord = (scope, name, id) => {
2559
+ if (!COLLECTION_NAME.test(name))
2560
+ return fail(400, "collection name is not allowed");
2561
+ if (!RECORD_ID.test(id))
2562
+ return fail(400, "record id is not allowed");
2563
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2564
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
2565
+ };
2566
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2567
+ var createStateRecord = (scope, name, input) => {
2568
+ if (!COLLECTION_NAME.test(name))
2569
+ return fail(400, "collection name is not allowed");
2570
+ const parsed = jsonValue(input.value);
2571
+ if (!parsed.ok)
2572
+ return parsed;
2573
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2574
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2575
+ const checked = requireId(id);
2576
+ if (!checked.ok)
2577
+ return checked;
2578
+ if (collection.has(checked.value))
2579
+ return fail(409, `record ${checked.value} already exists`);
2580
+ const stored = collection.insert(checked.value, parsed.value);
2581
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2582
+ };
2583
+ var replaceStateRecord = (scope, name, id, value) => {
2584
+ if (!COLLECTION_NAME.test(name))
2585
+ return fail(400, "collection name is not allowed");
2586
+ const checked = requireId(id);
2587
+ if (!checked.ok)
2588
+ return checked;
2589
+ const parsed = jsonValue(value);
2590
+ if (!parsed.ok)
2591
+ return parsed;
2592
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2593
+ if (!collection.has(checked.value))
2594
+ return fail(404, `no record ${checked.value} in ${name}`);
2595
+ const stored = collection.update(checked.value, parsed.value);
2596
+ if (!stored)
2597
+ return fail(404, `no record ${checked.value} in ${name}`);
2598
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2599
+ };
2600
+ var patchStateRecord = (scope, name, id, value) => {
2601
+ const current = readStateRecord(scope, name, id);
2602
+ if (!current.ok)
2603
+ return current;
2604
+ const parsed = jsonValue(value);
2605
+ if (!parsed.ok)
2606
+ return parsed;
2607
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2608
+ return replaceStateRecord(scope, name, id, next);
2609
+ };
2610
+ var deleteStateRecord = (scope, name, id) => {
2611
+ if (!COLLECTION_NAME.test(name))
2612
+ return fail(400, "collection name is not allowed");
2613
+ const checked = requireId(id);
2614
+ if (!checked.ok)
2615
+ return checked;
2616
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2617
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2618
+ };
2619
+ var json4 = (status, body) => new Response(JSON.stringify(body), {
2620
+ status,
2621
+ headers: { "content-type": "application/json; charset=utf-8" }
2622
+ });
2623
+ var adminError2 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2624
+ var fromResult = (result, status) => result.ok ? json4(status, result.value) : adminError2(result.status, result.message);
2625
+ var integerParam = (value) => {
2626
+ if (value === null)
2627
+ return void 0;
2628
+ if (!/^-?\d+$/.test(value))
2629
+ return "bad";
2630
+ return Number(value);
2631
+ };
2632
+ var stateAdminRoutes = (routes) => {
2633
+ const open = (namespace) => {
2634
+ try {
2635
+ return { ok: true, value: routes.open(namespace) };
2636
+ } catch (error) {
2637
+ return fail(400, error instanceof Error ? error.message : String(error));
2638
+ }
2639
+ };
2640
+ const wrote = (namespace) => {
2641
+ routes.afterWrite?.(namespace);
2642
+ };
2643
+ return {
2644
+ "GET /state": ({ namespace }) => {
2645
+ const scope = open(namespace);
2646
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2647
+ },
2648
+ "GET /state/:collection": ({ namespace, params, url }) => {
2649
+ const scope = open(namespace);
2650
+ if (!scope.ok)
2651
+ return fromResult(scope, 200);
2652
+ const limit = integerParam(url.searchParams.get("limit"));
2653
+ const after = integerParam(url.searchParams.get("after"));
2654
+ if (limit === "bad")
2655
+ return adminError2(400, "limit: expected an integer");
2656
+ if (after === "bad")
2657
+ return adminError2(400, "after: expected a sequence number");
2658
+ const order = url.searchParams.get("order");
2659
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2660
+ ...limit !== void 0 ? { limit } : {},
2661
+ ...after !== void 0 ? { after } : {},
2662
+ ...order === "newest" || order === "oldest" ? { order } : {}
2663
+ }), 200);
2664
+ },
2665
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2666
+ const scope = open(namespace);
2667
+ if (!scope.ok)
2668
+ return fromResult(scope, 200);
2669
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2670
+ },
2671
+ "POST /state/:collection": ({ namespace, params, body }) => {
2672
+ const scope = open(namespace);
2673
+ if (!scope.ok)
2674
+ return fromResult(scope, 201);
2675
+ if (!isRecord3(body) || !("value" in body)) {
2676
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2677
+ }
2678
+ const id = body.id;
2679
+ if (id !== void 0 && typeof id !== "string")
2680
+ return adminError2(400, "id must be a string");
2681
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2682
+ ...typeof id === "string" ? { id } : {},
2683
+ value: body.value
2684
+ });
2685
+ if (created.ok)
2686
+ wrote(namespace);
2687
+ return fromResult(created, 201);
2688
+ },
2689
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2690
+ const scope = open(namespace);
2691
+ if (!scope.ok)
2692
+ return fromResult(scope, 200);
2693
+ if (!isRecord3(body) || !("value" in body))
2694
+ return adminError2(400, 'expected {"value": <json>}');
2695
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2696
+ if (replaced.ok)
2697
+ wrote(namespace);
2698
+ return fromResult(replaced, 200);
2699
+ },
2700
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2701
+ const scope = open(namespace);
2702
+ if (!scope.ok)
2703
+ return fromResult(scope, 200);
2704
+ if (!isRecord3(body) || !("value" in body))
2705
+ return adminError2(400, 'expected {"value": <json>}');
2706
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2707
+ if (patched.ok)
2708
+ wrote(namespace);
2709
+ return fromResult(patched, 200);
2710
+ },
2711
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2712
+ const scope = open(namespace);
2713
+ if (!scope.ok)
2714
+ return fromResult(scope, 200);
2715
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2716
+ if (removed.ok)
2717
+ wrote(namespace);
2718
+ return fromResult(removed, 200);
2719
+ }
2720
+ };
2721
+ };
2722
+
1357
2723
  // ../core/dist/version.js
1358
- var PACKAGE_VERSION = true ? "1.3.0" : UNRELEASED_VERSION;
2724
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1359
2725
 
1360
2726
  // ../core/dist/webhooks.js
1361
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1362
- var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
1363
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2727
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2728
+ var adminError3 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
2729
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1364
2730
  var parseEndpoint = (value) => {
1365
- if (!isRecord3(value) || typeof value.url !== "string")
2731
+ if (!isRecord4(value) || typeof value.url !== "string")
1366
2732
  return "each endpoint needs a url";
1367
2733
  try {
1368
2734
  new URL(value.url);
@@ -1379,18 +2745,18 @@ var parseEndpoint = (value) => {
1379
2745
  const events = value.events ?? value.enabledEvents;
1380
2746
  if (Array.isArray(events))
1381
2747
  endpoint.events = events.map(String);
1382
- if (isRecord3(value.tags)) {
2748
+ if (isRecord4(value.tags)) {
1383
2749
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1384
2750
  }
1385
2751
  if (typeof value.account === "string")
1386
2752
  endpoint.tags = { ...endpoint.tags, account: value.account };
1387
- if (isRecord3(value.headers)) {
2753
+ if (isRecord4(value.headers)) {
1388
2754
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1389
2755
  }
1390
2756
  return endpoint;
1391
2757
  };
1392
2758
  var webhookAdminRoutes = (hub) => ({
1393
- "GET /webhooks": ({ url, namespace }) => json3(200, {
2759
+ "GET /webhooks": ({ url, namespace }) => json5(200, {
1394
2760
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1395
2761
  const type = url.searchParams.get("type");
1396
2762
  return type === null || d.type === type;
@@ -1398,51 +2764,51 @@ var webhookAdminRoutes = (hub) => ({
1398
2764
  }),
1399
2765
  "GET /webhooks/events": ({ url, namespace }) => {
1400
2766
  const type = url.searchParams.get("type");
1401
- return json3(200, {
2767
+ return json5(200, {
1402
2768
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1403
2769
  });
1404
2770
  },
1405
2771
  "POST /webhooks/:id/replay": async ({ params }) => {
1406
2772
  const replayed = await hub.replay(params.id);
1407
- return replayed ? json3(200, replayed) : adminError2(404, `no delivery ${params.id}`);
2773
+ return replayed ? json5(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1408
2774
  },
1409
2775
  "POST /webhooks/flush": async () => {
1410
2776
  await hub.flush();
1411
- return json3(200, { status: "ok" });
2777
+ return json5(200, { status: "ok" });
1412
2778
  },
1413
2779
  "POST /webhooks/faults": ({ body, namespace }) => {
1414
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1415
- return adminError2(400, "mode must be duplicate, reorder or drop");
2780
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2781
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1416
2782
  }
1417
2783
  const fault = { mode: body.mode };
1418
2784
  if (typeof body.count === "number")
1419
2785
  fault.count = body.count;
1420
2786
  hub.fault(namespace, fault);
1421
- return json3(201, { namespace, ...fault });
2787
+ return json5(201, { namespace, ...fault });
1422
2788
  },
1423
- "GET /webhook-endpoints": ({ namespace }) => json3(200, {
2789
+ "GET /webhook-endpoints": ({ namespace }) => json5(200, {
1424
2790
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1425
2791
  ...rest,
1426
2792
  secret: secret ? "(set)" : null
1427
2793
  }))
1428
2794
  }),
1429
2795
  "PUT /webhook-endpoints": ({ body, namespace }) => {
1430
- const list2 = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
2796
+ const list2 = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
1431
2797
  if (!Array.isArray(list2))
1432
- return adminError2(400, "expected [{url, secret?, events?}]");
2798
+ return adminError3(400, "expected [{url, secret?, events?}]");
1433
2799
  const parsed = [];
1434
2800
  for (const each of list2) {
1435
2801
  const endpoint = parseEndpoint(each);
1436
2802
  if (typeof endpoint === "string")
1437
- return adminError2(400, endpoint);
2803
+ return adminError3(400, endpoint);
1438
2804
  parsed.push(endpoint);
1439
2805
  }
1440
2806
  const set = hub.setEndpoints(namespace, parsed);
1441
- return json3(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2807
+ return json5(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1442
2808
  },
1443
2809
  "DELETE /webhook-endpoints": ({ namespace }) => {
1444
2810
  hub.setEndpoints(namespace, []);
1445
- return json3(200, { status: "ok" });
2811
+ return json5(200, { status: "ok" });
1446
2812
  }
1447
2813
  });
1448
2814
  var parsePayload = (message) => {
@@ -1507,6 +2873,7 @@ var operationMatcher = (document2) => {
1507
2873
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1508
2874
  };
1509
2875
  var createRuntime = (options) => {
2876
+ assertAdminUi(options.adminUi);
1510
2877
  const sqlite = bootSqlite(options.sqlite);
1511
2878
  const clock = options.clock ?? createClock();
1512
2879
  const rng = createRng(options.seed ?? 0);
@@ -1713,6 +3080,19 @@ var createRuntime = (options) => {
1713
3080
  else
1714
3081
  timeline(name);
1715
3082
  };
3083
+ const declarationsFor = (namespace) => {
3084
+ const declared = options.state;
3085
+ if (!declared)
3086
+ return [];
3087
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3088
+ };
3089
+ const stateScope = (namespace) => ({
3090
+ sqlite,
3091
+ namespace,
3092
+ storageNamespace: storageNamespace(namespace),
3093
+ root: instance(namespace),
3094
+ declarations: declarationsFor(namespace)
3095
+ });
1716
3096
  const runtime = {
1717
3097
  name: options.name,
1718
3098
  sqlite,
@@ -1751,6 +3131,7 @@ var createRuntime = (options) => {
1751
3131
  branch,
1752
3132
  checkout,
1753
3133
  timeline,
3134
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
1754
3135
  fetch: async (incoming) => {
1755
3136
  let request = incoming;
1756
3137
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -1944,11 +3325,20 @@ var createRuntime = (options) => {
1944
3325
  ...credentialRoutes(credentials),
1945
3326
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
1946
3327
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
1947
- ...options.admin?.(runtime) ?? {}
3328
+ ...options.admin?.(runtime) ?? {},
3329
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3330
+ // beside these; it does not replace `/state` or `/ui`.
3331
+ ...stateAdminRoutes({
3332
+ open: stateScope,
3333
+ afterWrite: (namespace) => {
3334
+ checkpoint(namespace, "main");
3335
+ }
3336
+ }),
3337
+ ...adminUiRoutes(options.name, options.adminUi)
1948
3338
  },
1949
3339
  adminKey: options.adminKey
1950
3340
  });
1951
- return runtime;
3341
+ return defineMock(runtime);
1952
3342
  };
1953
3343
  var mutableResponse = (response) => {
1954
3344
  try {
@@ -2188,10 +3578,10 @@ var SLACK_PRESETS = {
2188
3578
  rules: [{ pathPrefix: "/api/", effect: "invalid_auth" }]
2189
3579
  }
2190
3580
  };
2191
- var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2192
- var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2193
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2194
- var list = (body, key) => Array.isArray(body) ? body : isRecord4(body) && Array.isArray(body[key]) ? body[key] : void 0;
3581
+ var json6 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3582
+ var adminError4 = (status, message) => json6(status, { error: { type: "mockingbird_admin", message } });
3583
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3584
+ var list = (body, key) => Array.isArray(body) ? body : isRecord5(body) && Array.isArray(body[key]) ? body[key] : void 0;
2195
3585
  var hookSuffix = (value) => {
2196
3586
  let path = value;
2197
3587
  try {
@@ -2224,13 +3614,13 @@ var adminRoutes = (runtime) => ({
2224
3614
  (api) => api.state.outbox,
2225
3615
  outboxFilter
2226
3616
  ),
2227
- "GET /hooks": ({ namespace }) => json4(200, {
3617
+ "GET /hooks": ({ namespace }) => json6(200, {
2228
3618
  hooks: runtime.instance(namespace).state.hooks.list({ order: "oldest" }).map((row) => ({ ...row.value, url: `/services/${row.value.path}` }))
2229
3619
  }),
2230
3620
  "POST /hooks": ({ body, namespace }) => {
2231
- const entries = list(body, "hooks") ?? (isRecord4(body) ? [body] : void 0);
2232
- if (!entries || entries.some((e) => !isRecord4(e) || typeof e.path !== "string")) {
2233
- return adminError3(400, 'expected {"path": "T\u2026/B\u2026/X\u2026", "channel"?: "C\u2026"} or {"hooks": [...]}');
3621
+ const entries = list(body, "hooks") ?? (isRecord5(body) ? [body] : void 0);
3622
+ if (!entries || entries.some((e) => !isRecord5(e) || typeof e.path !== "string")) {
3623
+ return adminError4(400, 'expected {"path": "T\u2026/B\u2026/X\u2026", "channel"?: "C\u2026"} or {"hooks": [...]}');
2234
3624
  }
2235
3625
  const api = runtime.instance(namespace);
2236
3626
  const created = entries.map((entry) => {
@@ -2242,7 +3632,7 @@ var adminRoutes = (runtime) => ({
2242
3632
  api.state.hooks.insert(path, hook);
2243
3633
  return { ...hook, url: `/services/${path}` };
2244
3634
  });
2245
- return json4(201, { hooks: created });
3635
+ return json6(201, { hooks: created });
2246
3636
  },
2247
3637
  "DELETE /hooks": ({ namespace, url }) => {
2248
3638
  const api = runtime.instance(namespace);
@@ -2250,15 +3640,15 @@ var adminRoutes = (runtime) => ({
2250
3640
  for (const row of api.state.hooks.list()) {
2251
3641
  if (only === null || row.id === hookSuffix(only)) api.state.hooks.delete(row.id);
2252
3642
  }
2253
- return json4(200, { status: "ok" });
3643
+ return json6(200, { status: "ok" });
2254
3644
  },
2255
- "GET /channels": ({ namespace }) => json4(200, {
3645
+ "GET /channels": ({ namespace }) => json6(200, {
2256
3646
  channels: runtime.instance(namespace).state.channels.list({ order: "oldest" }).map((r) => r.value)
2257
3647
  }),
2258
3648
  "POST /channels": ({ body, namespace }) => {
2259
- const entries = list(body, "channels") ?? (isRecord4(body) ? [body] : void 0);
2260
- if (!entries || entries.some((e) => !isRecord4(e) || typeof e.name !== "string")) {
2261
- return adminError3(
3649
+ const entries = list(body, "channels") ?? (isRecord5(body) ? [body] : void 0);
3650
+ if (!entries || entries.some((e) => !isRecord5(e) || typeof e.name !== "string")) {
3651
+ return adminError4(
2262
3652
  400,
2263
3653
  'expected {"id"?, "name", "is_private"?, "is_archived"?, "is_member"?}'
2264
3654
  );
@@ -2277,15 +3667,15 @@ var adminRoutes = (runtime) => ({
2277
3667
  api.state.channels.insert(channel.id, channel);
2278
3668
  return channel;
2279
3669
  });
2280
- return json4(201, { channels: saved });
3670
+ return json6(201, { channels: saved });
2281
3671
  },
2282
- "GET /users": ({ namespace }) => json4(200, {
3672
+ "GET /users": ({ namespace }) => json6(200, {
2283
3673
  users: runtime.instance(namespace).state.users.list({ order: "oldest" }).map((r) => r.value)
2284
3674
  }),
2285
3675
  "POST /users": ({ body, namespace }) => {
2286
- const entries = list(body, "users") ?? (isRecord4(body) ? [body] : void 0);
2287
- if (!entries || entries.some((e) => !isRecord4(e) || typeof e.id !== "string")) {
2288
- return adminError3(400, 'expected {"id": "U\u2026", "name"?, "real_name"?, "email"?}');
3676
+ const entries = list(body, "users") ?? (isRecord5(body) ? [body] : void 0);
3677
+ if (!entries || entries.some((e) => !isRecord5(e) || typeof e.id !== "string")) {
3678
+ return adminError4(400, 'expected {"id": "U\u2026", "name"?, "real_name"?, "email"?}');
2289
3679
  }
2290
3680
  const api = runtime.instance(namespace);
2291
3681
  const saved = entries.map((entry) => {
@@ -2302,12 +3692,12 @@ var adminRoutes = (runtime) => ({
2302
3692
  api.state.users.insert(id, user);
2303
3693
  return user;
2304
3694
  });
2305
- return json4(201, { users: saved });
3695
+ return json6(201, { users: saved });
2306
3696
  },
2307
3697
  "POST /files": ({ body, namespace }) => {
2308
- const entries = list(body, "files") ?? (isRecord4(body) ? [body] : void 0);
2309
- if (!entries || entries.some((e) => !isRecord4(e) || typeof e.id !== "string")) {
2310
- return adminError3(400, 'expected {"id": "F\u2026", "name"?, "mimetype"?, "size"?}');
3698
+ const entries = list(body, "files") ?? (isRecord5(body) ? [body] : void 0);
3699
+ if (!entries || entries.some((e) => !isRecord5(e) || typeof e.id !== "string")) {
3700
+ return adminError4(400, 'expected {"id": "F\u2026", "name"?, "mimetype"?, "size"?}');
2311
3701
  }
2312
3702
  const api = runtime.instance(namespace);
2313
3703
  const saved = entries.map((entry) => {
@@ -2325,14 +3715,14 @@ var adminRoutes = (runtime) => ({
2325
3715
  api.state.files.insert(id, file);
2326
3716
  return file;
2327
3717
  });
2328
- return json4(201, { files: saved });
3718
+ return json6(201, { files: saved });
2329
3719
  },
2330
- "GET /views": ({ namespace }) => json4(200, {
3720
+ "GET /views": ({ namespace }) => json6(200, {
2331
3721
  views: runtime.instance(namespace).state.views.list({ order: "oldest" }).map((r) => r.value)
2332
3722
  }),
2333
- "GET /settings": ({ namespace }) => json4(200, runtime.instance(namespace).state.current()),
3723
+ "GET /settings": ({ namespace }) => json6(200, runtime.instance(namespace).state.current()),
2334
3724
  "PUT /settings": ({ body, namespace }) => {
2335
- if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
3725
+ if (!isRecord5(body)) return adminError4(400, "expected a JSON object");
2336
3726
  const patch = {};
2337
3727
  for (const key of [
2338
3728
  "teamId",
@@ -2343,19 +3733,19 @@ var adminRoutes = (runtime) => ({
2343
3733
  "appId"
2344
3734
  ]) {
2345
3735
  if (body[key] === void 0) continue;
2346
- if (typeof body[key] !== "string") return adminError3(400, `${key}: string`);
3736
+ if (typeof body[key] !== "string") return adminError4(400, `${key}: string`);
2347
3737
  patch[key] = body[key];
2348
3738
  }
2349
3739
  if (body.tokens !== void 0) {
2350
- if (!Array.isArray(body.tokens)) return adminError3(400, "tokens: string[]");
3740
+ if (!Array.isArray(body.tokens)) return adminError4(400, "tokens: string[]");
2351
3741
  patch.tokens = body.tokens.map(String);
2352
3742
  }
2353
3743
  if (body.strictChannels !== void 0) {
2354
3744
  if (typeof body.strictChannels !== "boolean")
2355
- return adminError3(400, "strictChannels: boolean");
3745
+ return adminError4(400, "strictChannels: boolean");
2356
3746
  patch.strictChannels = body.strictChannels;
2357
3747
  }
2358
- return json4(200, runtime.instance(namespace).state.update(patch));
3748
+ return json6(200, runtime.instance(namespace).state.update(patch));
2359
3749
  }
2360
3750
  });
2361
3751
  var createRuntime2 = (options = {}) => createRuntime({
@@ -2386,12 +3776,12 @@ var slackCredential = (request) => {
2386
3776
  const path = new URL(request.url).pathname;
2387
3777
  return WEBHOOK_PATH.exec(path.replace(/^\/ns\/[^/]+/, ""))?.[1];
2388
3778
  };
2389
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3779
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2390
3780
  var text = (status, body, headers = {}) => new Response(body, {
2391
3781
  status,
2392
3782
  headers: { "content-type": "text/plain; charset=utf-8", ...headers }
2393
3783
  });
2394
- var fail = (error, extra = {}) => jsonRes(200, { ok: false, error, ...extra });
3784
+ var fail2 = (error, extra = {}) => jsonRes(200, { ok: false, error, ...extra });
2395
3785
  var SlackError = class extends Error {
2396
3786
  constructor(code, extra = {}) {
2397
3787
  super(code);
@@ -2407,11 +3797,11 @@ var readArgs = (context) => {
2407
3797
  for (const [key, value] of context.url.searchParams) args[key] = value;
2408
3798
  const body = context.body;
2409
3799
  const contentType = context.request.headers.get("content-type") ?? "";
2410
- let json5 = false;
3800
+ let json7 = false;
2411
3801
  if (body.kind === "json") {
2412
- if (!isRecord5(body.value)) throw new SlackError("invalid_json");
3802
+ if (!isRecord6(body.value)) throw new SlackError("invalid_json");
2413
3803
  Object.assign(args, body.value);
2414
- json5 = true;
3804
+ json7 = true;
2415
3805
  } else if (body.kind === "form") {
2416
3806
  Object.assign(args, body.value);
2417
3807
  for (const key of ["blocks", "attachments", "view"]) {
@@ -2428,14 +3818,14 @@ var readArgs = (context) => {
2428
3818
  } else if (body.kind === "invalid") {
2429
3819
  throw new SlackError("invalid_json");
2430
3820
  }
2431
- return Object.assign(args, { __json: json5, __charset: /charset=/i.test(contentType) });
3821
+ return Object.assign(args, { __json: json7, __charset: /charset=/i.test(contentType) });
2432
3822
  };
2433
3823
  var str = (value) => typeof value === "string" && value.length > 0 ? value : typeof value === "number" ? String(value) : void 0;
2434
3824
  var checkBlocks = (blocks) => {
2435
3825
  if (blocks === void 0 || blocks === null || blocks === "") return null;
2436
3826
  if (!Array.isArray(blocks) || blocks.length > 50) throw new SlackError("invalid_blocks");
2437
3827
  for (const block of blocks) {
2438
- if (!isRecord5(block) || typeof block.type !== "string") throw new SlackError("invalid_blocks");
3828
+ if (!isRecord6(block) || typeof block.type !== "string") throw new SlackError("invalid_blocks");
2439
3829
  }
2440
3830
  return blocks;
2441
3831
  };
@@ -2465,7 +3855,7 @@ var SlackAPI = class {
2465
3855
  );
2466
3856
  return ids ? annotateResponse(response, { ids }) : response;
2467
3857
  } catch (error) {
2468
- if (error instanceof SlackError) return fail(error.code, error.extra);
3858
+ if (error instanceof SlackError) return fail2(error.code, error.extra);
2469
3859
  throw error;
2470
3860
  }
2471
3861
  };
@@ -2497,7 +3887,7 @@ var SlackAPI = class {
2497
3887
  sqlite,
2498
3888
  namespace,
2499
3889
  now: this.now,
2500
- notFound: (request) => new URL(request.url).pathname.startsWith("/api/") ? fail("unknown_method") : text(404, "no_service"),
3890
+ notFound: (request) => new URL(request.url).pathname.startsWith("/api/") ? fail2("unknown_method") : text(404, "no_service"),
2501
3891
  onError: (error) => {
2502
3892
  if (error instanceof HttpError) return error.toResponse();
2503
3893
  throw error;
@@ -2536,12 +3926,12 @@ var SlackAPI = class {
2536
3926
  return webhook ? text(status, code) : jsonRes(status, { ok: false, error: code });
2537
3927
  }
2538
3928
  if (webhook) return void 0;
2539
- if (faultEffect(context.request, "invalid_auth") !== void 0) return fail("invalid_auth");
3929
+ if (faultEffect(context.request, "invalid_auth") !== void 0) return fail2("invalid_auth");
2540
3930
  const token = bearerToken(context.request) ?? this.bodyToken(context);
2541
- if (!token) return fail("not_authed");
3931
+ if (!token) return fail2("not_authed");
2542
3932
  const accepted = this.settings().tokens;
2543
3933
  const ok = accepted.length > 0 ? accepted.includes(token) : /^xox[abp]-/.test(token);
2544
- return ok ? void 0 : fail("invalid_auth");
3934
+ return ok ? void 0 : fail2("invalid_auth");
2545
3935
  }
2546
3936
  /** Form posts may carry `token=` instead of the header (Slack's legacy style). */
2547
3937
  bodyToken(context) {
@@ -2622,7 +4012,7 @@ var SlackAPI = class {
2622
4012
  return text(400, "invalid_payload");
2623
4013
  }
2624
4014
  } else return text(400, "invalid_payload");
2625
- if (!isRecord5(payload)) return text(400, "invalid_payload");
4015
+ if (!isRecord6(payload)) return text(400, "invalid_payload");
2626
4016
  let blocks;
2627
4017
  try {
2628
4018
  blocks = checkBlocks(payload.blocks);
@@ -2888,7 +4278,7 @@ var SlackAPI = class {
2888
4278
  openView(args) {
2889
4279
  if (!str(args.trigger_id)) throw new SlackError("invalid_arguments");
2890
4280
  const view = args.view;
2891
- if (!isRecord5(view) || view.type !== "modal" && view.type !== "home") {
4281
+ if (!isRecord6(view) || view.type !== "modal" && view.type !== "home") {
2892
4282
  throw new SlackError("invalid_arguments", {
2893
4283
  response_metadata: { messages: ["[ERROR] view.type must be modal"] }
2894
4284
  });
@@ -2925,4 +4315,4 @@ export {
2925
4315
  slackCredential,
2926
4316
  SlackAPI
2927
4317
  };
2928
- //# sourceMappingURL=chunk-EDQWEMMR.js.map
4318
+ //# sourceMappingURL=chunk-N46A45RB.js.map