@crvouga/mockingbird-service-payload-cms 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.
@@ -176,30 +176,30 @@ var createClock = (source = Date.now) => {
176
176
  var Collection = class {
177
177
  sqlite;
178
178
  namespace;
179
- name;
180
- constructor(sqlite, namespace, name) {
179
+ collectionName;
180
+ constructor(sqlite, namespace, collectionName) {
181
181
  this.sqlite = sqlite;
182
182
  this.namespace = namespace;
183
- this.name = name;
183
+ this.collectionName = collectionName;
184
184
  }
185
185
  bumpCollectionSeq() {
186
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
186
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.collectionName);
187
187
  const next = (row?.value ?? 0) + 1;
188
188
  this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
189
- ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
189
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.collectionName, next);
190
190
  return next;
191
191
  }
192
192
  nextSequence() {
193
193
  return this.sqlite.transaction(() => this.bumpCollectionSeq());
194
194
  }
195
195
  get(id) {
196
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
196
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
197
197
  if (!row)
198
198
  return void 0;
199
199
  return JSON.parse(row.value).value;
200
200
  }
201
201
  has(id) {
202
- const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
202
+ const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
203
203
  return row !== void 0;
204
204
  }
205
205
  /** Insert a new record, assigning it the next sequence number. */
@@ -209,32 +209,32 @@ var Collection = class {
209
209
  const stored = { seq, value };
210
210
  this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
211
211
  VALUES (?, ?, ?, ?, ?)
212
- ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
212
+ ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.collectionName, id, seq, JSON.stringify(stored));
213
213
  return stored;
214
214
  });
215
215
  }
216
216
  /** Replace an existing record's value, keeping its position. */
217
217
  update(id, value) {
218
218
  return this.sqlite.transaction(() => {
219
- const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
219
+ const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
220
220
  if (!row)
221
221
  return void 0;
222
222
  const stored = { seq: row.seq, value };
223
- this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
223
+ this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.collectionName, id);
224
224
  return stored;
225
225
  });
226
226
  }
227
227
  delete(id) {
228
- const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
228
+ const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.collectionName, id);
229
229
  return result.changes > 0;
230
230
  }
231
231
  /** How many records the collection holds, without reading them. */
232
232
  count() {
233
- const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
233
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.collectionName);
234
234
  return Number(row?.n ?? 0);
235
235
  }
236
236
  list(options = {}) {
237
- const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
237
+ const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.collectionName);
238
238
  const out = [];
239
239
  for (const row of rows) {
240
240
  const stored = JSON.parse(row.value);
@@ -491,16 +491,18 @@ var createControlPlane = (context) => {
491
491
  uptimeMs: context.wallNow() - context.startedAt,
492
492
  clock: context.clock.state(),
493
493
  namespaces: context.namespaces().length,
494
+ adminUi: `${ADMIN_PREFIX}/ui`,
494
495
  ...context.describe()
495
496
  });
496
497
  }
497
498
  if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
498
499
  return void 0;
499
500
  }
500
- if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
501
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
502
+ const shell = request.method === "GET" && (path === "/ui" || path === "/ui/");
503
+ if (!shell && context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
501
504
  return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
502
505
  }
503
- const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
504
506
  for (const route of routes) {
505
507
  if (route.method !== request.method)
506
508
  continue;
@@ -1139,6 +1141,936 @@ var clearNamespace = (sqlite, namespace) => {
1139
1141
  });
1140
1142
  };
1141
1143
 
1144
+ // ../core/dist/surface.js
1145
+ var defineMock = (runtime) => runtime;
1146
+ var STANDARD_ADMIN_ROUTES = [
1147
+ "GET /",
1148
+ "POST /reset",
1149
+ "GET /namespaces",
1150
+ "GET /clock",
1151
+ "POST /clock",
1152
+ "GET /faults",
1153
+ "POST /faults",
1154
+ "DELETE /faults",
1155
+ "POST /snapshots",
1156
+ "POST /snapshots/:id/restore",
1157
+ "DELETE /snapshots/:id",
1158
+ "GET /timeline",
1159
+ "POST /checkpoints",
1160
+ "POST /branches/:name",
1161
+ "POST /branches/:name/checkout",
1162
+ "GET /requests",
1163
+ "DELETE /requests",
1164
+ "GET /metrics",
1165
+ "DELETE /metrics",
1166
+ "GET /credentials",
1167
+ "PUT /credentials",
1168
+ "DELETE /credentials",
1169
+ "GET /state",
1170
+ "GET /state/:collection",
1171
+ "GET /state/:collection/:id",
1172
+ "POST /state/:collection",
1173
+ "PUT /state/:collection/:id",
1174
+ "PATCH /state/:collection/:id",
1175
+ "DELETE /state/:collection/:id",
1176
+ "GET /ui",
1177
+ "GET /ui/",
1178
+ "GET /ui/manifest"
1179
+ ];
1180
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1181
+ var assertAdminUi = (ui) => {
1182
+ if (!ui?.panels)
1183
+ return;
1184
+ const seen = /* @__PURE__ */ new Set();
1185
+ for (const panel of ui.panels) {
1186
+ if (!PANEL_ID.test(panel.id)) {
1187
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1188
+ }
1189
+ if (seen.has(panel.id))
1190
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1191
+ seen.add(panel.id);
1192
+ if (panel.title.trim() === "")
1193
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1194
+ }
1195
+ };
1196
+
1197
+ // ../core/dist/admin-ui.js
1198
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1199
+ switch (char) {
1200
+ case "&":
1201
+ return "&amp;";
1202
+ case "<":
1203
+ return "&lt;";
1204
+ case ">":
1205
+ return "&gt;";
1206
+ case '"':
1207
+ return "&quot;";
1208
+ default:
1209
+ return "&#39;";
1210
+ }
1211
+ });
1212
+ var renderAdminDocument = (service) => {
1213
+ const name = escapeHtml(service);
1214
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1215
+ return `<!DOCTYPE html>
1216
+ <html lang="en">
1217
+ <head>
1218
+ <meta charset="utf-8">
1219
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1220
+ <meta name="color-scheme" content="light dark">
1221
+ <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">
1222
+ <title>${name} admin</title>
1223
+ <style>
1224
+ :root {
1225
+ color-scheme: light;
1226
+ --bg: #f6f5f2;
1227
+ --bg-elev: #ffffff;
1228
+ --bg-muted: #eeece6;
1229
+ --bg-inset: #f3f1eb;
1230
+ --line: #e2dfd6;
1231
+ --line-strong: #d0ccc1;
1232
+ --ink: #1c1915;
1233
+ --muted: #5e584f;
1234
+ --faint: #8a8378;
1235
+ --accent: #3d4f3a;
1236
+ --accent-ink: #f7f6f2;
1237
+ --accent-soft: #e5ece2;
1238
+ --ok: #1f7a45;
1239
+ --ok-soft: #e5f4eb;
1240
+ --warn: #9a6700;
1241
+ --warn-soft: #fbf3df;
1242
+ --err: #a33b32;
1243
+ --err-soft: #fdecea;
1244
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1245
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1246
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1247
+ --radius: 14px;
1248
+ --header: 60px;
1249
+ --nav: 220px;
1250
+ }
1251
+ :root[data-theme="dark"] {
1252
+ color-scheme: dark;
1253
+ --bg: #141311;
1254
+ --bg-elev: #1e1c19;
1255
+ --bg-muted: #26231f;
1256
+ --bg-inset: #181715;
1257
+ --line: #34302b;
1258
+ --line-strong: #4a453d;
1259
+ --ink: #f4f1ea;
1260
+ --muted: #c4bdb1;
1261
+ --faint: #8f877c;
1262
+ --accent: #c5d5b8;
1263
+ --accent-ink: #1a2118;
1264
+ --accent-soft: #2a3328;
1265
+ --ok: #8fd6a8;
1266
+ --ok-soft: #1a2e22;
1267
+ --warn: #f0cc78;
1268
+ --warn-soft: #332911;
1269
+ --err: #f0a8a2;
1270
+ --err-soft: #3a201e;
1271
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1272
+ }
1273
+ @media (prefers-color-scheme: dark) {
1274
+ :root:not([data-theme="light"]) {
1275
+ color-scheme: dark;
1276
+ --bg: #141311;
1277
+ --bg-elev: #1e1c19;
1278
+ --bg-muted: #26231f;
1279
+ --bg-inset: #181715;
1280
+ --line: #34302b;
1281
+ --line-strong: #4a453d;
1282
+ --ink: #f4f1ea;
1283
+ --muted: #c4bdb1;
1284
+ --faint: #8f877c;
1285
+ --accent: #c5d5b8;
1286
+ --accent-ink: #1a2118;
1287
+ --accent-soft: #2a3328;
1288
+ --ok: #8fd6a8;
1289
+ --ok-soft: #1a2e22;
1290
+ --warn: #f0cc78;
1291
+ --warn-soft: #332911;
1292
+ --err: #f0a8a2;
1293
+ --err-soft: #3a201e;
1294
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1295
+ }
1296
+ }
1297
+ * { box-sizing: border-box; }
1298
+ html, body { margin: 0; height: 100%; }
1299
+ body {
1300
+ font-family: var(--sans);
1301
+ background: var(--bg);
1302
+ color: var(--ink);
1303
+ line-height: 1.45;
1304
+ padding-left: env(safe-area-inset-left);
1305
+ padding-right: env(safe-area-inset-right);
1306
+ -webkit-text-size-adjust: 100%;
1307
+ }
1308
+ button, input, select, textarea { font: inherit; color: inherit; }
1309
+ button { cursor: pointer; }
1310
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1311
+ @media (prefers-reduced-motion: reduce) {
1312
+ * { scroll-behavior: auto !important; transition: none !important; }
1313
+ }
1314
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1315
+ header.top {
1316
+ position: sticky; top: 0; z-index: 5;
1317
+ display: flex; align-items: center; gap: 12px;
1318
+ min-height: var(--header); padding: 10px 16px;
1319
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1320
+ border-bottom: 1px solid var(--line);
1321
+ backdrop-filter: blur(10px);
1322
+ }
1323
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1324
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1325
+ .brand span { color: var(--faint); font-size: 12px; }
1326
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1327
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1328
+ label.field input, label.field select, .controls input[type="password"] {
1329
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1330
+ padding: 7px 8px; min-height: 36px;
1331
+ }
1332
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1333
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1334
+ background: var(--bg-elev);
1335
+ }
1336
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1337
+ .btn-quiet { background: transparent; }
1338
+ .btn-danger { color: var(--err); }
1339
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1340
+ record or the full nav row would widen the page past the viewport. */
1341
+ .layout {
1342
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1343
+ flex: 1; min-height: 0; min-width: 0;
1344
+ }
1345
+ nav.side {
1346
+ border-right: 1px solid var(--line); padding: 12px;
1347
+ display: flex; flex-direction: column; gap: 4px;
1348
+ background: var(--bg-elev);
1349
+ }
1350
+ nav.side button {
1351
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1352
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1353
+ }
1354
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1355
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1356
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1357
+ .lede { margin: 0 0 16px; color: var(--muted); }
1358
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1359
+ .card {
1360
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1361
+ padding: 14px 16px; box-shadow: var(--shadow);
1362
+ }
1363
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1364
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1365
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1366
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1367
+ .collection {
1368
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1369
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1370
+ }
1371
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1372
+ .collection small { display: block; color: var(--faint); }
1373
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1374
+ .chip {
1375
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1376
+ border-radius: 999px; padding: 4px 8px;
1377
+ }
1378
+ .chip i { color: var(--faint); font-style: normal; }
1379
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1380
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1381
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1382
+ tr.clickable { cursor: pointer; }
1383
+ tr.clickable:hover { background: var(--bg-muted); }
1384
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1385
+ pre {
1386
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1387
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1388
+ }
1389
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1390
+ .banner {
1391
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1392
+ background: var(--err-soft); color: var(--err);
1393
+ }
1394
+ .banner.show { display: block; }
1395
+ .empty { color: var(--muted); padding: 24px 8px; }
1396
+ dialog {
1397
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1398
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1399
+ }
1400
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1401
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1402
+ textarea {
1403
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1404
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1405
+ font-family: var(--mono); font-size: 12px;
1406
+ }
1407
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1408
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1409
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1410
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1411
+ .status-2 { color: var(--ok); }
1412
+ .status-4, .status-5, .status-0 { color: var(--err); }
1413
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1414
+ .route {
1415
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1416
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1417
+ }
1418
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1419
+ @media (max-width: 800px) {
1420
+ header.top {
1421
+ align-items: stretch; flex-direction: column;
1422
+ padding-top: max(10px, env(safe-area-inset-top));
1423
+ }
1424
+ input, select, textarea { font-size: 16px; }
1425
+ .controls { width: 100%; }
1426
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1427
+ .layout { grid-template-columns: minmax(0, 1fr); }
1428
+ nav.side {
1429
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1430
+ border-right: 0; border-bottom: 1px solid var(--line);
1431
+ padding: 8px;
1432
+ }
1433
+ nav.side button { white-space: nowrap; flex: none; }
1434
+ .split { grid-template-columns: minmax(0, 1fr); }
1435
+ main { padding: 14px; }
1436
+ table, thead, tbody, tr, th, td { display: block; }
1437
+ thead { display: none; }
1438
+ tr {
1439
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1440
+ background: var(--bg-elev); min-width: 0;
1441
+ }
1442
+ td {
1443
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1444
+ min-width: 0; overflow-wrap: anywhere;
1445
+ }
1446
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1447
+ .route { grid-template-columns: 72px 1fr; }
1448
+ .route button { grid-column: 1 / -1; }
1449
+ }
1450
+ </style>
1451
+ </head>
1452
+ <body>
1453
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1454
+ <header class="top">
1455
+ <div class="brand">
1456
+ <strong>${name}</strong>
1457
+ <span>Mockingbird admin</span>
1458
+ </div>
1459
+ <div class="controls">
1460
+ <label class="field">Namespace
1461
+ <select id="namespace" aria-label="Namespace"></select>
1462
+ </label>
1463
+ <label class="field">Admin key
1464
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1465
+ </label>
1466
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1467
+ <button class="btn" id="refresh" type="button">Refresh</button>
1468
+ </div>
1469
+ </header>
1470
+ <div class="layout">
1471
+ <nav class="side" id="nav" aria-label="Admin sections">
1472
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1473
+ <button type="button" data-view="state">State</button>
1474
+ <button type="button" data-view="clock">Clock</button>
1475
+ <button type="button" data-view="faults">Faults</button>
1476
+ <button type="button" data-view="journal">Journal</button>
1477
+ <button type="button" data-view="routes">Routes</button>
1478
+ </nav>
1479
+ <main id="views">
1480
+ <p class="banner" id="banner" role="alert"></p>
1481
+ <section class="view" id="view-overview">
1482
+ <h2>Overview</h2>
1483
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1484
+ <div class="grid" id="overview-cards"></div>
1485
+ <h3>Recent requests</h3>
1486
+ <div id="overview-requests"></div>
1487
+ </section>
1488
+ <section class="view" id="view-state" hidden>
1489
+ <h2>State</h2>
1490
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1491
+ <div class="split">
1492
+ <div id="collections"></div>
1493
+ <div>
1494
+ <div id="schema"></div>
1495
+ <div class="row-actions">
1496
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1497
+ </div>
1498
+ <div id="records"></div>
1499
+ </div>
1500
+ </div>
1501
+ </section>
1502
+ <section class="view" id="view-clock" hidden>
1503
+ <h2>Clock</h2>
1504
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1505
+ <div class="card" id="clock-readout"></div>
1506
+ <div class="row-actions">
1507
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1508
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1509
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1510
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1511
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1512
+ <button class="btn" id="freeze" type="button">Freeze</button>
1513
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1514
+ </div>
1515
+ <form id="clock-set" class="row-actions">
1516
+ <label class="field">Set instant
1517
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1518
+ </label>
1519
+ <button class="btn-primary" type="submit">Set</button>
1520
+ </form>
1521
+ </section>
1522
+ <section class="view" id="view-faults" hidden>
1523
+ <h2>Faults</h2>
1524
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1525
+ <form id="fault-form" class="card stack">
1526
+ <label class="field">Preset
1527
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1528
+ </label>
1529
+ <label class="field">Status
1530
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1531
+ </label>
1532
+ <label class="field">Path prefix
1533
+ <input id="fault-path" placeholder="/v1">
1534
+ </label>
1535
+ <label class="field">Method
1536
+ <input id="fault-method" placeholder="GET">
1537
+ </label>
1538
+ <div class="dialog-actions">
1539
+ <button class="btn-primary" type="submit">Add fault</button>
1540
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1541
+ </div>
1542
+ </form>
1543
+ <div id="fault-list"></div>
1544
+ </section>
1545
+ <section class="view" id="view-journal" hidden>
1546
+ <h2>Journal</h2>
1547
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1548
+ <div class="row-actions">
1549
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1550
+ </div>
1551
+ <div id="journal"></div>
1552
+ </section>
1553
+ <section class="view" id="view-routes" hidden>
1554
+ <h2>Routes</h2>
1555
+ <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>
1556
+ <div id="route-list"></div>
1557
+ <form id="route-form" class="card stack">
1558
+ <strong id="route-title">Select a route</strong>
1559
+ <label class="field">JSON body
1560
+ <textarea id="route-body" placeholder="{ }"></textarea>
1561
+ </label>
1562
+ <div class="dialog-actions">
1563
+ <button class="btn-primary" type="submit">Send</button>
1564
+ </div>
1565
+ <pre id="route-result">Response will show here.</pre>
1566
+ </form>
1567
+ </section>
1568
+ </main>
1569
+ </div>
1570
+ </div>
1571
+ <dialog id="editor">
1572
+ <form method="dialog" id="editor-form">
1573
+ <strong id="editor-title">Record</strong>
1574
+ <label class="field">Id
1575
+ <input id="editor-id" required>
1576
+ </label>
1577
+ <label class="field">JSON value
1578
+ <textarea id="editor-value"></textarea>
1579
+ </label>
1580
+ <div class="dialog-actions">
1581
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1582
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1583
+ <button class="btn-primary" type="submit" value="save">Save</button>
1584
+ </div>
1585
+ </form>
1586
+ </dialog>
1587
+ <script>
1588
+ (() => {
1589
+ const STANDARD = new Set(${standard})
1590
+ const state = {
1591
+ namespace: "default",
1592
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1593
+ view: "overview",
1594
+ collection: "",
1595
+ shape: null,
1596
+ route: null,
1597
+ editing: null
1598
+ }
1599
+ const $ = (id) => document.getElementById(id)
1600
+ const banner = $("banner")
1601
+ const keyInput = $("admin-key")
1602
+ keyInput.value = state.key
1603
+ const params = new URLSearchParams(location.search)
1604
+ if (params.get("key")) {
1605
+ state.key = params.get("key")
1606
+ keyInput.value = state.key
1607
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1608
+ params.delete("key")
1609
+ const next = params.toString()
1610
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1611
+ }
1612
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1613
+
1614
+ const showError = (error) => {
1615
+ banner.textContent = error instanceof Error ? error.message : String(error)
1616
+ banner.classList.add("show")
1617
+ }
1618
+ const clearError = () => banner.classList.remove("show")
1619
+
1620
+ async function originGet(path) {
1621
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1622
+ if (!response.ok) throw new Error(response.status + " " + path)
1623
+ return response.json()
1624
+ }
1625
+ async function api(method, path, body) {
1626
+ const headers = { accept: "application/json" }
1627
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1628
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1629
+ if (body !== undefined) headers["content-type"] = "application/json"
1630
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1631
+ method,
1632
+ headers,
1633
+ body: body === undefined ? undefined : JSON.stringify(body)
1634
+ })
1635
+ const text = await response.text()
1636
+ let data = null
1637
+ if (text) {
1638
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1639
+ }
1640
+ if (response.status === 401) {
1641
+ keyInput.focus()
1642
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1643
+ }
1644
+ if (!response.ok) {
1645
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1646
+ }
1647
+ return data
1648
+ }
1649
+ const panelApi = {
1650
+ get: (path) => api("GET", path),
1651
+ send: (method, path, body) => api(method, path, body),
1652
+ namespace: () => state.namespace
1653
+ }
1654
+
1655
+ function setTheme(theme) {
1656
+ if (theme) document.documentElement.dataset.theme = theme
1657
+ else delete document.documentElement.dataset.theme
1658
+ }
1659
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1660
+ if (storedTheme) setTheme(storedTheme)
1661
+ $("theme").addEventListener("click", () => {
1662
+ const current = document.documentElement.dataset.theme
1663
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1664
+ const next = dark ? "light" : "dark"
1665
+ localStorage.setItem("mockingbird-admin-theme", next)
1666
+ setTheme(next)
1667
+ })
1668
+
1669
+ function show(view) {
1670
+ state.view = view
1671
+ for (const button of document.querySelectorAll("#nav button")) {
1672
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1673
+ }
1674
+ for (const section of document.querySelectorAll("main .view")) {
1675
+ section.hidden = section.id !== "view-" + view
1676
+ }
1677
+ }
1678
+ document.getElementById("nav").addEventListener("click", (event) => {
1679
+ const button = event.target.closest("button[data-view]")
1680
+ if (!button) return
1681
+ show(button.dataset.view)
1682
+ refresh().catch(showError)
1683
+ })
1684
+
1685
+ function cards(items) {
1686
+ return '<div class="grid">' + items.map((item) =>
1687
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1688
+ ).join("") + "</div>"
1689
+ }
1690
+ function table(columns, rows) {
1691
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1692
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1693
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1694
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1695
+ ).join("") + "</tr>").join("")
1696
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1697
+ }
1698
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1699
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1700
+ }[char]))
1701
+ const preview = (value) => {
1702
+ const text = JSON.stringify(value)
1703
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1704
+ }
1705
+ const when = (epoch) => {
1706
+ const date = new Date(epoch)
1707
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1708
+ }
1709
+ const clockCard = (epoch) => {
1710
+ const date = new Date(epoch)
1711
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1712
+ const iso = date.toISOString()
1713
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1714
+ }
1715
+
1716
+ async function loadNamespaces() {
1717
+ const data = await api("GET", "/namespaces")
1718
+ const select = $("namespace")
1719
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1720
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1721
+ select.innerHTML = names.map((name) =>
1722
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1723
+ ).join("")
1724
+ select.value = state.namespace
1725
+ }
1726
+
1727
+ async function renderOverview() {
1728
+ const [health, shape, clock, journal] = await Promise.all([
1729
+ originGet("/health"),
1730
+ api("GET", "/state"),
1731
+ api("GET", "/clock"),
1732
+ api("GET", "/requests?limit=8")
1733
+ ])
1734
+ state.shape = shape
1735
+ $("overview-cards").innerHTML = cards([
1736
+ { k: "Service", v: esc(health.service || "${name}") },
1737
+ { k: "Status", v: esc(health.status || "ok") },
1738
+ { k: "Namespace", v: esc(state.namespace) },
1739
+ { k: "Collections", v: String(shape.collections.length) },
1740
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1741
+ { k: "Clock", v: clockCard(clock.now) }
1742
+ ])
1743
+ const requests = (journal && journal.requests) || []
1744
+ $("overview-requests").innerHTML = table(
1745
+ [
1746
+ { label: "Method", cell: (row) => esc(row.method) },
1747
+ { label: "Path", cell: (row) => esc(row.path) },
1748
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1749
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1750
+ ],
1751
+ requests
1752
+ )
1753
+ }
1754
+
1755
+ function schemaChips(collection) {
1756
+ if (!collection || collection.fields.length === 0) {
1757
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
1758
+ }
1759
+ return '<div class="chips">' + collection.fields.map((field) =>
1760
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
1761
+ ).join("") + "</div>"
1762
+ }
1763
+
1764
+ async function renderState() {
1765
+ const shape = await api("GET", "/state")
1766
+ state.shape = shape
1767
+ const host = $("collections")
1768
+ if (shape.collections.length === 0) {
1769
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
1770
+ $("schema").innerHTML = ""
1771
+ $("records").innerHTML = ""
1772
+ return
1773
+ }
1774
+ if (!shape.collections.some((item) => item.name === state.collection)) {
1775
+ state.collection = shape.collections[0].name
1776
+ }
1777
+ host.innerHTML = shape.collections.map((item) =>
1778
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
1779
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
1780
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
1781
+ ).join("")
1782
+ const selected = shape.collections.find((item) => item.name === state.collection)
1783
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
1784
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
1785
+ schemaChips(selected)
1786
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
1787
+ const rows = page.records.map((record) => ({
1788
+ ...record,
1789
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
1790
+ }))
1791
+ $("records").innerHTML = table(
1792
+ [
1793
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
1794
+ { label: "Seq", cell: (row) => esc(row.seq) },
1795
+ { label: "Value", cell: (row) => preview(row.value) }
1796
+ ],
1797
+ rows
1798
+ )
1799
+ }
1800
+
1801
+ async function renderClock() {
1802
+ const clock = await api("GET", "/clock")
1803
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
1804
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
1805
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
1806
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
1807
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
1808
+ }
1809
+
1810
+ async function renderFaults() {
1811
+ const [faults, presets] = await Promise.all([
1812
+ api("GET", "/faults"),
1813
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
1814
+ ])
1815
+ const select = $("fault-preset")
1816
+ const current = select.value
1817
+ const list = presets.presets || []
1818
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
1819
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
1820
+ ).join("")
1821
+ select.value = current
1822
+ const rules = faults.faults || []
1823
+ $("fault-list").innerHTML = table(
1824
+ [
1825
+ { label: "Id", cell: (row) => esc(row.id) },
1826
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
1827
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
1828
+ ],
1829
+ rules
1830
+ )
1831
+ }
1832
+
1833
+ async function renderJournal() {
1834
+ const journal = await api("GET", "/requests?limit=100")
1835
+ $("journal").innerHTML = table(
1836
+ [
1837
+ { label: "When", cell: (row) => esc(row.at || "") },
1838
+ { label: "Method", cell: (row) => esc(row.method) },
1839
+ { label: "Path", cell: (row) => esc(row.path) },
1840
+ { label: "Status", cell: (row) => esc(row.status) },
1841
+ { label: "ms", cell: (row) => esc(row.durationMs) }
1842
+ ],
1843
+ journal.requests || []
1844
+ )
1845
+ }
1846
+
1847
+ async function renderRoutes() {
1848
+ const data = await api("GET", "/")
1849
+ const routes = data.routes || []
1850
+ $("route-list").innerHTML = routes.map((route) => {
1851
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
1852
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
1853
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
1854
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
1855
+ }).join("")
1856
+ }
1857
+
1858
+ const renderers = {
1859
+ overview: renderOverview,
1860
+ state: renderState,
1861
+ clock: renderClock,
1862
+ faults: renderFaults,
1863
+ journal: renderJournal,
1864
+ routes: renderRoutes
1865
+ }
1866
+
1867
+ async function refresh() {
1868
+ clearError()
1869
+ if (state.view in renderers) await renderers[state.view]()
1870
+ }
1871
+
1872
+ $("namespace").addEventListener("change", () => {
1873
+ state.namespace = $("namespace").value
1874
+ refresh().catch(showError)
1875
+ })
1876
+ keyInput.addEventListener("change", () => {
1877
+ state.key = keyInput.value.trim()
1878
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1879
+ refresh().catch(showError)
1880
+ })
1881
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
1882
+
1883
+ $("collections").addEventListener("click", (event) => {
1884
+ const button = event.target.closest("[data-collection]")
1885
+ if (!button) return
1886
+ state.collection = button.dataset.collection
1887
+ renderState().catch(showError)
1888
+ })
1889
+ $("records").addEventListener("click", (event) => {
1890
+ const row = event.target.closest("[data-id]")
1891
+ if (!row) return
1892
+ openEditor(row.dataset.id).catch(showError)
1893
+ })
1894
+
1895
+ const editor = $("editor")
1896
+ async function openEditor(id) {
1897
+ state.editing = id || null
1898
+ $("editor-title").textContent = id ? "Edit record" : "New record"
1899
+ $("editor-id").value = id || ""
1900
+ $("editor-id").readOnly = Boolean(id)
1901
+ $("editor-delete").hidden = !id
1902
+ if (id) {
1903
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1904
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
1905
+ } else {
1906
+ $("editor-value").value = "{\\n \\n}"
1907
+ }
1908
+ editor.showModal()
1909
+ }
1910
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
1911
+ $("editor-form").addEventListener("submit", (event) => {
1912
+ const submitter = event.submitter
1913
+ if (!submitter || submitter.value !== "save") return
1914
+ event.preventDefault()
1915
+ let value
1916
+ try { value = JSON.parse($("editor-value").value) }
1917
+ catch { showError(new Error("Value is not JSON")); return }
1918
+ const id = $("editor-id").value.trim()
1919
+ const path = "/state/" + encodeURIComponent(state.collection)
1920
+ const request = state.editing
1921
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
1922
+ : api("POST", path, { id: id || undefined, value })
1923
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
1924
+ })
1925
+ $("editor-delete").addEventListener("click", () => {
1926
+ const id = state.editing
1927
+ if (!id) return
1928
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1929
+ .then(() => { editor.close(); return renderState() })
1930
+ .catch(showError)
1931
+ })
1932
+
1933
+ document.querySelectorAll("[data-advance]").forEach((button) => {
1934
+ button.addEventListener("click", () => {
1935
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
1936
+ })
1937
+ })
1938
+ $("freeze").addEventListener("click", () => {
1939
+ const frozen = $("freeze").dataset.frozen === "1"
1940
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
1941
+ })
1942
+ $("clock-reset").addEventListener("click", () => {
1943
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
1944
+ })
1945
+ $("clock-set").addEventListener("submit", (event) => {
1946
+ event.preventDefault()
1947
+ const raw = $("clock-instant").value.trim()
1948
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
1949
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
1950
+ })
1951
+
1952
+ $("fault-form").addEventListener("submit", (event) => {
1953
+ event.preventDefault()
1954
+ const preset = $("fault-preset").value
1955
+ const body = preset
1956
+ ? { preset }
1957
+ : {
1958
+ status: Number($("fault-status").value),
1959
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
1960
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
1961
+ }
1962
+ if (!preset && !Number.isFinite(body.status)) {
1963
+ showError(new Error("Status must be a number, or choose a preset"))
1964
+ return
1965
+ }
1966
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
1967
+ })
1968
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
1969
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
1970
+
1971
+ $("route-list").addEventListener("click", (event) => {
1972
+ const button = event.target.closest("[data-route]")
1973
+ if (!button) return
1974
+ state.route = button.dataset.route
1975
+ $("route-title").textContent = state.route
1976
+ const method = state.route.split(" ")[0]
1977
+ $("route-body").disabled = method === "GET" || method === "DELETE"
1978
+ })
1979
+ $("route-form").addEventListener("submit", async (event) => {
1980
+ event.preventDefault()
1981
+ if (!state.route) return showError(new Error("Choose a route first"))
1982
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
1983
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
1984
+ let body
1985
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
1986
+ try { body = JSON.parse($("route-body").value) }
1987
+ catch { return showError(new Error("Body is not JSON")) }
1988
+ }
1989
+ try {
1990
+ const data = await api(method, concrete, body)
1991
+ $("route-result").textContent = JSON.stringify(data, null, 2)
1992
+ } catch (error) {
1993
+ showError(error)
1994
+ }
1995
+ })
1996
+
1997
+ function mountPanels(panels) {
1998
+ const nav = $("nav")
1999
+ const views = $("views")
2000
+ for (const panel of panels) {
2001
+ const button = document.createElement("button")
2002
+ button.type = "button"
2003
+ button.dataset.view = panel.id
2004
+ button.textContent = panel.title
2005
+ nav.append(button)
2006
+ const section = document.createElement("section")
2007
+ section.className = "view"
2008
+ section.id = "view-" + panel.id
2009
+ section.hidden = true
2010
+ const title = document.createElement("h2")
2011
+ title.textContent = panel.title
2012
+ const lede = document.createElement("p")
2013
+ lede.className = "lede"
2014
+ lede.textContent = panel.description || ""
2015
+ const body = document.createElement("div")
2016
+ body.className = "panel-body"
2017
+ body.id = "panel-" + panel.id
2018
+ body.innerHTML = panel.html || ""
2019
+ section.append(title, lede, body)
2020
+ views.append(section)
2021
+ if (panel.script) {
2022
+ try {
2023
+ const run = new Function("root", "api", panel.script)
2024
+ run(body, panelApi)
2025
+ } catch (error) {
2026
+ const note = document.createElement("p")
2027
+ note.className = "banner show"
2028
+ note.textContent = error instanceof Error ? error.message : String(error)
2029
+ body.append(note)
2030
+ }
2031
+ }
2032
+ }
2033
+ }
2034
+
2035
+ loadNamespaces()
2036
+ .then(() => api("GET", "/ui/manifest"))
2037
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2038
+ .catch(showError)
2039
+ })()
2040
+ </script>
2041
+ </body>
2042
+ </html>`;
2043
+ };
2044
+ var htmlResponse = (body) => new Response(body, {
2045
+ status: 200,
2046
+ headers: {
2047
+ "content-type": "text/html; charset=utf-8",
2048
+ "cache-control": "no-store"
2049
+ }
2050
+ });
2051
+ var json2 = (body) => new Response(JSON.stringify(body), {
2052
+ status: 200,
2053
+ headers: { "content-type": "application/json; charset=utf-8" }
2054
+ });
2055
+ var adminUiRoutes = (service, ui) => {
2056
+ const shell = () => renderAdminDocument(service);
2057
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2058
+ return {
2059
+ "GET /ui": () => htmlResponse(document2()),
2060
+ "GET /ui/": () => htmlResponse(document2()),
2061
+ "GET /ui/manifest": () => json2({
2062
+ service,
2063
+ panels: (ui?.panels ?? []).map((panel) => ({
2064
+ id: panel.id,
2065
+ title: panel.title,
2066
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2067
+ html: panel.html,
2068
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2069
+ }))
2070
+ })
2071
+ };
2072
+ };
2073
+
1142
2074
  // ../../openapi/metadata/dist/types.js
1143
2075
  var EXTENSION_KEYS = {
1144
2076
  operation: "x-mockingbird",
@@ -1302,15 +2234,449 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1302
2234
  });
1303
2235
  };
1304
2236
 
2237
+ // ../core/dist/state-view.js
2238
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2239
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2240
+ var SAMPLE = 25;
2241
+ var WALK_LIMIT = 1e4;
2242
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2243
+ var fail2 = (status, message) => ({ ok: false, status, message });
2244
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2245
+ var kindOf = (value) => {
2246
+ if (value === null)
2247
+ return "null";
2248
+ if (Array.isArray(value))
2249
+ return "array";
2250
+ switch (typeof value) {
2251
+ case "string":
2252
+ return "string";
2253
+ case "number":
2254
+ return Number.isFinite(value) ? "number" : "unknown";
2255
+ case "boolean":
2256
+ return "boolean";
2257
+ case "object":
2258
+ return "object";
2259
+ default:
2260
+ return "unknown";
2261
+ }
2262
+ };
2263
+ var humanize = (name) => {
2264
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2265
+ if (words === "")
2266
+ return name;
2267
+ return words.charAt(0).toUpperCase() + words.slice(1);
2268
+ };
2269
+ var jsonValue = (value) => {
2270
+ if (value === void 0)
2271
+ return fail2(400, "value is required");
2272
+ try {
2273
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2274
+ } catch {
2275
+ return fail2(400, "value must be JSON");
2276
+ }
2277
+ };
2278
+ var ctorName = (value) => {
2279
+ const ctor = value.constructor;
2280
+ return typeof ctor?.name === "string" ? ctor.name : "";
2281
+ };
2282
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2283
+ var discoverCollections = (root) => {
2284
+ const found = [];
2285
+ const seen = /* @__PURE__ */ new Set();
2286
+ const visit = (value, depth) => {
2287
+ if (found.length + seen.size > WALK_LIMIT)
2288
+ return;
2289
+ if (value === null || typeof value !== "object")
2290
+ return;
2291
+ if (seen.has(value))
2292
+ return;
2293
+ seen.add(value);
2294
+ if (value instanceof Collection) {
2295
+ found.push(value);
2296
+ return;
2297
+ }
2298
+ if (value instanceof Map) {
2299
+ for (const child of value.values())
2300
+ visit(child, depth + 1);
2301
+ return;
2302
+ }
2303
+ if (value instanceof Set) {
2304
+ for (const child of value.values())
2305
+ visit(child, depth + 1);
2306
+ return;
2307
+ }
2308
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2309
+ return;
2310
+ if (Array.isArray(value)) {
2311
+ const cap = Math.min(value.length, 32);
2312
+ for (let i = 0; i < cap; i++)
2313
+ visit(value[i], depth + 1);
2314
+ return;
2315
+ }
2316
+ let children;
2317
+ try {
2318
+ children = Object.values(value);
2319
+ } catch {
2320
+ return;
2321
+ }
2322
+ for (const child of children)
2323
+ visit(child, depth + 1);
2324
+ };
2325
+ visit(root, 0);
2326
+ return found;
2327
+ };
2328
+ var storedNames = (sqlite, namespace) => {
2329
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2330
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2331
+ return [...records, ...sequences].map((row) => row.name);
2332
+ };
2333
+ var blankAccum = (name) => ({
2334
+ name,
2335
+ kinds: /* @__PURE__ */ new Set(),
2336
+ present: 0,
2337
+ nested: /* @__PURE__ */ new Map()
2338
+ });
2339
+ var absorb = (accum, value) => {
2340
+ const kind = kindOf(value);
2341
+ accum.kinds.add(kind);
2342
+ accum.present++;
2343
+ if (!isRecord3(value))
2344
+ return;
2345
+ for (const [key, child] of Object.entries(value)) {
2346
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2347
+ absorb(nested, child);
2348
+ accum.nested.set(key, nested);
2349
+ }
2350
+ };
2351
+ var finishField = (accum, samples) => {
2352
+ const kinds = [...accum.kinds];
2353
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2354
+ const field = {
2355
+ name: accum.name,
2356
+ kind,
2357
+ optional: accum.present < samples || kinds.includes("null")
2358
+ };
2359
+ if (accum.nested.size > 0) {
2360
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2361
+ }
2362
+ return field;
2363
+ };
2364
+ var inferFields = (records) => {
2365
+ if (records.length === 0)
2366
+ return [];
2367
+ const sample = records.slice(0, SAMPLE);
2368
+ const objects = sample.filter((record) => isRecord3(record.value));
2369
+ if (objects.length === 0) {
2370
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2371
+ const list = [...kinds];
2372
+ return [
2373
+ {
2374
+ name: "(value)",
2375
+ kind: list.length === 1 ? list[0] : "unknown",
2376
+ optional: false
2377
+ }
2378
+ ];
2379
+ }
2380
+ const root = /* @__PURE__ */ new Map();
2381
+ for (const record of objects) {
2382
+ for (const [key, value] of Object.entries(record.value)) {
2383
+ const accum = root.get(key) ?? blankAccum(key);
2384
+ absorb(accum, value);
2385
+ root.set(key, accum);
2386
+ }
2387
+ }
2388
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2389
+ };
2390
+ var mergeFields = (declared, inferred) => {
2391
+ const byName = /* @__PURE__ */ new Map();
2392
+ for (const field of inferred)
2393
+ byName.set(field.name, field);
2394
+ const ordered = [];
2395
+ const seen = /* @__PURE__ */ new Set();
2396
+ for (const field of declared ?? []) {
2397
+ const found = byName.get(field.name);
2398
+ seen.add(field.name);
2399
+ if (!found) {
2400
+ ordered.push({ ...field, optional: field.optional });
2401
+ continue;
2402
+ }
2403
+ ordered.push({
2404
+ ...found,
2405
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2406
+ optional: field.optional || found.optional,
2407
+ ...field.description !== void 0 ? { description: field.description } : {},
2408
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2409
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2410
+ });
2411
+ }
2412
+ for (const field of inferred) {
2413
+ if (!seen.has(field.name))
2414
+ ordered.push(field);
2415
+ }
2416
+ return ordered;
2417
+ };
2418
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2419
+ var readRecord = (collection, id) => {
2420
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2421
+ const row = rows.find((entry) => entry.id === id);
2422
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2423
+ };
2424
+ var inspectState = (scope) => {
2425
+ const declared = /* @__PURE__ */ new Map();
2426
+ for (const declaration of scope.declarations ?? []) {
2427
+ if (COLLECTION_NAME.test(declaration.name))
2428
+ declared.set(declaration.name, declaration);
2429
+ }
2430
+ const names = new Set(declared.keys());
2431
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2432
+ names.add(name);
2433
+ for (const collection of discoverCollections(scope.root)) {
2434
+ if (collection.namespace === scope.storageNamespace)
2435
+ names.add(collection.collectionName);
2436
+ }
2437
+ const collections = [];
2438
+ for (const name of names) {
2439
+ if (!COLLECTION_NAME.test(name))
2440
+ continue;
2441
+ const declaration = declared.get(name);
2442
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2443
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2444
+ const inferred = inferFields(records);
2445
+ const fields = mergeFields(declaration?.fields, inferred);
2446
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2447
+ collections.push({
2448
+ name,
2449
+ label: declaration?.label ?? humanize(name),
2450
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2451
+ count: collection.count(),
2452
+ source,
2453
+ fields,
2454
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2455
+ });
2456
+ }
2457
+ const order = /* @__PURE__ */ new Map();
2458
+ for (const [index, item] of (scope.declarations ?? []).entries())
2459
+ order.set(item.name, index);
2460
+ collections.sort((a, b) => {
2461
+ const left = order.get(a.name);
2462
+ const right = order.get(b.name);
2463
+ if (left !== void 0 && right !== void 0)
2464
+ return left - right;
2465
+ if (left !== void 0)
2466
+ return -1;
2467
+ if (right !== void 0)
2468
+ return 1;
2469
+ return a.name.localeCompare(b.name);
2470
+ });
2471
+ return {
2472
+ namespace: scope.namespace,
2473
+ storageNamespace: scope.storageNamespace,
2474
+ collections
2475
+ };
2476
+ };
2477
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2478
+ if (!COLLECTION_NAME.test(name))
2479
+ return fail2(400, "collection name is not allowed");
2480
+ const limit = query.limit ?? 50;
2481
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2482
+ return fail2(400, "limit must be an integer from 1 to 200");
2483
+ }
2484
+ const order = query.order ?? "newest";
2485
+ if (order !== "newest" && order !== "oldest")
2486
+ return fail2(400, 'order must be "newest" or "oldest"');
2487
+ const collection = collectionOf(sqlite, storageNamespace, name);
2488
+ const rows = collection.list({ order }).filter((row) => {
2489
+ if (query.after === void 0)
2490
+ return true;
2491
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2492
+ });
2493
+ const slice = rows.slice(0, limit);
2494
+ const last = slice.at(-1);
2495
+ return {
2496
+ ok: true,
2497
+ value: {
2498
+ collection: name,
2499
+ count: collection.count(),
2500
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2501
+ next: rows.length > limit && last ? last.seq : null
2502
+ }
2503
+ };
2504
+ };
2505
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2506
+ var readStateRecord = (scope, name, id) => {
2507
+ if (!COLLECTION_NAME.test(name))
2508
+ return fail2(400, "collection name is not allowed");
2509
+ if (!RECORD_ID.test(id))
2510
+ return fail2(400, "record id is not allowed");
2511
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2512
+ return record ? { ok: true, value: record } : fail2(404, `no record ${id} in ${name}`);
2513
+ };
2514
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail2(400, "id must be a single path segment");
2515
+ var createStateRecord = (scope, name, input) => {
2516
+ if (!COLLECTION_NAME.test(name))
2517
+ return fail2(400, "collection name is not allowed");
2518
+ const parsed = jsonValue(input.value);
2519
+ if (!parsed.ok)
2520
+ return parsed;
2521
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2522
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2523
+ const checked = requireId(id);
2524
+ if (!checked.ok)
2525
+ return checked;
2526
+ if (collection.has(checked.value))
2527
+ return fail2(409, `record ${checked.value} already exists`);
2528
+ const stored = collection.insert(checked.value, parsed.value);
2529
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2530
+ };
2531
+ var replaceStateRecord = (scope, name, id, value) => {
2532
+ if (!COLLECTION_NAME.test(name))
2533
+ return fail2(400, "collection name is not allowed");
2534
+ const checked = requireId(id);
2535
+ if (!checked.ok)
2536
+ return checked;
2537
+ const parsed = jsonValue(value);
2538
+ if (!parsed.ok)
2539
+ return parsed;
2540
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2541
+ if (!collection.has(checked.value))
2542
+ return fail2(404, `no record ${checked.value} in ${name}`);
2543
+ const stored = collection.update(checked.value, parsed.value);
2544
+ if (!stored)
2545
+ return fail2(404, `no record ${checked.value} in ${name}`);
2546
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2547
+ };
2548
+ var patchStateRecord = (scope, name, id, value) => {
2549
+ const current = readStateRecord(scope, name, id);
2550
+ if (!current.ok)
2551
+ return current;
2552
+ const parsed = jsonValue(value);
2553
+ if (!parsed.ok)
2554
+ return parsed;
2555
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2556
+ return replaceStateRecord(scope, name, id, next);
2557
+ };
2558
+ var deleteStateRecord = (scope, name, id) => {
2559
+ if (!COLLECTION_NAME.test(name))
2560
+ return fail2(400, "collection name is not allowed");
2561
+ const checked = requireId(id);
2562
+ if (!checked.ok)
2563
+ return checked;
2564
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2565
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail2(404, `no record ${checked.value} in ${name}`);
2566
+ };
2567
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2568
+ status,
2569
+ headers: { "content-type": "application/json; charset=utf-8" }
2570
+ });
2571
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2572
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2573
+ var integerParam = (value) => {
2574
+ if (value === null)
2575
+ return void 0;
2576
+ if (!/^-?\d+$/.test(value))
2577
+ return "bad";
2578
+ return Number(value);
2579
+ };
2580
+ var stateAdminRoutes = (routes) => {
2581
+ const open = (namespace) => {
2582
+ try {
2583
+ return { ok: true, value: routes.open(namespace) };
2584
+ } catch (error) {
2585
+ return fail2(400, error instanceof Error ? error.message : String(error));
2586
+ }
2587
+ };
2588
+ const wrote = (namespace) => {
2589
+ routes.afterWrite?.(namespace);
2590
+ };
2591
+ return {
2592
+ "GET /state": ({ namespace }) => {
2593
+ const scope = open(namespace);
2594
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2595
+ },
2596
+ "GET /state/:collection": ({ namespace, params, url }) => {
2597
+ const scope = open(namespace);
2598
+ if (!scope.ok)
2599
+ return fromResult(scope, 200);
2600
+ const limit = integerParam(url.searchParams.get("limit"));
2601
+ const after = integerParam(url.searchParams.get("after"));
2602
+ if (limit === "bad")
2603
+ return adminError2(400, "limit: expected an integer");
2604
+ if (after === "bad")
2605
+ return adminError2(400, "after: expected a sequence number");
2606
+ const order = url.searchParams.get("order");
2607
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2608
+ ...limit !== void 0 ? { limit } : {},
2609
+ ...after !== void 0 ? { after } : {},
2610
+ ...order === "newest" || order === "oldest" ? { order } : {}
2611
+ }), 200);
2612
+ },
2613
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2614
+ const scope = open(namespace);
2615
+ if (!scope.ok)
2616
+ return fromResult(scope, 200);
2617
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2618
+ },
2619
+ "POST /state/:collection": ({ namespace, params, body }) => {
2620
+ const scope = open(namespace);
2621
+ if (!scope.ok)
2622
+ return fromResult(scope, 201);
2623
+ if (!isRecord3(body) || !("value" in body)) {
2624
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2625
+ }
2626
+ const id = body.id;
2627
+ if (id !== void 0 && typeof id !== "string")
2628
+ return adminError2(400, "id must be a string");
2629
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2630
+ ...typeof id === "string" ? { id } : {},
2631
+ value: body.value
2632
+ });
2633
+ if (created.ok)
2634
+ wrote(namespace);
2635
+ return fromResult(created, 201);
2636
+ },
2637
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2638
+ const scope = open(namespace);
2639
+ if (!scope.ok)
2640
+ return fromResult(scope, 200);
2641
+ if (!isRecord3(body) || !("value" in body))
2642
+ return adminError2(400, 'expected {"value": <json>}');
2643
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2644
+ if (replaced.ok)
2645
+ wrote(namespace);
2646
+ return fromResult(replaced, 200);
2647
+ },
2648
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2649
+ const scope = open(namespace);
2650
+ if (!scope.ok)
2651
+ return fromResult(scope, 200);
2652
+ if (!isRecord3(body) || !("value" in body))
2653
+ return adminError2(400, 'expected {"value": <json>}');
2654
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2655
+ if (patched.ok)
2656
+ wrote(namespace);
2657
+ return fromResult(patched, 200);
2658
+ },
2659
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2660
+ const scope = open(namespace);
2661
+ if (!scope.ok)
2662
+ return fromResult(scope, 200);
2663
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2664
+ if (removed.ok)
2665
+ wrote(namespace);
2666
+ return fromResult(removed, 200);
2667
+ }
2668
+ };
2669
+ };
2670
+
1305
2671
  // ../core/dist/version.js
1306
- var PACKAGE_VERSION = true ? "1.3.0" : UNRELEASED_VERSION;
2672
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1307
2673
 
1308
2674
  // ../core/dist/webhooks.js
1309
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1310
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1311
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2675
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2676
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2677
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1312
2678
  var parseEndpoint = (value) => {
1313
- if (!isRecord3(value) || typeof value.url !== "string")
2679
+ if (!isRecord4(value) || typeof value.url !== "string")
1314
2680
  return "each endpoint needs a url";
1315
2681
  try {
1316
2682
  new URL(value.url);
@@ -1327,18 +2693,18 @@ var parseEndpoint = (value) => {
1327
2693
  const events = value.events ?? value.enabledEvents;
1328
2694
  if (Array.isArray(events))
1329
2695
  endpoint.events = events.map(String);
1330
- if (isRecord3(value.tags)) {
2696
+ if (isRecord4(value.tags)) {
1331
2697
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1332
2698
  }
1333
2699
  if (typeof value.account === "string")
1334
2700
  endpoint.tags = { ...endpoint.tags, account: value.account };
1335
- if (isRecord3(value.headers)) {
2701
+ if (isRecord4(value.headers)) {
1336
2702
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1337
2703
  }
1338
2704
  return endpoint;
1339
2705
  };
1340
2706
  var webhookAdminRoutes = (hub) => ({
1341
- "GET /webhooks": ({ url, namespace }) => json2(200, {
2707
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
1342
2708
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1343
2709
  const type = url.searchParams.get("type");
1344
2710
  return type === null || d.type === type;
@@ -1346,51 +2712,51 @@ var webhookAdminRoutes = (hub) => ({
1346
2712
  }),
1347
2713
  "GET /webhooks/events": ({ url, namespace }) => {
1348
2714
  const type = url.searchParams.get("type");
1349
- return json2(200, {
2715
+ return json4(200, {
1350
2716
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1351
2717
  });
1352
2718
  },
1353
2719
  "POST /webhooks/:id/replay": async ({ params }) => {
1354
2720
  const replayed = await hub.replay(params.id);
1355
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
2721
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1356
2722
  },
1357
2723
  "POST /webhooks/flush": async () => {
1358
2724
  await hub.flush();
1359
- return json2(200, { status: "ok" });
2725
+ return json4(200, { status: "ok" });
1360
2726
  },
1361
2727
  "POST /webhooks/faults": ({ body, namespace }) => {
1362
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1363
- return adminError2(400, "mode must be duplicate, reorder or drop");
2728
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2729
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1364
2730
  }
1365
2731
  const fault = { mode: body.mode };
1366
2732
  if (typeof body.count === "number")
1367
2733
  fault.count = body.count;
1368
2734
  hub.fault(namespace, fault);
1369
- return json2(201, { namespace, ...fault });
2735
+ return json4(201, { namespace, ...fault });
1370
2736
  },
1371
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
2737
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
1372
2738
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1373
2739
  ...rest,
1374
2740
  secret: secret ? "(set)" : null
1375
2741
  }))
1376
2742
  }),
1377
2743
  "PUT /webhook-endpoints": ({ body, namespace }) => {
1378
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
2744
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
1379
2745
  if (!Array.isArray(list))
1380
- return adminError2(400, "expected [{url, secret?, events?}]");
2746
+ return adminError3(400, "expected [{url, secret?, events?}]");
1381
2747
  const parsed = [];
1382
2748
  for (const each of list) {
1383
2749
  const endpoint = parseEndpoint(each);
1384
2750
  if (typeof endpoint === "string")
1385
- return adminError2(400, endpoint);
2751
+ return adminError3(400, endpoint);
1386
2752
  parsed.push(endpoint);
1387
2753
  }
1388
2754
  const set = hub.setEndpoints(namespace, parsed);
1389
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2755
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1390
2756
  },
1391
2757
  "DELETE /webhook-endpoints": ({ namespace }) => {
1392
2758
  hub.setEndpoints(namespace, []);
1393
- return json2(200, { status: "ok" });
2759
+ return json4(200, { status: "ok" });
1394
2760
  }
1395
2761
  });
1396
2762
  var parsePayload = (message) => {
@@ -1455,6 +2821,7 @@ var operationMatcher = (document2) => {
1455
2821
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1456
2822
  };
1457
2823
  var createRuntime = (options) => {
2824
+ assertAdminUi(options.adminUi);
1458
2825
  const sqlite = bootSqlite(options.sqlite);
1459
2826
  const clock = options.clock ?? createClock();
1460
2827
  const rng = createRng(options.seed ?? 0);
@@ -1661,6 +3028,19 @@ var createRuntime = (options) => {
1661
3028
  else
1662
3029
  timeline(name);
1663
3030
  };
3031
+ const declarationsFor = (namespace) => {
3032
+ const declared = options.state;
3033
+ if (!declared)
3034
+ return [];
3035
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3036
+ };
3037
+ const stateScope = (namespace) => ({
3038
+ sqlite,
3039
+ namespace,
3040
+ storageNamespace: storageNamespace(namespace),
3041
+ root: instance(namespace),
3042
+ declarations: declarationsFor(namespace)
3043
+ });
1664
3044
  const runtime = {
1665
3045
  name: options.name,
1666
3046
  sqlite,
@@ -1699,6 +3079,7 @@ var createRuntime = (options) => {
1699
3079
  branch,
1700
3080
  checkout,
1701
3081
  timeline,
3082
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
1702
3083
  fetch: async (incoming) => {
1703
3084
  let request = incoming;
1704
3085
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -1892,11 +3273,20 @@ var createRuntime = (options) => {
1892
3273
  ...credentialRoutes(credentials),
1893
3274
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
1894
3275
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
1895
- ...options.admin?.(runtime) ?? {}
3276
+ ...options.admin?.(runtime) ?? {},
3277
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3278
+ // beside these; it does not replace `/state` or `/ui`.
3279
+ ...stateAdminRoutes({
3280
+ open: stateScope,
3281
+ afterWrite: (namespace) => {
3282
+ checkpoint(namespace, "main");
3283
+ }
3284
+ }),
3285
+ ...adminUiRoutes(options.name, options.adminUi)
1896
3286
  },
1897
3287
  adminKey: options.adminKey
1898
3288
  });
1899
- return runtime;
3289
+ return defineMock(runtime);
1900
3290
  };
1901
3291
  var mutableResponse = (response) => {
1902
3292
  try {
@@ -2132,11 +3522,11 @@ var PAYLOAD_CMS_PRESETS = {
2132
3522
  rules: [{ pathPrefix: "/api/", latencyMs: 1e4 }]
2133
3523
  }
2134
3524
  };
2135
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2136
- var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2137
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3525
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3526
+ var adminError4 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
3527
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2138
3528
  var toDocs = (value, now) => {
2139
- if (!Array.isArray(value) || !value.every(isRecord4)) return "expected {docs: [{\u2026}]}";
3529
+ if (!Array.isArray(value) || !value.every(isRecord5)) return "expected {docs: [{\u2026}]}";
2140
3530
  return value.map((doc, index) => ({
2141
3531
  createdAt: now,
2142
3532
  updatedAt: now,
@@ -2145,29 +3535,29 @@ var toDocs = (value, now) => {
2145
3535
  }));
2146
3536
  };
2147
3537
  var adminRoutes = (runtime) => ({
2148
- "GET /collections": ({ namespace }) => json3(200, { collections: runtime.instance(namespace).collections() }),
3538
+ "GET /collections": ({ namespace }) => json5(200, { collections: runtime.instance(namespace).collections() }),
2149
3539
  "GET /collections/:slug": ({ params, namespace }) => {
2150
3540
  const collection = runtime.instance(namespace).state.get(params.slug);
2151
- return collection ? json3(200, collection) : adminError3(404, `no collection ${params.slug}`);
3541
+ return collection ? json5(200, collection) : adminError4(404, `no collection ${params.slug}`);
2152
3542
  },
2153
3543
  "PUT /collections/:slug": ({ params, body, namespace }) => {
2154
3544
  const docs = toDocs(
2155
- isRecord4(body) ? body.docs : void 0,
3545
+ isRecord5(body) ? body.docs : void 0,
2156
3546
  new Date(runtime.clock.now()).toISOString()
2157
3547
  );
2158
- if (typeof docs === "string") return adminError3(400, docs);
2159
- return json3(200, runtime.instance(namespace).state.replace(params.slug, docs));
3548
+ if (typeof docs === "string") return adminError4(400, docs);
3549
+ return json5(200, runtime.instance(namespace).state.replace(params.slug, docs));
2160
3550
  },
2161
3551
  "POST /collections/:slug/docs": ({ params, body, namespace }) => {
2162
- if (!isRecord4(body)) return adminError3(400, "expected a document object");
2163
- return json3(201, runtime.instance(namespace).addDoc(params.slug, body));
3552
+ if (!isRecord5(body)) return adminError4(400, "expected a document object");
3553
+ return json5(201, runtime.instance(namespace).addDoc(params.slug, body));
2164
3554
  },
2165
3555
  "PATCH /collections/:slug/docs/:id": ({ params, body, namespace }) => {
2166
- if (!isRecord4(body)) return adminError3(400, "expected a partial document object");
3556
+ if (!isRecord5(body)) return adminError4(400, "expected a partial document object");
2167
3557
  const doc = runtime.instance(namespace).updateDoc(params.slug, Number(params.id), body);
2168
- return doc ? json3(200, doc) : adminError3(404, `no document ${params.slug}/${params.id}`);
3558
+ return doc ? json5(200, doc) : adminError4(404, `no document ${params.slug}/${params.id}`);
2169
3559
  },
2170
- "DELETE /collections/:slug/docs/:id": ({ params, namespace }) => runtime.instance(namespace).deleteDoc(params.slug, Number(params.id)) ? json3(200, { deleted: true }) : adminError3(404, `no document ${params.slug}/${params.id}`)
3560
+ "DELETE /collections/:slug/docs/:id": ({ params, namespace }) => runtime.instance(namespace).deleteDoc(params.slug, Number(params.id)) ? json5(200, { deleted: true }) : adminError4(404, `no document ${params.slug}/${params.id}`)
2171
3561
  });
2172
3562
  var createRuntime2 = (options = {}) => createRuntime({
2173
3563
  name: PAYLOAD_CMS_NAMESPACE,
@@ -2210,8 +3600,8 @@ var OPERATORS = [
2210
3600
  "like",
2211
3601
  "contains"
2212
3602
  ];
2213
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2214
- var fieldValue = (doc, path) => path.split(".").reduce((value, key) => isRecord5(value) ? value[key] : void 0, doc);
3603
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3604
+ var fieldValue = (doc, path) => path.split(".").reduce((value, key) => isRecord6(value) ? value[key] : void 0, doc);
2215
3605
  var cast = (raw, sample) => {
2216
3606
  if (typeof raw !== "string") return raw;
2217
3607
  if (typeof sample === "boolean") return raw === "true" ? true : raw === "false" ? false : raw;
@@ -2257,11 +3647,11 @@ var test = (operator, actual, raw) => {
2257
3647
  };
2258
3648
  var compileWhere = (where, fields) => {
2259
3649
  if (where === void 0) return { ok: true, match: () => true };
2260
- if (!isRecord5(where)) return { ok: false, message: "The where query is malformed." };
3650
+ if (!isRecord6(where)) return { ok: false, message: "The where query is malformed." };
2261
3651
  const parts = [];
2262
3652
  for (const [key, condition] of Object.entries(where)) {
2263
3653
  if (key === "and" || key === "or") {
2264
- const nested = (Array.isArray(condition) ? condition : isRecord5(condition) ? Object.values(condition) : []).map((item) => compileWhere(item, fields));
3654
+ const nested = (Array.isArray(condition) ? condition : isRecord6(condition) ? Object.values(condition) : []).map((item) => compileWhere(item, fields));
2265
3655
  const failed = nested.find((c) => !c.ok);
2266
3656
  if (failed) return failed;
2267
3657
  const matchers = nested.map((c) => c.match);
@@ -2274,7 +3664,7 @@ var compileWhere = (where, fields) => {
2274
3664
  if (!fields.has(root)) {
2275
3665
  return { ok: false, message: `The following path cannot be queried: ${key}` };
2276
3666
  }
2277
- if (!isRecord5(condition))
3667
+ if (!isRecord6(condition))
2278
3668
  return { ok: false, message: `The following path cannot be queried: ${key}` };
2279
3669
  for (const [operator, value] of Object.entries(condition)) {
2280
3670
  if (!OPERATORS.includes(operator)) {
@@ -2443,4 +3833,4 @@ export {
2443
3833
  compileWhere,
2444
3834
  PayloadCmsAPI
2445
3835
  };
2446
- //# sourceMappingURL=chunk-BB273WDT.js.map
3836
+ //# sourceMappingURL=chunk-2ZHNDZ7B.js.map