@crvouga/mockingbird-service-posthog 1.2.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;
@@ -1151,6 +1153,936 @@ var clearNamespace = (sqlite, namespace) => {
1151
1153
  });
1152
1154
  };
1153
1155
 
1156
+ // ../core/dist/surface.js
1157
+ var defineMock = (runtime) => runtime;
1158
+ var STANDARD_ADMIN_ROUTES = [
1159
+ "GET /",
1160
+ "POST /reset",
1161
+ "GET /namespaces",
1162
+ "GET /clock",
1163
+ "POST /clock",
1164
+ "GET /faults",
1165
+ "POST /faults",
1166
+ "DELETE /faults",
1167
+ "POST /snapshots",
1168
+ "POST /snapshots/:id/restore",
1169
+ "DELETE /snapshots/:id",
1170
+ "GET /timeline",
1171
+ "POST /checkpoints",
1172
+ "POST /branches/:name",
1173
+ "POST /branches/:name/checkout",
1174
+ "GET /requests",
1175
+ "DELETE /requests",
1176
+ "GET /metrics",
1177
+ "DELETE /metrics",
1178
+ "GET /credentials",
1179
+ "PUT /credentials",
1180
+ "DELETE /credentials",
1181
+ "GET /state",
1182
+ "GET /state/:collection",
1183
+ "GET /state/:collection/:id",
1184
+ "POST /state/:collection",
1185
+ "PUT /state/:collection/:id",
1186
+ "PATCH /state/:collection/:id",
1187
+ "DELETE /state/:collection/:id",
1188
+ "GET /ui",
1189
+ "GET /ui/",
1190
+ "GET /ui/manifest"
1191
+ ];
1192
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1193
+ var assertAdminUi = (ui) => {
1194
+ if (!ui?.panels)
1195
+ return;
1196
+ const seen = /* @__PURE__ */ new Set();
1197
+ for (const panel of ui.panels) {
1198
+ if (!PANEL_ID.test(panel.id)) {
1199
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1200
+ }
1201
+ if (seen.has(panel.id))
1202
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1203
+ seen.add(panel.id);
1204
+ if (panel.title.trim() === "")
1205
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1206
+ }
1207
+ };
1208
+
1209
+ // ../core/dist/admin-ui.js
1210
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1211
+ switch (char) {
1212
+ case "&":
1213
+ return "&amp;";
1214
+ case "<":
1215
+ return "&lt;";
1216
+ case ">":
1217
+ return "&gt;";
1218
+ case '"':
1219
+ return "&quot;";
1220
+ default:
1221
+ return "&#39;";
1222
+ }
1223
+ });
1224
+ var renderAdminDocument = (service) => {
1225
+ const name = escapeHtml(service);
1226
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1227
+ return `<!DOCTYPE html>
1228
+ <html lang="en">
1229
+ <head>
1230
+ <meta charset="utf-8">
1231
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1232
+ <meta name="color-scheme" content="light dark">
1233
+ <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">
1234
+ <title>${name} admin</title>
1235
+ <style>
1236
+ :root {
1237
+ color-scheme: light;
1238
+ --bg: #f6f5f2;
1239
+ --bg-elev: #ffffff;
1240
+ --bg-muted: #eeece6;
1241
+ --bg-inset: #f3f1eb;
1242
+ --line: #e2dfd6;
1243
+ --line-strong: #d0ccc1;
1244
+ --ink: #1c1915;
1245
+ --muted: #5e584f;
1246
+ --faint: #8a8378;
1247
+ --accent: #3d4f3a;
1248
+ --accent-ink: #f7f6f2;
1249
+ --accent-soft: #e5ece2;
1250
+ --ok: #1f7a45;
1251
+ --ok-soft: #e5f4eb;
1252
+ --warn: #9a6700;
1253
+ --warn-soft: #fbf3df;
1254
+ --err: #a33b32;
1255
+ --err-soft: #fdecea;
1256
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1257
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1258
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1259
+ --radius: 14px;
1260
+ --header: 60px;
1261
+ --nav: 220px;
1262
+ }
1263
+ :root[data-theme="dark"] {
1264
+ color-scheme: dark;
1265
+ --bg: #141311;
1266
+ --bg-elev: #1e1c19;
1267
+ --bg-muted: #26231f;
1268
+ --bg-inset: #181715;
1269
+ --line: #34302b;
1270
+ --line-strong: #4a453d;
1271
+ --ink: #f4f1ea;
1272
+ --muted: #c4bdb1;
1273
+ --faint: #8f877c;
1274
+ --accent: #c5d5b8;
1275
+ --accent-ink: #1a2118;
1276
+ --accent-soft: #2a3328;
1277
+ --ok: #8fd6a8;
1278
+ --ok-soft: #1a2e22;
1279
+ --warn: #f0cc78;
1280
+ --warn-soft: #332911;
1281
+ --err: #f0a8a2;
1282
+ --err-soft: #3a201e;
1283
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1284
+ }
1285
+ @media (prefers-color-scheme: dark) {
1286
+ :root:not([data-theme="light"]) {
1287
+ color-scheme: dark;
1288
+ --bg: #141311;
1289
+ --bg-elev: #1e1c19;
1290
+ --bg-muted: #26231f;
1291
+ --bg-inset: #181715;
1292
+ --line: #34302b;
1293
+ --line-strong: #4a453d;
1294
+ --ink: #f4f1ea;
1295
+ --muted: #c4bdb1;
1296
+ --faint: #8f877c;
1297
+ --accent: #c5d5b8;
1298
+ --accent-ink: #1a2118;
1299
+ --accent-soft: #2a3328;
1300
+ --ok: #8fd6a8;
1301
+ --ok-soft: #1a2e22;
1302
+ --warn: #f0cc78;
1303
+ --warn-soft: #332911;
1304
+ --err: #f0a8a2;
1305
+ --err-soft: #3a201e;
1306
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1307
+ }
1308
+ }
1309
+ * { box-sizing: border-box; }
1310
+ html, body { margin: 0; height: 100%; }
1311
+ body {
1312
+ font-family: var(--sans);
1313
+ background: var(--bg);
1314
+ color: var(--ink);
1315
+ line-height: 1.45;
1316
+ padding-left: env(safe-area-inset-left);
1317
+ padding-right: env(safe-area-inset-right);
1318
+ -webkit-text-size-adjust: 100%;
1319
+ }
1320
+ button, input, select, textarea { font: inherit; color: inherit; }
1321
+ button { cursor: pointer; }
1322
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1323
+ @media (prefers-reduced-motion: reduce) {
1324
+ * { scroll-behavior: auto !important; transition: none !important; }
1325
+ }
1326
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1327
+ header.top {
1328
+ position: sticky; top: 0; z-index: 5;
1329
+ display: flex; align-items: center; gap: 12px;
1330
+ min-height: var(--header); padding: 10px 16px;
1331
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1332
+ border-bottom: 1px solid var(--line);
1333
+ backdrop-filter: blur(10px);
1334
+ }
1335
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1336
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1337
+ .brand span { color: var(--faint); font-size: 12px; }
1338
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1339
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1340
+ label.field input, label.field select, .controls input[type="password"] {
1341
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1342
+ padding: 7px 8px; min-height: 36px;
1343
+ }
1344
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1345
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1346
+ background: var(--bg-elev);
1347
+ }
1348
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1349
+ .btn-quiet { background: transparent; }
1350
+ .btn-danger { color: var(--err); }
1351
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1352
+ record or the full nav row would widen the page past the viewport. */
1353
+ .layout {
1354
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1355
+ flex: 1; min-height: 0; min-width: 0;
1356
+ }
1357
+ nav.side {
1358
+ border-right: 1px solid var(--line); padding: 12px;
1359
+ display: flex; flex-direction: column; gap: 4px;
1360
+ background: var(--bg-elev);
1361
+ }
1362
+ nav.side button {
1363
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1364
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1365
+ }
1366
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1367
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1368
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1369
+ .lede { margin: 0 0 16px; color: var(--muted); }
1370
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1371
+ .card {
1372
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1373
+ padding: 14px 16px; box-shadow: var(--shadow);
1374
+ }
1375
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1376
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1377
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1378
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1379
+ .collection {
1380
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1381
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1382
+ }
1383
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1384
+ .collection small { display: block; color: var(--faint); }
1385
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1386
+ .chip {
1387
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1388
+ border-radius: 999px; padding: 4px 8px;
1389
+ }
1390
+ .chip i { color: var(--faint); font-style: normal; }
1391
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1392
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1393
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1394
+ tr.clickable { cursor: pointer; }
1395
+ tr.clickable:hover { background: var(--bg-muted); }
1396
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1397
+ pre {
1398
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1399
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1400
+ }
1401
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1402
+ .banner {
1403
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1404
+ background: var(--err-soft); color: var(--err);
1405
+ }
1406
+ .banner.show { display: block; }
1407
+ .empty { color: var(--muted); padding: 24px 8px; }
1408
+ dialog {
1409
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1410
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1411
+ }
1412
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1413
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1414
+ textarea {
1415
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1416
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1417
+ font-family: var(--mono); font-size: 12px;
1418
+ }
1419
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1420
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1421
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1422
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1423
+ .status-2 { color: var(--ok); }
1424
+ .status-4, .status-5, .status-0 { color: var(--err); }
1425
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1426
+ .route {
1427
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1428
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1429
+ }
1430
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1431
+ @media (max-width: 800px) {
1432
+ header.top {
1433
+ align-items: stretch; flex-direction: column;
1434
+ padding-top: max(10px, env(safe-area-inset-top));
1435
+ }
1436
+ input, select, textarea { font-size: 16px; }
1437
+ .controls { width: 100%; }
1438
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1439
+ .layout { grid-template-columns: minmax(0, 1fr); }
1440
+ nav.side {
1441
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1442
+ border-right: 0; border-bottom: 1px solid var(--line);
1443
+ padding: 8px;
1444
+ }
1445
+ nav.side button { white-space: nowrap; flex: none; }
1446
+ .split { grid-template-columns: minmax(0, 1fr); }
1447
+ main { padding: 14px; }
1448
+ table, thead, tbody, tr, th, td { display: block; }
1449
+ thead { display: none; }
1450
+ tr {
1451
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1452
+ background: var(--bg-elev); min-width: 0;
1453
+ }
1454
+ td {
1455
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1456
+ min-width: 0; overflow-wrap: anywhere;
1457
+ }
1458
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1459
+ .route { grid-template-columns: 72px 1fr; }
1460
+ .route button { grid-column: 1 / -1; }
1461
+ }
1462
+ </style>
1463
+ </head>
1464
+ <body>
1465
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1466
+ <header class="top">
1467
+ <div class="brand">
1468
+ <strong>${name}</strong>
1469
+ <span>Mockingbird admin</span>
1470
+ </div>
1471
+ <div class="controls">
1472
+ <label class="field">Namespace
1473
+ <select id="namespace" aria-label="Namespace"></select>
1474
+ </label>
1475
+ <label class="field">Admin key
1476
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1477
+ </label>
1478
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1479
+ <button class="btn" id="refresh" type="button">Refresh</button>
1480
+ </div>
1481
+ </header>
1482
+ <div class="layout">
1483
+ <nav class="side" id="nav" aria-label="Admin sections">
1484
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1485
+ <button type="button" data-view="state">State</button>
1486
+ <button type="button" data-view="clock">Clock</button>
1487
+ <button type="button" data-view="faults">Faults</button>
1488
+ <button type="button" data-view="journal">Journal</button>
1489
+ <button type="button" data-view="routes">Routes</button>
1490
+ </nav>
1491
+ <main id="views">
1492
+ <p class="banner" id="banner" role="alert"></p>
1493
+ <section class="view" id="view-overview">
1494
+ <h2>Overview</h2>
1495
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1496
+ <div class="grid" id="overview-cards"></div>
1497
+ <h3>Recent requests</h3>
1498
+ <div id="overview-requests"></div>
1499
+ </section>
1500
+ <section class="view" id="view-state" hidden>
1501
+ <h2>State</h2>
1502
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1503
+ <div class="split">
1504
+ <div id="collections"></div>
1505
+ <div>
1506
+ <div id="schema"></div>
1507
+ <div class="row-actions">
1508
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1509
+ </div>
1510
+ <div id="records"></div>
1511
+ </div>
1512
+ </div>
1513
+ </section>
1514
+ <section class="view" id="view-clock" hidden>
1515
+ <h2>Clock</h2>
1516
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1517
+ <div class="card" id="clock-readout"></div>
1518
+ <div class="row-actions">
1519
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1520
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1521
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1522
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1523
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1524
+ <button class="btn" id="freeze" type="button">Freeze</button>
1525
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1526
+ </div>
1527
+ <form id="clock-set" class="row-actions">
1528
+ <label class="field">Set instant
1529
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1530
+ </label>
1531
+ <button class="btn-primary" type="submit">Set</button>
1532
+ </form>
1533
+ </section>
1534
+ <section class="view" id="view-faults" hidden>
1535
+ <h2>Faults</h2>
1536
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1537
+ <form id="fault-form" class="card stack">
1538
+ <label class="field">Preset
1539
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1540
+ </label>
1541
+ <label class="field">Status
1542
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1543
+ </label>
1544
+ <label class="field">Path prefix
1545
+ <input id="fault-path" placeholder="/v1">
1546
+ </label>
1547
+ <label class="field">Method
1548
+ <input id="fault-method" placeholder="GET">
1549
+ </label>
1550
+ <div class="dialog-actions">
1551
+ <button class="btn-primary" type="submit">Add fault</button>
1552
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1553
+ </div>
1554
+ </form>
1555
+ <div id="fault-list"></div>
1556
+ </section>
1557
+ <section class="view" id="view-journal" hidden>
1558
+ <h2>Journal</h2>
1559
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1560
+ <div class="row-actions">
1561
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1562
+ </div>
1563
+ <div id="journal"></div>
1564
+ </section>
1565
+ <section class="view" id="view-routes" hidden>
1566
+ <h2>Routes</h2>
1567
+ <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>
1568
+ <div id="route-list"></div>
1569
+ <form id="route-form" class="card stack">
1570
+ <strong id="route-title">Select a route</strong>
1571
+ <label class="field">JSON body
1572
+ <textarea id="route-body" placeholder="{ }"></textarea>
1573
+ </label>
1574
+ <div class="dialog-actions">
1575
+ <button class="btn-primary" type="submit">Send</button>
1576
+ </div>
1577
+ <pre id="route-result">Response will show here.</pre>
1578
+ </form>
1579
+ </section>
1580
+ </main>
1581
+ </div>
1582
+ </div>
1583
+ <dialog id="editor">
1584
+ <form method="dialog" id="editor-form">
1585
+ <strong id="editor-title">Record</strong>
1586
+ <label class="field">Id
1587
+ <input id="editor-id" required>
1588
+ </label>
1589
+ <label class="field">JSON value
1590
+ <textarea id="editor-value"></textarea>
1591
+ </label>
1592
+ <div class="dialog-actions">
1593
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1594
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1595
+ <button class="btn-primary" type="submit" value="save">Save</button>
1596
+ </div>
1597
+ </form>
1598
+ </dialog>
1599
+ <script>
1600
+ (() => {
1601
+ const STANDARD = new Set(${standard})
1602
+ const state = {
1603
+ namespace: "default",
1604
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1605
+ view: "overview",
1606
+ collection: "",
1607
+ shape: null,
1608
+ route: null,
1609
+ editing: null
1610
+ }
1611
+ const $ = (id) => document.getElementById(id)
1612
+ const banner = $("banner")
1613
+ const keyInput = $("admin-key")
1614
+ keyInput.value = state.key
1615
+ const params = new URLSearchParams(location.search)
1616
+ if (params.get("key")) {
1617
+ state.key = params.get("key")
1618
+ keyInput.value = state.key
1619
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1620
+ params.delete("key")
1621
+ const next = params.toString()
1622
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1623
+ }
1624
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1625
+
1626
+ const showError = (error) => {
1627
+ banner.textContent = error instanceof Error ? error.message : String(error)
1628
+ banner.classList.add("show")
1629
+ }
1630
+ const clearError = () => banner.classList.remove("show")
1631
+
1632
+ async function originGet(path) {
1633
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1634
+ if (!response.ok) throw new Error(response.status + " " + path)
1635
+ return response.json()
1636
+ }
1637
+ async function api(method, path, body) {
1638
+ const headers = { accept: "application/json" }
1639
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1640
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1641
+ if (body !== undefined) headers["content-type"] = "application/json"
1642
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1643
+ method,
1644
+ headers,
1645
+ body: body === undefined ? undefined : JSON.stringify(body)
1646
+ })
1647
+ const text = await response.text()
1648
+ let data = null
1649
+ if (text) {
1650
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1651
+ }
1652
+ if (response.status === 401) {
1653
+ keyInput.focus()
1654
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1655
+ }
1656
+ if (!response.ok) {
1657
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1658
+ }
1659
+ return data
1660
+ }
1661
+ const panelApi = {
1662
+ get: (path) => api("GET", path),
1663
+ send: (method, path, body) => api(method, path, body),
1664
+ namespace: () => state.namespace
1665
+ }
1666
+
1667
+ function setTheme(theme) {
1668
+ if (theme) document.documentElement.dataset.theme = theme
1669
+ else delete document.documentElement.dataset.theme
1670
+ }
1671
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1672
+ if (storedTheme) setTheme(storedTheme)
1673
+ $("theme").addEventListener("click", () => {
1674
+ const current = document.documentElement.dataset.theme
1675
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1676
+ const next = dark ? "light" : "dark"
1677
+ localStorage.setItem("mockingbird-admin-theme", next)
1678
+ setTheme(next)
1679
+ })
1680
+
1681
+ function show(view) {
1682
+ state.view = view
1683
+ for (const button of document.querySelectorAll("#nav button")) {
1684
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1685
+ }
1686
+ for (const section of document.querySelectorAll("main .view")) {
1687
+ section.hidden = section.id !== "view-" + view
1688
+ }
1689
+ }
1690
+ document.getElementById("nav").addEventListener("click", (event) => {
1691
+ const button = event.target.closest("button[data-view]")
1692
+ if (!button) return
1693
+ show(button.dataset.view)
1694
+ refresh().catch(showError)
1695
+ })
1696
+
1697
+ function cards(items) {
1698
+ return '<div class="grid">' + items.map((item) =>
1699
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1700
+ ).join("") + "</div>"
1701
+ }
1702
+ function table(columns, rows) {
1703
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1704
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1705
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1706
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1707
+ ).join("") + "</tr>").join("")
1708
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1709
+ }
1710
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1711
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1712
+ }[char]))
1713
+ const preview = (value) => {
1714
+ const text = JSON.stringify(value)
1715
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1716
+ }
1717
+ const when = (epoch) => {
1718
+ const date = new Date(epoch)
1719
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1720
+ }
1721
+ const clockCard = (epoch) => {
1722
+ const date = new Date(epoch)
1723
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1724
+ const iso = date.toISOString()
1725
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1726
+ }
1727
+
1728
+ async function loadNamespaces() {
1729
+ const data = await api("GET", "/namespaces")
1730
+ const select = $("namespace")
1731
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1732
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1733
+ select.innerHTML = names.map((name) =>
1734
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1735
+ ).join("")
1736
+ select.value = state.namespace
1737
+ }
1738
+
1739
+ async function renderOverview() {
1740
+ const [health, shape, clock, journal] = await Promise.all([
1741
+ originGet("/health"),
1742
+ api("GET", "/state"),
1743
+ api("GET", "/clock"),
1744
+ api("GET", "/requests?limit=8")
1745
+ ])
1746
+ state.shape = shape
1747
+ $("overview-cards").innerHTML = cards([
1748
+ { k: "Service", v: esc(health.service || "${name}") },
1749
+ { k: "Status", v: esc(health.status || "ok") },
1750
+ { k: "Namespace", v: esc(state.namespace) },
1751
+ { k: "Collections", v: String(shape.collections.length) },
1752
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1753
+ { k: "Clock", v: clockCard(clock.now) }
1754
+ ])
1755
+ const requests = (journal && journal.requests) || []
1756
+ $("overview-requests").innerHTML = table(
1757
+ [
1758
+ { label: "Method", cell: (row) => esc(row.method) },
1759
+ { label: "Path", cell: (row) => esc(row.path) },
1760
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1761
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1762
+ ],
1763
+ requests
1764
+ )
1765
+ }
1766
+
1767
+ function schemaChips(collection) {
1768
+ if (!collection || collection.fields.length === 0) {
1769
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
1770
+ }
1771
+ return '<div class="chips">' + collection.fields.map((field) =>
1772
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
1773
+ ).join("") + "</div>"
1774
+ }
1775
+
1776
+ async function renderState() {
1777
+ const shape = await api("GET", "/state")
1778
+ state.shape = shape
1779
+ const host = $("collections")
1780
+ if (shape.collections.length === 0) {
1781
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
1782
+ $("schema").innerHTML = ""
1783
+ $("records").innerHTML = ""
1784
+ return
1785
+ }
1786
+ if (!shape.collections.some((item) => item.name === state.collection)) {
1787
+ state.collection = shape.collections[0].name
1788
+ }
1789
+ host.innerHTML = shape.collections.map((item) =>
1790
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
1791
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
1792
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
1793
+ ).join("")
1794
+ const selected = shape.collections.find((item) => item.name === state.collection)
1795
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
1796
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
1797
+ schemaChips(selected)
1798
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
1799
+ const rows = page.records.map((record) => ({
1800
+ ...record,
1801
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
1802
+ }))
1803
+ $("records").innerHTML = table(
1804
+ [
1805
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
1806
+ { label: "Seq", cell: (row) => esc(row.seq) },
1807
+ { label: "Value", cell: (row) => preview(row.value) }
1808
+ ],
1809
+ rows
1810
+ )
1811
+ }
1812
+
1813
+ async function renderClock() {
1814
+ const clock = await api("GET", "/clock")
1815
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
1816
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
1817
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
1818
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
1819
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
1820
+ }
1821
+
1822
+ async function renderFaults() {
1823
+ const [faults, presets] = await Promise.all([
1824
+ api("GET", "/faults"),
1825
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
1826
+ ])
1827
+ const select = $("fault-preset")
1828
+ const current = select.value
1829
+ const list = presets.presets || []
1830
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
1831
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
1832
+ ).join("")
1833
+ select.value = current
1834
+ const rules = faults.faults || []
1835
+ $("fault-list").innerHTML = table(
1836
+ [
1837
+ { label: "Id", cell: (row) => esc(row.id) },
1838
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
1839
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
1840
+ ],
1841
+ rules
1842
+ )
1843
+ }
1844
+
1845
+ async function renderJournal() {
1846
+ const journal = await api("GET", "/requests?limit=100")
1847
+ $("journal").innerHTML = table(
1848
+ [
1849
+ { label: "When", cell: (row) => esc(row.at || "") },
1850
+ { label: "Method", cell: (row) => esc(row.method) },
1851
+ { label: "Path", cell: (row) => esc(row.path) },
1852
+ { label: "Status", cell: (row) => esc(row.status) },
1853
+ { label: "ms", cell: (row) => esc(row.durationMs) }
1854
+ ],
1855
+ journal.requests || []
1856
+ )
1857
+ }
1858
+
1859
+ async function renderRoutes() {
1860
+ const data = await api("GET", "/")
1861
+ const routes = data.routes || []
1862
+ $("route-list").innerHTML = routes.map((route) => {
1863
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
1864
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
1865
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
1866
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
1867
+ }).join("")
1868
+ }
1869
+
1870
+ const renderers = {
1871
+ overview: renderOverview,
1872
+ state: renderState,
1873
+ clock: renderClock,
1874
+ faults: renderFaults,
1875
+ journal: renderJournal,
1876
+ routes: renderRoutes
1877
+ }
1878
+
1879
+ async function refresh() {
1880
+ clearError()
1881
+ if (state.view in renderers) await renderers[state.view]()
1882
+ }
1883
+
1884
+ $("namespace").addEventListener("change", () => {
1885
+ state.namespace = $("namespace").value
1886
+ refresh().catch(showError)
1887
+ })
1888
+ keyInput.addEventListener("change", () => {
1889
+ state.key = keyInput.value.trim()
1890
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1891
+ refresh().catch(showError)
1892
+ })
1893
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
1894
+
1895
+ $("collections").addEventListener("click", (event) => {
1896
+ const button = event.target.closest("[data-collection]")
1897
+ if (!button) return
1898
+ state.collection = button.dataset.collection
1899
+ renderState().catch(showError)
1900
+ })
1901
+ $("records").addEventListener("click", (event) => {
1902
+ const row = event.target.closest("[data-id]")
1903
+ if (!row) return
1904
+ openEditor(row.dataset.id).catch(showError)
1905
+ })
1906
+
1907
+ const editor = $("editor")
1908
+ async function openEditor(id) {
1909
+ state.editing = id || null
1910
+ $("editor-title").textContent = id ? "Edit record" : "New record"
1911
+ $("editor-id").value = id || ""
1912
+ $("editor-id").readOnly = Boolean(id)
1913
+ $("editor-delete").hidden = !id
1914
+ if (id) {
1915
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1916
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
1917
+ } else {
1918
+ $("editor-value").value = "{\\n \\n}"
1919
+ }
1920
+ editor.showModal()
1921
+ }
1922
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
1923
+ $("editor-form").addEventListener("submit", (event) => {
1924
+ const submitter = event.submitter
1925
+ if (!submitter || submitter.value !== "save") return
1926
+ event.preventDefault()
1927
+ let value
1928
+ try { value = JSON.parse($("editor-value").value) }
1929
+ catch { showError(new Error("Value is not JSON")); return }
1930
+ const id = $("editor-id").value.trim()
1931
+ const path = "/state/" + encodeURIComponent(state.collection)
1932
+ const request = state.editing
1933
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
1934
+ : api("POST", path, { id: id || undefined, value })
1935
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
1936
+ })
1937
+ $("editor-delete").addEventListener("click", () => {
1938
+ const id = state.editing
1939
+ if (!id) return
1940
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1941
+ .then(() => { editor.close(); return renderState() })
1942
+ .catch(showError)
1943
+ })
1944
+
1945
+ document.querySelectorAll("[data-advance]").forEach((button) => {
1946
+ button.addEventListener("click", () => {
1947
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
1948
+ })
1949
+ })
1950
+ $("freeze").addEventListener("click", () => {
1951
+ const frozen = $("freeze").dataset.frozen === "1"
1952
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
1953
+ })
1954
+ $("clock-reset").addEventListener("click", () => {
1955
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
1956
+ })
1957
+ $("clock-set").addEventListener("submit", (event) => {
1958
+ event.preventDefault()
1959
+ const raw = $("clock-instant").value.trim()
1960
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
1961
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
1962
+ })
1963
+
1964
+ $("fault-form").addEventListener("submit", (event) => {
1965
+ event.preventDefault()
1966
+ const preset = $("fault-preset").value
1967
+ const body = preset
1968
+ ? { preset }
1969
+ : {
1970
+ status: Number($("fault-status").value),
1971
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
1972
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
1973
+ }
1974
+ if (!preset && !Number.isFinite(body.status)) {
1975
+ showError(new Error("Status must be a number, or choose a preset"))
1976
+ return
1977
+ }
1978
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
1979
+ })
1980
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
1981
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
1982
+
1983
+ $("route-list").addEventListener("click", (event) => {
1984
+ const button = event.target.closest("[data-route]")
1985
+ if (!button) return
1986
+ state.route = button.dataset.route
1987
+ $("route-title").textContent = state.route
1988
+ const method = state.route.split(" ")[0]
1989
+ $("route-body").disabled = method === "GET" || method === "DELETE"
1990
+ })
1991
+ $("route-form").addEventListener("submit", async (event) => {
1992
+ event.preventDefault()
1993
+ if (!state.route) return showError(new Error("Choose a route first"))
1994
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
1995
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
1996
+ let body
1997
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
1998
+ try { body = JSON.parse($("route-body").value) }
1999
+ catch { return showError(new Error("Body is not JSON")) }
2000
+ }
2001
+ try {
2002
+ const data = await api(method, concrete, body)
2003
+ $("route-result").textContent = JSON.stringify(data, null, 2)
2004
+ } catch (error) {
2005
+ showError(error)
2006
+ }
2007
+ })
2008
+
2009
+ function mountPanels(panels) {
2010
+ const nav = $("nav")
2011
+ const views = $("views")
2012
+ for (const panel of panels) {
2013
+ const button = document.createElement("button")
2014
+ button.type = "button"
2015
+ button.dataset.view = panel.id
2016
+ button.textContent = panel.title
2017
+ nav.append(button)
2018
+ const section = document.createElement("section")
2019
+ section.className = "view"
2020
+ section.id = "view-" + panel.id
2021
+ section.hidden = true
2022
+ const title = document.createElement("h2")
2023
+ title.textContent = panel.title
2024
+ const lede = document.createElement("p")
2025
+ lede.className = "lede"
2026
+ lede.textContent = panel.description || ""
2027
+ const body = document.createElement("div")
2028
+ body.className = "panel-body"
2029
+ body.id = "panel-" + panel.id
2030
+ body.innerHTML = panel.html || ""
2031
+ section.append(title, lede, body)
2032
+ views.append(section)
2033
+ if (panel.script) {
2034
+ try {
2035
+ const run = new Function("root", "api", panel.script)
2036
+ run(body, panelApi)
2037
+ } catch (error) {
2038
+ const note = document.createElement("p")
2039
+ note.className = "banner show"
2040
+ note.textContent = error instanceof Error ? error.message : String(error)
2041
+ body.append(note)
2042
+ }
2043
+ }
2044
+ }
2045
+ }
2046
+
2047
+ loadNamespaces()
2048
+ .then(() => api("GET", "/ui/manifest"))
2049
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2050
+ .catch(showError)
2051
+ })()
2052
+ </script>
2053
+ </body>
2054
+ </html>`;
2055
+ };
2056
+ var htmlResponse = (body) => new Response(body, {
2057
+ status: 200,
2058
+ headers: {
2059
+ "content-type": "text/html; charset=utf-8",
2060
+ "cache-control": "no-store"
2061
+ }
2062
+ });
2063
+ var json2 = (body) => new Response(JSON.stringify(body), {
2064
+ status: 200,
2065
+ headers: { "content-type": "application/json; charset=utf-8" }
2066
+ });
2067
+ var adminUiRoutes = (service, ui) => {
2068
+ const shell = () => renderAdminDocument(service);
2069
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2070
+ return {
2071
+ "GET /ui": () => htmlResponse(document2()),
2072
+ "GET /ui/": () => htmlResponse(document2()),
2073
+ "GET /ui/manifest": () => json2({
2074
+ service,
2075
+ panels: (ui?.panels ?? []).map((panel) => ({
2076
+ id: panel.id,
2077
+ title: panel.title,
2078
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2079
+ html: panel.html,
2080
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2081
+ }))
2082
+ })
2083
+ };
2084
+ };
2085
+
1154
2086
  // ../../openapi/metadata/dist/types.js
1155
2087
  var EXTENSION_KEYS = {
1156
2088
  operation: "x-mockingbird",
@@ -1314,19 +2246,453 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1314
2246
  });
1315
2247
  };
1316
2248
 
2249
+ // ../core/dist/state-view.js
2250
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2251
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2252
+ var SAMPLE = 25;
2253
+ var WALK_LIMIT = 1e4;
2254
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2255
+ var fail = (status, message) => ({ ok: false, status, message });
2256
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2257
+ var kindOf = (value) => {
2258
+ if (value === null)
2259
+ return "null";
2260
+ if (Array.isArray(value))
2261
+ return "array";
2262
+ switch (typeof value) {
2263
+ case "string":
2264
+ return "string";
2265
+ case "number":
2266
+ return Number.isFinite(value) ? "number" : "unknown";
2267
+ case "boolean":
2268
+ return "boolean";
2269
+ case "object":
2270
+ return "object";
2271
+ default:
2272
+ return "unknown";
2273
+ }
2274
+ };
2275
+ var humanize = (name) => {
2276
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2277
+ if (words === "")
2278
+ return name;
2279
+ return words.charAt(0).toUpperCase() + words.slice(1);
2280
+ };
2281
+ var jsonValue = (value) => {
2282
+ if (value === void 0)
2283
+ return fail(400, "value is required");
2284
+ try {
2285
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2286
+ } catch {
2287
+ return fail(400, "value must be JSON");
2288
+ }
2289
+ };
2290
+ var ctorName = (value) => {
2291
+ const ctor = value.constructor;
2292
+ return typeof ctor?.name === "string" ? ctor.name : "";
2293
+ };
2294
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2295
+ var discoverCollections = (root) => {
2296
+ const found = [];
2297
+ const seen = /* @__PURE__ */ new Set();
2298
+ const visit = (value, depth) => {
2299
+ if (found.length + seen.size > WALK_LIMIT)
2300
+ return;
2301
+ if (value === null || typeof value !== "object")
2302
+ return;
2303
+ if (seen.has(value))
2304
+ return;
2305
+ seen.add(value);
2306
+ if (value instanceof Collection) {
2307
+ found.push(value);
2308
+ return;
2309
+ }
2310
+ if (value instanceof Map) {
2311
+ for (const child of value.values())
2312
+ visit(child, depth + 1);
2313
+ return;
2314
+ }
2315
+ if (value instanceof Set) {
2316
+ for (const child of value.values())
2317
+ visit(child, depth + 1);
2318
+ return;
2319
+ }
2320
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2321
+ return;
2322
+ if (Array.isArray(value)) {
2323
+ const cap = Math.min(value.length, 32);
2324
+ for (let i = 0; i < cap; i++)
2325
+ visit(value[i], depth + 1);
2326
+ return;
2327
+ }
2328
+ let children;
2329
+ try {
2330
+ children = Object.values(value);
2331
+ } catch {
2332
+ return;
2333
+ }
2334
+ for (const child of children)
2335
+ visit(child, depth + 1);
2336
+ };
2337
+ visit(root, 0);
2338
+ return found;
2339
+ };
2340
+ var storedNames = (sqlite, namespace) => {
2341
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2342
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2343
+ return [...records, ...sequences].map((row) => row.name);
2344
+ };
2345
+ var blankAccum = (name) => ({
2346
+ name,
2347
+ kinds: /* @__PURE__ */ new Set(),
2348
+ present: 0,
2349
+ nested: /* @__PURE__ */ new Map()
2350
+ });
2351
+ var absorb = (accum, value) => {
2352
+ const kind = kindOf(value);
2353
+ accum.kinds.add(kind);
2354
+ accum.present++;
2355
+ if (!isRecord3(value))
2356
+ return;
2357
+ for (const [key, child] of Object.entries(value)) {
2358
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2359
+ absorb(nested, child);
2360
+ accum.nested.set(key, nested);
2361
+ }
2362
+ };
2363
+ var finishField = (accum, samples) => {
2364
+ const kinds = [...accum.kinds];
2365
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2366
+ const field = {
2367
+ name: accum.name,
2368
+ kind,
2369
+ optional: accum.present < samples || kinds.includes("null")
2370
+ };
2371
+ if (accum.nested.size > 0) {
2372
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2373
+ }
2374
+ return field;
2375
+ };
2376
+ var inferFields = (records) => {
2377
+ if (records.length === 0)
2378
+ return [];
2379
+ const sample = records.slice(0, SAMPLE);
2380
+ const objects = sample.filter((record) => isRecord3(record.value));
2381
+ if (objects.length === 0) {
2382
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2383
+ const list = [...kinds];
2384
+ return [
2385
+ {
2386
+ name: "(value)",
2387
+ kind: list.length === 1 ? list[0] : "unknown",
2388
+ optional: false
2389
+ }
2390
+ ];
2391
+ }
2392
+ const root = /* @__PURE__ */ new Map();
2393
+ for (const record of objects) {
2394
+ for (const [key, value] of Object.entries(record.value)) {
2395
+ const accum = root.get(key) ?? blankAccum(key);
2396
+ absorb(accum, value);
2397
+ root.set(key, accum);
2398
+ }
2399
+ }
2400
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2401
+ };
2402
+ var mergeFields = (declared, inferred) => {
2403
+ const byName = /* @__PURE__ */ new Map();
2404
+ for (const field of inferred)
2405
+ byName.set(field.name, field);
2406
+ const ordered = [];
2407
+ const seen = /* @__PURE__ */ new Set();
2408
+ for (const field of declared ?? []) {
2409
+ const found = byName.get(field.name);
2410
+ seen.add(field.name);
2411
+ if (!found) {
2412
+ ordered.push({ ...field, optional: field.optional });
2413
+ continue;
2414
+ }
2415
+ ordered.push({
2416
+ ...found,
2417
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2418
+ optional: field.optional || found.optional,
2419
+ ...field.description !== void 0 ? { description: field.description } : {},
2420
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2421
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2422
+ });
2423
+ }
2424
+ for (const field of inferred) {
2425
+ if (!seen.has(field.name))
2426
+ ordered.push(field);
2427
+ }
2428
+ return ordered;
2429
+ };
2430
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2431
+ var readRecord = (collection, id) => {
2432
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2433
+ const row = rows.find((entry) => entry.id === id);
2434
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2435
+ };
2436
+ var inspectState = (scope) => {
2437
+ const declared = /* @__PURE__ */ new Map();
2438
+ for (const declaration of scope.declarations ?? []) {
2439
+ if (COLLECTION_NAME.test(declaration.name))
2440
+ declared.set(declaration.name, declaration);
2441
+ }
2442
+ const names = new Set(declared.keys());
2443
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2444
+ names.add(name);
2445
+ for (const collection of discoverCollections(scope.root)) {
2446
+ if (collection.namespace === scope.storageNamespace)
2447
+ names.add(collection.collectionName);
2448
+ }
2449
+ const collections = [];
2450
+ for (const name of names) {
2451
+ if (!COLLECTION_NAME.test(name))
2452
+ continue;
2453
+ const declaration = declared.get(name);
2454
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2455
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2456
+ const inferred = inferFields(records);
2457
+ const fields = mergeFields(declaration?.fields, inferred);
2458
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2459
+ collections.push({
2460
+ name,
2461
+ label: declaration?.label ?? humanize(name),
2462
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2463
+ count: collection.count(),
2464
+ source,
2465
+ fields,
2466
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2467
+ });
2468
+ }
2469
+ const order = /* @__PURE__ */ new Map();
2470
+ for (const [index, item] of (scope.declarations ?? []).entries())
2471
+ order.set(item.name, index);
2472
+ collections.sort((a, b) => {
2473
+ const left = order.get(a.name);
2474
+ const right = order.get(b.name);
2475
+ if (left !== void 0 && right !== void 0)
2476
+ return left - right;
2477
+ if (left !== void 0)
2478
+ return -1;
2479
+ if (right !== void 0)
2480
+ return 1;
2481
+ return a.name.localeCompare(b.name);
2482
+ });
2483
+ return {
2484
+ namespace: scope.namespace,
2485
+ storageNamespace: scope.storageNamespace,
2486
+ collections
2487
+ };
2488
+ };
2489
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2490
+ if (!COLLECTION_NAME.test(name))
2491
+ return fail(400, "collection name is not allowed");
2492
+ const limit = query.limit ?? 50;
2493
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2494
+ return fail(400, "limit must be an integer from 1 to 200");
2495
+ }
2496
+ const order = query.order ?? "newest";
2497
+ if (order !== "newest" && order !== "oldest")
2498
+ return fail(400, 'order must be "newest" or "oldest"');
2499
+ const collection = collectionOf(sqlite, storageNamespace, name);
2500
+ const rows = collection.list({ order }).filter((row) => {
2501
+ if (query.after === void 0)
2502
+ return true;
2503
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2504
+ });
2505
+ const slice = rows.slice(0, limit);
2506
+ const last = slice.at(-1);
2507
+ return {
2508
+ ok: true,
2509
+ value: {
2510
+ collection: name,
2511
+ count: collection.count(),
2512
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2513
+ next: rows.length > limit && last ? last.seq : null
2514
+ }
2515
+ };
2516
+ };
2517
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2518
+ var readStateRecord = (scope, name, id) => {
2519
+ if (!COLLECTION_NAME.test(name))
2520
+ return fail(400, "collection name is not allowed");
2521
+ if (!RECORD_ID.test(id))
2522
+ return fail(400, "record id is not allowed");
2523
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2524
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
2525
+ };
2526
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2527
+ var createStateRecord = (scope, name, input) => {
2528
+ if (!COLLECTION_NAME.test(name))
2529
+ return fail(400, "collection name is not allowed");
2530
+ const parsed = jsonValue(input.value);
2531
+ if (!parsed.ok)
2532
+ return parsed;
2533
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2534
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2535
+ const checked = requireId(id);
2536
+ if (!checked.ok)
2537
+ return checked;
2538
+ if (collection.has(checked.value))
2539
+ return fail(409, `record ${checked.value} already exists`);
2540
+ const stored = collection.insert(checked.value, parsed.value);
2541
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2542
+ };
2543
+ var replaceStateRecord = (scope, name, id, value) => {
2544
+ if (!COLLECTION_NAME.test(name))
2545
+ return fail(400, "collection name is not allowed");
2546
+ const checked = requireId(id);
2547
+ if (!checked.ok)
2548
+ return checked;
2549
+ const parsed = jsonValue(value);
2550
+ if (!parsed.ok)
2551
+ return parsed;
2552
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2553
+ if (!collection.has(checked.value))
2554
+ return fail(404, `no record ${checked.value} in ${name}`);
2555
+ const stored = collection.update(checked.value, parsed.value);
2556
+ if (!stored)
2557
+ return fail(404, `no record ${checked.value} in ${name}`);
2558
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2559
+ };
2560
+ var patchStateRecord = (scope, name, id, value) => {
2561
+ const current = readStateRecord(scope, name, id);
2562
+ if (!current.ok)
2563
+ return current;
2564
+ const parsed = jsonValue(value);
2565
+ if (!parsed.ok)
2566
+ return parsed;
2567
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2568
+ return replaceStateRecord(scope, name, id, next);
2569
+ };
2570
+ var deleteStateRecord = (scope, name, id) => {
2571
+ if (!COLLECTION_NAME.test(name))
2572
+ return fail(400, "collection name is not allowed");
2573
+ const checked = requireId(id);
2574
+ if (!checked.ok)
2575
+ return checked;
2576
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2577
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2578
+ };
2579
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2580
+ status,
2581
+ headers: { "content-type": "application/json; charset=utf-8" }
2582
+ });
2583
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2584
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2585
+ var integerParam = (value) => {
2586
+ if (value === null)
2587
+ return void 0;
2588
+ if (!/^-?\d+$/.test(value))
2589
+ return "bad";
2590
+ return Number(value);
2591
+ };
2592
+ var stateAdminRoutes = (routes) => {
2593
+ const open = (namespace) => {
2594
+ try {
2595
+ return { ok: true, value: routes.open(namespace) };
2596
+ } catch (error2) {
2597
+ return fail(400, error2 instanceof Error ? error2.message : String(error2));
2598
+ }
2599
+ };
2600
+ const wrote = (namespace) => {
2601
+ routes.afterWrite?.(namespace);
2602
+ };
2603
+ return {
2604
+ "GET /state": ({ namespace }) => {
2605
+ const scope = open(namespace);
2606
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2607
+ },
2608
+ "GET /state/:collection": ({ namespace, params, url }) => {
2609
+ const scope = open(namespace);
2610
+ if (!scope.ok)
2611
+ return fromResult(scope, 200);
2612
+ const limit = integerParam(url.searchParams.get("limit"));
2613
+ const after = integerParam(url.searchParams.get("after"));
2614
+ if (limit === "bad")
2615
+ return adminError2(400, "limit: expected an integer");
2616
+ if (after === "bad")
2617
+ return adminError2(400, "after: expected a sequence number");
2618
+ const order = url.searchParams.get("order");
2619
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2620
+ ...limit !== void 0 ? { limit } : {},
2621
+ ...after !== void 0 ? { after } : {},
2622
+ ...order === "newest" || order === "oldest" ? { order } : {}
2623
+ }), 200);
2624
+ },
2625
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2626
+ const scope = open(namespace);
2627
+ if (!scope.ok)
2628
+ return fromResult(scope, 200);
2629
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2630
+ },
2631
+ "POST /state/:collection": ({ namespace, params, body }) => {
2632
+ const scope = open(namespace);
2633
+ if (!scope.ok)
2634
+ return fromResult(scope, 201);
2635
+ if (!isRecord3(body) || !("value" in body)) {
2636
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2637
+ }
2638
+ const id = body.id;
2639
+ if (id !== void 0 && typeof id !== "string")
2640
+ return adminError2(400, "id must be a string");
2641
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2642
+ ...typeof id === "string" ? { id } : {},
2643
+ value: body.value
2644
+ });
2645
+ if (created.ok)
2646
+ wrote(namespace);
2647
+ return fromResult(created, 201);
2648
+ },
2649
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2650
+ const scope = open(namespace);
2651
+ if (!scope.ok)
2652
+ return fromResult(scope, 200);
2653
+ if (!isRecord3(body) || !("value" in body))
2654
+ return adminError2(400, 'expected {"value": <json>}');
2655
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2656
+ if (replaced.ok)
2657
+ wrote(namespace);
2658
+ return fromResult(replaced, 200);
2659
+ },
2660
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2661
+ const scope = open(namespace);
2662
+ if (!scope.ok)
2663
+ return fromResult(scope, 200);
2664
+ if (!isRecord3(body) || !("value" in body))
2665
+ return adminError2(400, 'expected {"value": <json>}');
2666
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2667
+ if (patched.ok)
2668
+ wrote(namespace);
2669
+ return fromResult(patched, 200);
2670
+ },
2671
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2672
+ const scope = open(namespace);
2673
+ if (!scope.ok)
2674
+ return fromResult(scope, 200);
2675
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2676
+ if (removed.ok)
2677
+ wrote(namespace);
2678
+ return fromResult(removed, 200);
2679
+ }
2680
+ };
2681
+ };
2682
+
1317
2683
  // ../core/dist/version.js
1318
- var PACKAGE_VERSION = true ? "1.2.0" : UNRELEASED_VERSION;
2684
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1319
2685
 
1320
2686
  // ../core/dist/signing.js
1321
2687
  var encoder = new TextEncoder();
1322
2688
  var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
1323
2689
 
1324
2690
  // ../core/dist/webhooks.js
1325
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1326
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1327
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2691
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2692
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2693
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1328
2694
  var parseEndpoint = (value) => {
1329
- if (!isRecord3(value) || typeof value.url !== "string")
2695
+ if (!isRecord4(value) || typeof value.url !== "string")
1330
2696
  return "each endpoint needs a url";
1331
2697
  try {
1332
2698
  new URL(value.url);
@@ -1343,18 +2709,18 @@ var parseEndpoint = (value) => {
1343
2709
  const events = value.events ?? value.enabledEvents;
1344
2710
  if (Array.isArray(events))
1345
2711
  endpoint.events = events.map(String);
1346
- if (isRecord3(value.tags)) {
2712
+ if (isRecord4(value.tags)) {
1347
2713
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1348
2714
  }
1349
2715
  if (typeof value.account === "string")
1350
2716
  endpoint.tags = { ...endpoint.tags, account: value.account };
1351
- if (isRecord3(value.headers)) {
2717
+ if (isRecord4(value.headers)) {
1352
2718
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1353
2719
  }
1354
2720
  return endpoint;
1355
2721
  };
1356
2722
  var webhookAdminRoutes = (hub) => ({
1357
- "GET /webhooks": ({ url, namespace }) => json2(200, {
2723
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
1358
2724
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1359
2725
  const type = url.searchParams.get("type");
1360
2726
  return type === null || d.type === type;
@@ -1362,51 +2728,51 @@ var webhookAdminRoutes = (hub) => ({
1362
2728
  }),
1363
2729
  "GET /webhooks/events": ({ url, namespace }) => {
1364
2730
  const type = url.searchParams.get("type");
1365
- return json2(200, {
2731
+ return json4(200, {
1366
2732
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1367
2733
  });
1368
2734
  },
1369
2735
  "POST /webhooks/:id/replay": async ({ params }) => {
1370
2736
  const replayed = await hub.replay(params.id);
1371
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
2737
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1372
2738
  },
1373
2739
  "POST /webhooks/flush": async () => {
1374
2740
  await hub.flush();
1375
- return json2(200, { status: "ok" });
2741
+ return json4(200, { status: "ok" });
1376
2742
  },
1377
2743
  "POST /webhooks/faults": ({ body, namespace }) => {
1378
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1379
- return adminError2(400, "mode must be duplicate, reorder or drop");
2744
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2745
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1380
2746
  }
1381
2747
  const fault = { mode: body.mode };
1382
2748
  if (typeof body.count === "number")
1383
2749
  fault.count = body.count;
1384
2750
  hub.fault(namespace, fault);
1385
- return json2(201, { namespace, ...fault });
2751
+ return json4(201, { namespace, ...fault });
1386
2752
  },
1387
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
2753
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
1388
2754
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1389
2755
  ...rest,
1390
2756
  secret: secret ? "(set)" : null
1391
2757
  }))
1392
2758
  }),
1393
2759
  "PUT /webhook-endpoints": ({ body, namespace }) => {
1394
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
2760
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
1395
2761
  if (!Array.isArray(list))
1396
- return adminError2(400, "expected [{url, secret?, events?}]");
2762
+ return adminError3(400, "expected [{url, secret?, events?}]");
1397
2763
  const parsed = [];
1398
2764
  for (const each of list) {
1399
2765
  const endpoint = parseEndpoint(each);
1400
2766
  if (typeof endpoint === "string")
1401
- return adminError2(400, endpoint);
2767
+ return adminError3(400, endpoint);
1402
2768
  parsed.push(endpoint);
1403
2769
  }
1404
2770
  const set = hub.setEndpoints(namespace, parsed);
1405
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2771
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1406
2772
  },
1407
2773
  "DELETE /webhook-endpoints": ({ namespace }) => {
1408
2774
  hub.setEndpoints(namespace, []);
1409
- return json2(200, { status: "ok" });
2775
+ return json4(200, { status: "ok" });
1410
2776
  }
1411
2777
  });
1412
2778
  var parsePayload = (message) => {
@@ -1470,6 +2836,7 @@ var operationMatcher = (document2) => {
1470
2836
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1471
2837
  };
1472
2838
  var createRuntime = (options) => {
2839
+ assertAdminUi(options.adminUi);
1473
2840
  const sqlite = bootSqlite(options.sqlite);
1474
2841
  const clock = options.clock ?? createClock();
1475
2842
  const rng = createRng(options.seed ?? 0);
@@ -1676,6 +3043,19 @@ var createRuntime = (options) => {
1676
3043
  else
1677
3044
  timeline(name);
1678
3045
  };
3046
+ const declarationsFor = (namespace) => {
3047
+ const declared = options.state;
3048
+ if (!declared)
3049
+ return [];
3050
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3051
+ };
3052
+ const stateScope = (namespace) => ({
3053
+ sqlite,
3054
+ namespace,
3055
+ storageNamespace: storageNamespace(namespace),
3056
+ root: instance(namespace),
3057
+ declarations: declarationsFor(namespace)
3058
+ });
1679
3059
  const runtime = {
1680
3060
  name: options.name,
1681
3061
  sqlite,
@@ -1714,6 +3094,7 @@ var createRuntime = (options) => {
1714
3094
  branch,
1715
3095
  checkout,
1716
3096
  timeline,
3097
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
1717
3098
  fetch: async (incoming) => {
1718
3099
  let request = incoming;
1719
3100
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -1907,11 +3288,20 @@ var createRuntime = (options) => {
1907
3288
  ...credentialRoutes(credentials),
1908
3289
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
1909
3290
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
1910
- ...options.admin?.(runtime) ?? {}
3291
+ ...options.admin?.(runtime) ?? {},
3292
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3293
+ // beside these; it does not replace `/state` or `/ui`.
3294
+ ...stateAdminRoutes({
3295
+ open: stateScope,
3296
+ afterWrite: (namespace) => {
3297
+ checkpoint(namespace, "main");
3298
+ }
3299
+ }),
3300
+ ...adminUiRoutes(options.name, options.adminUi)
1911
3301
  },
1912
3302
  adminKey: options.adminKey
1913
3303
  });
1914
- return runtime;
3304
+ return defineMock(runtime);
1915
3305
  };
1916
3306
  var mutableResponse = (response) => {
1917
3307
  try {
@@ -2048,15 +3438,15 @@ var decodePostHogBody = (request) => {
2048
3438
  decoded.set(request, pending);
2049
3439
  return pending;
2050
3440
  };
2051
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3441
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2052
3442
  var nonEmpty = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
2053
3443
  var tokenFromBody = (body) => {
2054
3444
  if (Array.isArray(body)) return tokenFromBody(body[0]);
2055
- if (!isRecord4(body)) return void 0;
3445
+ if (!isRecord5(body)) return void 0;
2056
3446
  const direct = nonEmpty(body.token) ?? nonEmpty(body.api_key);
2057
3447
  if (direct) return direct;
2058
3448
  if (Array.isArray(body.batch)) return tokenFromBody(body.batch[0]);
2059
- if (isRecord4(body.properties)) return nonEmpty(body.properties.token);
3449
+ if (isRecord5(body.properties)) return nonEmpty(body.properties.token);
2060
3450
  return void 0;
2061
3451
  };
2062
3452
  var ARRAY_PATH = /^\/array\/([^/]+)\/config(\.js)?\/?$/;
@@ -2130,7 +3520,7 @@ var legacyMaps = (evaluations) => {
2130
3520
  }
2131
3521
  return { featureFlags, featureFlagPayloads };
2132
3522
  };
2133
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3523
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2134
3524
  var payloadString = (payload) => payload === void 0 || payload === null ? null : JSON.stringify(payload);
2135
3525
  var parsePayload2 = (payload) => {
2136
3526
  if (payload === null) return null;
@@ -2159,7 +3549,7 @@ var adminView = (flag) => ({
2159
3549
  var isValue = (value) => typeof value === "boolean" || typeof value === "string" && value.length > 0;
2160
3550
  var parseFlagSpec = (body) => {
2161
3551
  if (body === void 0) return { default: null, payload: null, overrides: [] };
2162
- if (!isRecord5(body)) return "expected a JSON object";
3552
+ if (!isRecord6(body)) return "expected a JSON object";
2163
3553
  const value = body.default ?? body.value;
2164
3554
  if (value !== void 0 && value !== null && !isValue(value)) {
2165
3555
  return "default must be true, false, a variant string, or null (absent)";
@@ -2168,7 +3558,7 @@ var parseFlagSpec = (body) => {
2168
3558
  if (body.overrides !== void 0) {
2169
3559
  if (!Array.isArray(body.overrides)) return "overrides must be a list";
2170
3560
  for (const each of body.overrides) {
2171
- if (!isRecord5(each)) return "each override is {distinct_id?|email?, value, payload?}";
3561
+ if (!isRecord6(each)) return "each override is {distinct_id?|email?, value, payload?}";
2172
3562
  const id = each.distinct_id ?? each.distinctId;
2173
3563
  const email = each.email;
2174
3564
  if (id === void 0 && email === void 0) return "each override needs distinct_id or email";
@@ -2249,10 +3639,10 @@ var restView = (flag) => {
2249
3639
  };
2250
3640
  var propertyValues = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string" || typeof v === "number").map(String) : typeof value === "string" || typeof value === "number" ? [String(value)] : [];
2251
3641
  var fromFilters = (filters) => {
2252
- const record = isRecord5(filters) ? filters : {};
2253
- const groups = Array.isArray(record.groups) ? record.groups.filter(isRecord5) : [];
2254
- const multivariate = isRecord5(record.multivariate) ? record.multivariate : void 0;
2255
- const variants = Array.isArray(multivariate?.variants) ? multivariate.variants.filter(isRecord5) : [];
3642
+ const record = isRecord6(filters) ? filters : {};
3643
+ const groups = Array.isArray(record.groups) ? record.groups.filter(isRecord6) : [];
3644
+ const multivariate = isRecord6(record.multivariate) ? record.multivariate : void 0;
3645
+ const variants = Array.isArray(multivariate?.variants) ? multivariate.variants.filter(isRecord6) : [];
2256
3646
  const topVariant = [...variants].sort((a, b) => Number(b.rollout_percentage ?? 0) - Number(a.rollout_percentage ?? 0)).map((v) => v.key).find((key) => typeof key === "string" && key.length > 0);
2257
3647
  const on = (group) => {
2258
3648
  const rollout = group.rollout_percentage ?? 100;
@@ -2263,7 +3653,7 @@ var fromFilters = (filters) => {
2263
3653
  const overrides = [];
2264
3654
  let fallback = groups.length === 0 ? false : null;
2265
3655
  for (const group of groups) {
2266
- const properties = Array.isArray(group.properties) ? group.properties.filter(isRecord5) : [];
3656
+ const properties = Array.isArray(group.properties) ? group.properties.filter(isRecord6) : [];
2267
3657
  if (properties.length === 0) {
2268
3658
  const rollout = group.rollout_percentage ?? 100;
2269
3659
  const value = typeof rollout === "number" && rollout < 100 ? false : on(group);
@@ -2280,7 +3670,7 @@ var fromFilters = (filters) => {
2280
3670
  }
2281
3671
  }
2282
3672
  if (fallback === null) fallback = false;
2283
- const payloads = isRecord5(record.payloads) ? record.payloads : {};
3673
+ const payloads = isRecord6(record.payloads) ? record.payloads : {};
2284
3674
  const rawPayload = typeof fallback === "string" && fallback in payloads ? payloads[fallback] : payloads.true;
2285
3675
  const payload = rawPayload === void 0 || rawPayload === null ? null : typeof rawPayload === "string" ? rawPayload : JSON.stringify(rawPayload);
2286
3676
  return { default: fallback, payload, overrides };
@@ -2453,13 +3843,13 @@ var POSTHOG_PRESETS = {
2453
3843
  }))
2454
3844
  }
2455
3845
  };
2456
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2457
- var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2458
- var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3846
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3847
+ var adminError4 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
3848
+ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2459
3849
  var parseBulk = (body) => {
2460
- const source = isRecord6(body) && isRecord6(body.flags) ? body.flags : body;
2461
- const entries = Array.isArray(source) ? source.map((each) => [isRecord6(each) ? String(each.key ?? "") : "", each]) : isRecord6(source) ? Object.entries(source).filter(([key]) => key !== "replace") : [];
2462
- if (!Array.isArray(source) && !isRecord6(source)) return "expected {flags: {<key>: spec}}";
3850
+ const source = isRecord7(body) && isRecord7(body.flags) ? body.flags : body;
3851
+ const entries = Array.isArray(source) ? source.map((each) => [isRecord7(each) ? String(each.key ?? "") : "", each]) : isRecord7(source) ? Object.entries(source).filter(([key]) => key !== "replace") : [];
3852
+ if (!Array.isArray(source) && !isRecord7(source)) return "expected {flags: {<key>: spec}}";
2463
3853
  const specs = {};
2464
3854
  for (const [key, value] of entries) {
2465
3855
  if (!key) return "every flag needs a key";
@@ -2473,7 +3863,7 @@ var parseQueryResults = (value) => {
2473
3863
  if (!Array.isArray(value)) return "queryResults: [{match?, columns?, results: [[\u2026]]}]";
2474
3864
  const out = [];
2475
3865
  for (const each of value) {
2476
- if (!isRecord6(each) || !Array.isArray(each.results) || !each.results.every(Array.isArray)) {
3866
+ if (!isRecord7(each) || !Array.isArray(each.results) || !each.results.every(Array.isArray)) {
2477
3867
  return "each queryResults entry needs results: unknown[][]";
2478
3868
  }
2479
3869
  out.push({
@@ -2487,51 +3877,51 @@ var parseQueryResults = (value) => {
2487
3877
  var adminRoutes = (runtime) => {
2488
3878
  const api = (namespace) => runtime.instance(namespace);
2489
3879
  return {
2490
- "GET /flags": ({ namespace }) => json3(200, { flags: api(namespace).flagList() }),
3880
+ "GET /flags": ({ namespace }) => json5(200, { flags: api(namespace).flagList() }),
2491
3881
  "GET /flags/evaluate": ({ url, namespace }) => {
2492
3882
  const distinctId = url.searchParams.get("distinct_id");
2493
- if (!distinctId) return adminError3(400, "distinct_id is required");
3883
+ if (!distinctId) return adminError4(400, "distinct_id is required");
2494
3884
  const email = url.searchParams.get("email");
2495
3885
  const evaluations = api(namespace).evaluate({
2496
3886
  distinct_id: distinctId,
2497
3887
  ...email ? { person_properties: { email } } : {}
2498
3888
  });
2499
- return json3(200, {
3889
+ return json5(200, {
2500
3890
  flags: Object.fromEntries(evaluations.map((e) => [e.key, e.value]))
2501
3891
  });
2502
3892
  },
2503
3893
  "GET /flags/:key": ({ params, namespace }) => {
2504
3894
  const flag = api(namespace).state.flags.get(params.key);
2505
- return flag ? json3(200, adminView(flag)) : adminError3(404, `no flag ${params.key}`);
3895
+ return flag ? json5(200, adminView(flag)) : adminError4(404, `no flag ${params.key}`);
2506
3896
  },
2507
3897
  "PUT /flags/:key": ({ params, body, namespace }) => {
2508
3898
  const spec = parseFlagSpec(body);
2509
- if (typeof spec === "string") return adminError3(400, spec);
2510
- return json3(200, adminView(api(namespace).state.putFlag(params.key, spec)));
3899
+ if (typeof spec === "string") return adminError4(400, spec);
3900
+ return json5(200, adminView(api(namespace).state.putFlag(params.key, spec)));
2511
3901
  },
2512
- "DELETE /flags/:key": ({ params, namespace }) => api(namespace).state.flags.delete(params.key) ? json3(200, { deleted: params.key }) : adminError3(404, `no flag ${params.key}`),
3902
+ "DELETE /flags/:key": ({ params, namespace }) => api(namespace).state.flags.delete(params.key) ? json5(200, { deleted: params.key }) : adminError4(404, `no flag ${params.key}`),
2513
3903
  "PUT /flags": ({ body, namespace }) => {
2514
3904
  const specs = parseBulk(body);
2515
- if (typeof specs === "string") return adminError3(400, specs);
3905
+ if (typeof specs === "string") return adminError4(400, specs);
2516
3906
  const state = api(namespace).state;
2517
- if (isRecord6(body) && body.replace === true) {
3907
+ if (isRecord7(body) && body.replace === true) {
2518
3908
  for (const flag of state.listFlags()) state.flags.delete(flag.key);
2519
3909
  }
2520
3910
  for (const [key, spec] of Object.entries(specs)) state.putFlag(key, spec);
2521
- return json3(200, { flags: api(namespace).flagList() });
3911
+ return json5(200, { flags: api(namespace).flagList() });
2522
3912
  },
2523
3913
  "POST /flags/import": ({ body, namespace }) => {
2524
- const input = isRecord6(body) ? body : {};
3914
+ const input = isRecord7(body) ? body : {};
2525
3915
  const env = input.env ?? "dev";
2526
- if (env !== "dev" && env !== "prod") return adminError3(400, 'env must be "dev" or "prod"');
3916
+ if (env !== "dev" && env !== "prod") return adminError4(400, 'env must be "dev" or "prod"');
2527
3917
  const from = input.from ?? "state.json";
2528
3918
  let file;
2529
- if (isRecord6(input.state) && Array.isArray(input.state.flags)) {
3919
+ if (isRecord7(input.state) && Array.isArray(input.state.flags)) {
2530
3920
  file = input.state;
2531
3921
  } else if (from === "state.json") {
2532
3922
  file = ACME_FLAG_STATE;
2533
3923
  } else {
2534
- return adminError3(400, 'from must be "state.json" (the bundled copy) or pass "state"');
3924
+ return adminError4(400, 'from must be "state.json" (the bundled copy) or pass "state"');
2535
3925
  }
2536
3926
  const project = typeof input.project === "string" ? input.project : void 0;
2537
3927
  const specs = specsFromState(file, { env, ...project ? { project } : {} });
@@ -2540,7 +3930,7 @@ var adminRoutes = (runtime) => {
2540
3930
  for (const flag of state.listFlags()) state.flags.delete(flag.key);
2541
3931
  }
2542
3932
  for (const [key, spec] of Object.entries(specs)) state.putFlag(key, spec);
2543
- return json3(200, {
3933
+ return json5(200, {
2544
3934
  imported: Object.keys(specs).length,
2545
3935
  env,
2546
3936
  project: project ?? "member-app"
@@ -2549,17 +3939,17 @@ var adminRoutes = (runtime) => {
2549
3939
  "POST /flags/bump": ({ namespace }) => {
2550
3940
  const state = api(namespace).state;
2551
3941
  const next = state.update({ generation: state.current().generation + 1 });
2552
- return json3(200, {
3942
+ return json5(200, {
2553
3943
  generation: next.generation,
2554
3944
  note: "Nothing changed server-side. Clear the app's flag caches now (backend 60 s per user, EMR frontend 60 s / 10 s)."
2555
3945
  });
2556
3946
  },
2557
3947
  "GET /events": ({ url, namespace }) => {
2558
3948
  const since = parseSince(url.searchParams.get("since"));
2559
- if (since === null) return adminError3(400, "since must be epoch ms or ISO-8601");
3949
+ if (since === null) return adminError4(400, "since must be epoch ms or ISO-8601");
2560
3950
  const distinct = url.searchParams.get("distinct_id");
2561
3951
  const event = url.searchParams.get("event");
2562
- return json3(200, {
3952
+ return json5(200, {
2563
3953
  events: api(namespace).events({
2564
3954
  ...distinct !== null ? { distinct_id: distinct } : {},
2565
3955
  ...event !== null ? { event } : {},
@@ -2567,22 +3957,22 @@ var adminRoutes = (runtime) => {
2567
3957
  })
2568
3958
  });
2569
3959
  },
2570
- "GET /recordings": ({ namespace }) => json3(200, { count: api(namespace).state.current().recordings }),
2571
- "GET /settings": ({ namespace }) => json3(200, api(namespace).state.current()),
3960
+ "GET /recordings": ({ namespace }) => json5(200, { count: api(namespace).state.current().recordings }),
3961
+ "GET /settings": ({ namespace }) => json5(200, api(namespace).state.current()),
2572
3962
  "PUT /settings": ({ body, namespace }) => {
2573
- if (!isRecord6(body)) return adminError3(400, "expected a JSON object");
3963
+ if (!isRecord7(body)) return adminError4(400, "expected a JSON object");
2574
3964
  const patch = {};
2575
3965
  if (body.sessionRecording !== void 0) {
2576
3966
  if (typeof body.sessionRecording !== "boolean")
2577
- return adminError3(400, "sessionRecording: boolean");
3967
+ return adminError4(400, "sessionRecording: boolean");
2578
3968
  patch.sessionRecording = body.sessionRecording;
2579
3969
  }
2580
3970
  if (body.queryResults !== void 0) {
2581
3971
  const parsed = parseQueryResults(body.queryResults);
2582
- if (typeof parsed === "string") return adminError3(400, parsed);
3972
+ if (typeof parsed === "string") return adminError4(400, parsed);
2583
3973
  patch.queryResults = parsed;
2584
3974
  }
2585
- return json3(200, api(namespace).state.update(patch));
3975
+ return json5(200, api(namespace).state.update(patch));
2586
3976
  }
2587
3977
  };
2588
3978
  };
@@ -2622,7 +4012,7 @@ var createRuntime2 = (options = {}) => {
2622
4012
 
2623
4013
  // src/index.ts
2624
4014
  var POSTHOG_NAMESPACE = "posthog";
2625
- var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4015
+ var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2626
4016
  var error = (status, type, code, detail, attr) => jsonRes(status, { type, code, detail, attr: attr ?? null });
2627
4017
  var invalidApiKey = () => error(
2628
4018
  401,
@@ -2660,7 +4050,7 @@ var scrubProperties = (event, properties) => {
2660
4050
  }
2661
4051
  const kept = scrubRecord(properties);
2662
4052
  for (const nested of ["$set", "$set_once"]) {
2663
- if (isRecord7(kept[nested])) kept[nested] = scrubRecord(kept[nested]);
4053
+ if (isRecord8(kept[nested])) kept[nested] = scrubRecord(kept[nested]);
2664
4054
  }
2665
4055
  return kept;
2666
4056
  };
@@ -2781,7 +4171,7 @@ var PostHogAPI = class {
2781
4171
  }
2782
4172
  flags(context, route) {
2783
4173
  const body = this.body(context);
2784
- if (!isRecord7(body)) return malformed();
4174
+ if (!isRecord8(body)) return malformed();
2785
4175
  if (!tokenFromBody(body)) return invalidApiKey();
2786
4176
  const distinctId = body.distinct_id;
2787
4177
  if (typeof distinctId !== "string" && typeof distinctId !== "number") {
@@ -2791,7 +4181,7 @@ var PostHogAPI = class {
2791
4181
  const detailed = route === "decide" ? version >= 4 : version >= 2;
2792
4182
  const subject = {
2793
4183
  distinct_id: String(distinctId),
2794
- ...isRecord7(body.person_properties) ? { person_properties: body.person_properties } : {}
4184
+ ...isRecord8(body.person_properties) ? { person_properties: body.person_properties } : {}
2795
4185
  };
2796
4186
  const keys = [body.flag_keys_to_evaluate, body.flag_keys].find(Array.isArray);
2797
4187
  const quotaLimited = this.effect(context, "quota_limited");
@@ -2824,15 +4214,15 @@ var PostHogAPI = class {
2824
4214
  }
2825
4215
  const token = tokenFromBody(body);
2826
4216
  if (!token) return invalidApiKey();
2827
- const items = Array.isArray(body) ? body : isRecord7(body) && Array.isArray(body.batch) ? body.batch : [body];
4217
+ const items = Array.isArray(body) ? body : isRecord8(body) && Array.isArray(body.batch) ? body.batch : [body];
2828
4218
  const events = items.filter(
2829
- (item) => isRecord7(item) && typeof item.event === "string" && item.event.length > 0
4219
+ (item) => isRecord8(item) && typeof item.event === "string" && item.event.length > 0
2830
4220
  );
2831
4221
  if (events.length === 0 && items.length > 0) return malformed("Invalid payload: no event name");
2832
4222
  const stored = [];
2833
4223
  for (const raw of events) {
2834
4224
  const event = raw.event;
2835
- const properties = isRecord7(raw.properties) ? raw.properties : {};
4225
+ const properties = isRecord8(raw.properties) ? raw.properties : {};
2836
4226
  const distinct = raw.distinct_id ?? properties.distinct_id ?? raw.$distinct_id ?? properties.$distinct_id;
2837
4227
  const uuid = typeof raw.uuid === "string" && raw.uuid ? raw.uuid : this.state.nextEventId();
2838
4228
  if (this.state.events.has(uuid)) continue;
@@ -2874,7 +4264,7 @@ var PostHogAPI = class {
2874
4264
  }
2875
4265
  createFlag(context) {
2876
4266
  const body = this.body(context);
2877
- if (!isRecord7(body)) return malformed();
4267
+ if (!isRecord8(body)) return malformed();
2878
4268
  const key = body.key;
2879
4269
  if (typeof key !== "string" || !/^[A-Za-z0-9_-]+$/.test(key)) {
2880
4270
  return error(
@@ -2906,7 +4296,7 @@ var PostHogAPI = class {
2906
4296
  const flag = this.state.findFlag(context.params.flagId ?? "");
2907
4297
  if (!flag) return error(404, "invalid_request", "not_found", "Not found.");
2908
4298
  const body = this.body(context);
2909
- if (!isRecord7(body)) return malformed();
4299
+ if (!isRecord8(body)) return malformed();
2910
4300
  const patch = {};
2911
4301
  if (typeof body.name === "string") patch.name = body.name;
2912
4302
  if (typeof body.active === "boolean") patch.active = body.active;
@@ -2917,7 +4307,7 @@ var PostHogAPI = class {
2917
4307
  }
2918
4308
  query(context) {
2919
4309
  const body = this.body(context);
2920
- const query = isRecord7(body) && isRecord7(body.query) ? body.query : void 0;
4310
+ const query = isRecord8(body) && isRecord8(body.query) ? body.query : void 0;
2921
4311
  if (query?.kind !== "HogQLQuery" || typeof query.query !== "string") {
2922
4312
  return error(400, "validation_error", "invalid_input", "Expected a HogQLQuery.", "query");
2923
4313
  }
@@ -2959,4 +4349,4 @@ export {
2959
4349
  scrubProperties,
2960
4350
  PostHogAPI
2961
4351
  };
2962
- //# sourceMappingURL=chunk-2FGITTBR.js.map
4352
+ //# sourceMappingURL=chunk-UJEAOIXF.js.map