@crvouga/mockingbird-service-plane 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,30 +38,30 @@ var createClock = (source = Date.now) => {
38
38
  var Collection = class {
39
39
  sqlite;
40
40
  namespace;
41
- name;
42
- constructor(sqlite, namespace, name) {
41
+ collectionName;
42
+ constructor(sqlite, namespace, collectionName) {
43
43
  this.sqlite = sqlite;
44
44
  this.namespace = namespace;
45
- this.name = name;
45
+ this.collectionName = collectionName;
46
46
  }
47
47
  bumpCollectionSeq() {
48
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
48
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.collectionName);
49
49
  const next = (row?.value ?? 0) + 1;
50
50
  this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
51
- ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
51
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.collectionName, next);
52
52
  return next;
53
53
  }
54
54
  nextSequence() {
55
55
  return this.sqlite.transaction(() => this.bumpCollectionSeq());
56
56
  }
57
57
  get(id) {
58
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
58
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
59
59
  if (!row)
60
60
  return void 0;
61
61
  return JSON.parse(row.value).value;
62
62
  }
63
63
  has(id) {
64
- const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
64
+ const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
65
65
  return row !== void 0;
66
66
  }
67
67
  /** Insert a new record, assigning it the next sequence number. */
@@ -71,32 +71,32 @@ var Collection = class {
71
71
  const stored = { seq, value };
72
72
  this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
73
73
  VALUES (?, ?, ?, ?, ?)
74
- ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
74
+ ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.collectionName, id, seq, JSON.stringify(stored));
75
75
  return stored;
76
76
  });
77
77
  }
78
78
  /** Replace an existing record's value, keeping its position. */
79
79
  update(id, value) {
80
80
  return this.sqlite.transaction(() => {
81
- const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
81
+ const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
82
82
  if (!row)
83
83
  return void 0;
84
84
  const stored = { seq: row.seq, value };
85
- this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
85
+ this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.collectionName, id);
86
86
  return stored;
87
87
  });
88
88
  }
89
89
  delete(id) {
90
- const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
90
+ const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.collectionName, id);
91
91
  return result.changes > 0;
92
92
  }
93
93
  /** How many records the collection holds, without reading them. */
94
94
  count() {
95
- const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
95
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.collectionName);
96
96
  return Number(row?.n ?? 0);
97
97
  }
98
98
  list(options = {}) {
99
- const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
99
+ const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.collectionName);
100
100
  const out = [];
101
101
  for (const row of rows) {
102
102
  const stored = JSON.parse(row.value);
@@ -353,16 +353,18 @@ var createControlPlane = (context) => {
353
353
  uptimeMs: context.wallNow() - context.startedAt,
354
354
  clock: context.clock.state(),
355
355
  namespaces: context.namespaces().length,
356
+ adminUi: `${ADMIN_PREFIX}/ui`,
356
357
  ...context.describe()
357
358
  });
358
359
  }
359
360
  if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
360
361
  return void 0;
361
362
  }
362
- if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
364
+ const shell = request.method === "GET" && (path === "/ui" || path === "/ui/");
365
+ if (!shell && context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
366
  return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
364
367
  }
365
- const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
366
368
  for (const route of routes) {
367
369
  if (route.method !== request.method)
368
370
  continue;
@@ -692,64 +694,64 @@ var graphemeLength = (value) => [...value].length;
692
694
  var validateValue = (document2, schema, value, path = []) => {
693
695
  const errors = [];
694
696
  const s = resolveSchema(document2, schema);
695
- const fail2 = (message) => errors.push({ path, message });
697
+ const fail3 = (message) => errors.push({ path, message });
696
698
  const actual = jsonTypeOf(value);
697
699
  if (actual === "undefined") {
698
- fail2("value is undefined");
700
+ fail3("value is undefined");
699
701
  return errors;
700
702
  }
701
703
  const types = schemaTypes(s);
702
704
  if (types.length > 0) {
703
705
  const ok2 = types.some((t) => t === actual || t === "number" && actual === "integer");
704
706
  if (!ok2) {
705
- fail2(`expected type ${types.join("|")}, got ${actual}`);
707
+ fail3(`expected type ${types.join("|")}, got ${actual}`);
706
708
  return errors;
707
709
  }
708
710
  }
709
711
  if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
710
- fail2("value not in enum");
712
+ fail3("value not in enum");
711
713
  }
712
714
  if (s.const !== void 0 && !deepEqual(s.const, value))
713
- fail2("value does not equal const");
715
+ fail3("value does not equal const");
714
716
  if (typeof value === "string") {
715
717
  const length = graphemeLength(value);
716
718
  if (s.minLength !== void 0 && length < s.minLength)
717
- fail2(`length ${length} < minLength ${s.minLength}`);
719
+ fail3(`length ${length} < minLength ${s.minLength}`);
718
720
  if (s.maxLength !== void 0 && length > s.maxLength)
719
- fail2(`length ${length} > maxLength ${s.maxLength}`);
721
+ fail3(`length ${length} > maxLength ${s.maxLength}`);
720
722
  if (s.pattern !== void 0) {
721
723
  try {
722
724
  if (!new RegExp(s.pattern, "u").test(value))
723
- fail2(`does not match pattern ${s.pattern}`);
725
+ fail3(`does not match pattern ${s.pattern}`);
724
726
  } catch {
725
727
  }
726
728
  }
727
729
  if (s.format !== void 0) {
728
730
  const pattern = FORMAT_PATTERNS[s.format];
729
731
  if (pattern && !pattern.test(value))
730
- fail2(`does not match format ${s.format}`);
732
+ fail3(`does not match format ${s.format}`);
731
733
  }
732
734
  }
733
735
  if (typeof value === "number") {
734
736
  if (s.minimum !== void 0 && value < s.minimum)
735
- fail2(`${value} < minimum ${s.minimum}`);
737
+ fail3(`${value} < minimum ${s.minimum}`);
736
738
  if (s.maximum !== void 0 && value > s.maximum)
737
- fail2(`${value} > maximum ${s.maximum}`);
739
+ fail3(`${value} > maximum ${s.maximum}`);
738
740
  if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
739
- fail2(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
741
+ fail3(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
740
742
  if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
741
- fail2(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
743
+ fail3(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
742
744
  if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
743
- fail2(`${value} is not a multiple of ${s.multipleOf}`);
745
+ fail3(`${value} is not a multiple of ${s.multipleOf}`);
744
746
  }
745
747
  }
746
748
  if (Array.isArray(value)) {
747
749
  if (s.minItems !== void 0 && value.length < s.minItems)
748
- fail2(`${value.length} items < minItems ${s.minItems}`);
750
+ fail3(`${value.length} items < minItems ${s.minItems}`);
749
751
  if (s.maxItems !== void 0 && value.length > s.maxItems)
750
- fail2(`${value.length} items > maxItems ${s.maxItems}`);
752
+ fail3(`${value.length} items > maxItems ${s.maxItems}`);
751
753
  if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
752
- fail2("items are not unique");
754
+ fail3("items are not unique");
753
755
  value.forEach((item, i) => {
754
756
  const itemSchema = s.prefixItems?.[i] ?? s.items;
755
757
  if (itemSchema)
@@ -761,11 +763,11 @@ var validateValue = (document2, schema, value, path = []) => {
761
763
  const keys = Object.keys(record);
762
764
  for (const name of s.required ?? [])
763
765
  if (!(name in record))
764
- fail2(`missing required property ${name}`);
766
+ fail3(`missing required property ${name}`);
765
767
  if (s.minProperties !== void 0 && keys.length < s.minProperties)
766
- fail2(`${keys.length} properties < minProperties ${s.minProperties}`);
768
+ fail3(`${keys.length} properties < minProperties ${s.minProperties}`);
767
769
  if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
768
- fail2(`${keys.length} properties > maxProperties ${s.maxProperties}`);
770
+ fail3(`${keys.length} properties > maxProperties ${s.maxProperties}`);
769
771
  for (const key of keys) {
770
772
  const property = s.properties?.[key];
771
773
  if (property) {
@@ -773,14 +775,14 @@ var validateValue = (document2, schema, value, path = []) => {
773
775
  continue;
774
776
  }
775
777
  if (s.additionalProperties === false)
776
- fail2(`unexpected property ${key}`);
778
+ fail3(`unexpected property ${key}`);
777
779
  else if (typeof s.additionalProperties === "object") {
778
780
  errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
779
781
  }
780
782
  if (s.propertyNames) {
781
783
  const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
782
784
  if (nameErrors.length > 0)
783
- fail2(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
785
+ fail3(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
784
786
  }
785
787
  }
786
788
  }
@@ -788,14 +790,14 @@ var validateValue = (document2, schema, value, path = []) => {
788
790
  for (const branch of s.allOf)
789
791
  errors.push(...validateValue(document2, branch, value, path));
790
792
  if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
791
- fail2("matches no anyOf branch");
793
+ fail3("matches no anyOf branch");
792
794
  if (s.oneOf) {
793
795
  const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
794
796
  if (matches2 !== 1)
795
- fail2(`matches ${matches2} oneOf branches, expected exactly 1`);
797
+ fail3(`matches ${matches2} oneOf branches, expected exactly 1`);
796
798
  }
797
799
  if (s.not && validateValue(document2, s.not, value).length === 0)
798
- fail2("matches forbidden `not` schema");
800
+ fail3("matches forbidden `not` schema");
799
801
  return errors;
800
802
  };
801
803
 
@@ -1368,6 +1370,936 @@ var clearNamespace = (sqlite, namespace) => {
1368
1370
  });
1369
1371
  };
1370
1372
 
1373
+ // ../core/dist/surface.js
1374
+ var defineMock = (runtime) => runtime;
1375
+ var STANDARD_ADMIN_ROUTES = [
1376
+ "GET /",
1377
+ "POST /reset",
1378
+ "GET /namespaces",
1379
+ "GET /clock",
1380
+ "POST /clock",
1381
+ "GET /faults",
1382
+ "POST /faults",
1383
+ "DELETE /faults",
1384
+ "POST /snapshots",
1385
+ "POST /snapshots/:id/restore",
1386
+ "DELETE /snapshots/:id",
1387
+ "GET /timeline",
1388
+ "POST /checkpoints",
1389
+ "POST /branches/:name",
1390
+ "POST /branches/:name/checkout",
1391
+ "GET /requests",
1392
+ "DELETE /requests",
1393
+ "GET /metrics",
1394
+ "DELETE /metrics",
1395
+ "GET /credentials",
1396
+ "PUT /credentials",
1397
+ "DELETE /credentials",
1398
+ "GET /state",
1399
+ "GET /state/:collection",
1400
+ "GET /state/:collection/:id",
1401
+ "POST /state/:collection",
1402
+ "PUT /state/:collection/:id",
1403
+ "PATCH /state/:collection/:id",
1404
+ "DELETE /state/:collection/:id",
1405
+ "GET /ui",
1406
+ "GET /ui/",
1407
+ "GET /ui/manifest"
1408
+ ];
1409
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1410
+ var assertAdminUi = (ui) => {
1411
+ if (!ui?.panels)
1412
+ return;
1413
+ const seen = /* @__PURE__ */ new Set();
1414
+ for (const panel of ui.panels) {
1415
+ if (!PANEL_ID.test(panel.id)) {
1416
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1417
+ }
1418
+ if (seen.has(panel.id))
1419
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1420
+ seen.add(panel.id);
1421
+ if (panel.title.trim() === "")
1422
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1423
+ }
1424
+ };
1425
+
1426
+ // ../core/dist/admin-ui.js
1427
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1428
+ switch (char) {
1429
+ case "&":
1430
+ return "&amp;";
1431
+ case "<":
1432
+ return "&lt;";
1433
+ case ">":
1434
+ return "&gt;";
1435
+ case '"':
1436
+ return "&quot;";
1437
+ default:
1438
+ return "&#39;";
1439
+ }
1440
+ });
1441
+ var renderAdminDocument = (service) => {
1442
+ const name = escapeHtml(service);
1443
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1444
+ return `<!DOCTYPE html>
1445
+ <html lang="en">
1446
+ <head>
1447
+ <meta charset="utf-8">
1448
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1449
+ <meta name="color-scheme" content="light dark">
1450
+ <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">
1451
+ <title>${name} admin</title>
1452
+ <style>
1453
+ :root {
1454
+ color-scheme: light;
1455
+ --bg: #f6f5f2;
1456
+ --bg-elev: #ffffff;
1457
+ --bg-muted: #eeece6;
1458
+ --bg-inset: #f3f1eb;
1459
+ --line: #e2dfd6;
1460
+ --line-strong: #d0ccc1;
1461
+ --ink: #1c1915;
1462
+ --muted: #5e584f;
1463
+ --faint: #8a8378;
1464
+ --accent: #3d4f3a;
1465
+ --accent-ink: #f7f6f2;
1466
+ --accent-soft: #e5ece2;
1467
+ --ok: #1f7a45;
1468
+ --ok-soft: #e5f4eb;
1469
+ --warn: #9a6700;
1470
+ --warn-soft: #fbf3df;
1471
+ --err: #a33b32;
1472
+ --err-soft: #fdecea;
1473
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1474
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1475
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1476
+ --radius: 14px;
1477
+ --header: 60px;
1478
+ --nav: 220px;
1479
+ }
1480
+ :root[data-theme="dark"] {
1481
+ color-scheme: dark;
1482
+ --bg: #141311;
1483
+ --bg-elev: #1e1c19;
1484
+ --bg-muted: #26231f;
1485
+ --bg-inset: #181715;
1486
+ --line: #34302b;
1487
+ --line-strong: #4a453d;
1488
+ --ink: #f4f1ea;
1489
+ --muted: #c4bdb1;
1490
+ --faint: #8f877c;
1491
+ --accent: #c5d5b8;
1492
+ --accent-ink: #1a2118;
1493
+ --accent-soft: #2a3328;
1494
+ --ok: #8fd6a8;
1495
+ --ok-soft: #1a2e22;
1496
+ --warn: #f0cc78;
1497
+ --warn-soft: #332911;
1498
+ --err: #f0a8a2;
1499
+ --err-soft: #3a201e;
1500
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1501
+ }
1502
+ @media (prefers-color-scheme: dark) {
1503
+ :root:not([data-theme="light"]) {
1504
+ color-scheme: dark;
1505
+ --bg: #141311;
1506
+ --bg-elev: #1e1c19;
1507
+ --bg-muted: #26231f;
1508
+ --bg-inset: #181715;
1509
+ --line: #34302b;
1510
+ --line-strong: #4a453d;
1511
+ --ink: #f4f1ea;
1512
+ --muted: #c4bdb1;
1513
+ --faint: #8f877c;
1514
+ --accent: #c5d5b8;
1515
+ --accent-ink: #1a2118;
1516
+ --accent-soft: #2a3328;
1517
+ --ok: #8fd6a8;
1518
+ --ok-soft: #1a2e22;
1519
+ --warn: #f0cc78;
1520
+ --warn-soft: #332911;
1521
+ --err: #f0a8a2;
1522
+ --err-soft: #3a201e;
1523
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1524
+ }
1525
+ }
1526
+ * { box-sizing: border-box; }
1527
+ html, body { margin: 0; height: 100%; }
1528
+ body {
1529
+ font-family: var(--sans);
1530
+ background: var(--bg);
1531
+ color: var(--ink);
1532
+ line-height: 1.45;
1533
+ padding-left: env(safe-area-inset-left);
1534
+ padding-right: env(safe-area-inset-right);
1535
+ -webkit-text-size-adjust: 100%;
1536
+ }
1537
+ button, input, select, textarea { font: inherit; color: inherit; }
1538
+ button { cursor: pointer; }
1539
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1540
+ @media (prefers-reduced-motion: reduce) {
1541
+ * { scroll-behavior: auto !important; transition: none !important; }
1542
+ }
1543
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1544
+ header.top {
1545
+ position: sticky; top: 0; z-index: 5;
1546
+ display: flex; align-items: center; gap: 12px;
1547
+ min-height: var(--header); padding: 10px 16px;
1548
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1549
+ border-bottom: 1px solid var(--line);
1550
+ backdrop-filter: blur(10px);
1551
+ }
1552
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1553
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1554
+ .brand span { color: var(--faint); font-size: 12px; }
1555
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1556
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1557
+ label.field input, label.field select, .controls input[type="password"] {
1558
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1559
+ padding: 7px 8px; min-height: 36px;
1560
+ }
1561
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1562
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1563
+ background: var(--bg-elev);
1564
+ }
1565
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1566
+ .btn-quiet { background: transparent; }
1567
+ .btn-danger { color: var(--err); }
1568
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1569
+ record or the full nav row would widen the page past the viewport. */
1570
+ .layout {
1571
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1572
+ flex: 1; min-height: 0; min-width: 0;
1573
+ }
1574
+ nav.side {
1575
+ border-right: 1px solid var(--line); padding: 12px;
1576
+ display: flex; flex-direction: column; gap: 4px;
1577
+ background: var(--bg-elev);
1578
+ }
1579
+ nav.side button {
1580
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1581
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1582
+ }
1583
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1584
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1585
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1586
+ .lede { margin: 0 0 16px; color: var(--muted); }
1587
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1588
+ .card {
1589
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1590
+ padding: 14px 16px; box-shadow: var(--shadow);
1591
+ }
1592
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1593
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1594
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1595
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1596
+ .collection {
1597
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1598
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1599
+ }
1600
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1601
+ .collection small { display: block; color: var(--faint); }
1602
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1603
+ .chip {
1604
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1605
+ border-radius: 999px; padding: 4px 8px;
1606
+ }
1607
+ .chip i { color: var(--faint); font-style: normal; }
1608
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1609
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1610
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1611
+ tr.clickable { cursor: pointer; }
1612
+ tr.clickable:hover { background: var(--bg-muted); }
1613
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1614
+ pre {
1615
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1616
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1617
+ }
1618
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1619
+ .banner {
1620
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1621
+ background: var(--err-soft); color: var(--err);
1622
+ }
1623
+ .banner.show { display: block; }
1624
+ .empty { color: var(--muted); padding: 24px 8px; }
1625
+ dialog {
1626
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1627
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1628
+ }
1629
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1630
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1631
+ textarea {
1632
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1633
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1634
+ font-family: var(--mono); font-size: 12px;
1635
+ }
1636
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1637
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1638
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1639
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1640
+ .status-2 { color: var(--ok); }
1641
+ .status-4, .status-5, .status-0 { color: var(--err); }
1642
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1643
+ .route {
1644
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1645
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1646
+ }
1647
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1648
+ @media (max-width: 800px) {
1649
+ header.top {
1650
+ align-items: stretch; flex-direction: column;
1651
+ padding-top: max(10px, env(safe-area-inset-top));
1652
+ }
1653
+ input, select, textarea { font-size: 16px; }
1654
+ .controls { width: 100%; }
1655
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1656
+ .layout { grid-template-columns: minmax(0, 1fr); }
1657
+ nav.side {
1658
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1659
+ border-right: 0; border-bottom: 1px solid var(--line);
1660
+ padding: 8px;
1661
+ }
1662
+ nav.side button { white-space: nowrap; flex: none; }
1663
+ .split { grid-template-columns: minmax(0, 1fr); }
1664
+ main { padding: 14px; }
1665
+ table, thead, tbody, tr, th, td { display: block; }
1666
+ thead { display: none; }
1667
+ tr {
1668
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1669
+ background: var(--bg-elev); min-width: 0;
1670
+ }
1671
+ td {
1672
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1673
+ min-width: 0; overflow-wrap: anywhere;
1674
+ }
1675
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1676
+ .route { grid-template-columns: 72px 1fr; }
1677
+ .route button { grid-column: 1 / -1; }
1678
+ }
1679
+ </style>
1680
+ </head>
1681
+ <body>
1682
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1683
+ <header class="top">
1684
+ <div class="brand">
1685
+ <strong>${name}</strong>
1686
+ <span>Mockingbird admin</span>
1687
+ </div>
1688
+ <div class="controls">
1689
+ <label class="field">Namespace
1690
+ <select id="namespace" aria-label="Namespace"></select>
1691
+ </label>
1692
+ <label class="field">Admin key
1693
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1694
+ </label>
1695
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1696
+ <button class="btn" id="refresh" type="button">Refresh</button>
1697
+ </div>
1698
+ </header>
1699
+ <div class="layout">
1700
+ <nav class="side" id="nav" aria-label="Admin sections">
1701
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1702
+ <button type="button" data-view="state">State</button>
1703
+ <button type="button" data-view="clock">Clock</button>
1704
+ <button type="button" data-view="faults">Faults</button>
1705
+ <button type="button" data-view="journal">Journal</button>
1706
+ <button type="button" data-view="routes">Routes</button>
1707
+ </nav>
1708
+ <main id="views">
1709
+ <p class="banner" id="banner" role="alert"></p>
1710
+ <section class="view" id="view-overview">
1711
+ <h2>Overview</h2>
1712
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1713
+ <div class="grid" id="overview-cards"></div>
1714
+ <h3>Recent requests</h3>
1715
+ <div id="overview-requests"></div>
1716
+ </section>
1717
+ <section class="view" id="view-state" hidden>
1718
+ <h2>State</h2>
1719
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1720
+ <div class="split">
1721
+ <div id="collections"></div>
1722
+ <div>
1723
+ <div id="schema"></div>
1724
+ <div class="row-actions">
1725
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1726
+ </div>
1727
+ <div id="records"></div>
1728
+ </div>
1729
+ </div>
1730
+ </section>
1731
+ <section class="view" id="view-clock" hidden>
1732
+ <h2>Clock</h2>
1733
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1734
+ <div class="card" id="clock-readout"></div>
1735
+ <div class="row-actions">
1736
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1737
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1738
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1739
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1740
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1741
+ <button class="btn" id="freeze" type="button">Freeze</button>
1742
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1743
+ </div>
1744
+ <form id="clock-set" class="row-actions">
1745
+ <label class="field">Set instant
1746
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1747
+ </label>
1748
+ <button class="btn-primary" type="submit">Set</button>
1749
+ </form>
1750
+ </section>
1751
+ <section class="view" id="view-faults" hidden>
1752
+ <h2>Faults</h2>
1753
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1754
+ <form id="fault-form" class="card stack">
1755
+ <label class="field">Preset
1756
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1757
+ </label>
1758
+ <label class="field">Status
1759
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1760
+ </label>
1761
+ <label class="field">Path prefix
1762
+ <input id="fault-path" placeholder="/v1">
1763
+ </label>
1764
+ <label class="field">Method
1765
+ <input id="fault-method" placeholder="GET">
1766
+ </label>
1767
+ <div class="dialog-actions">
1768
+ <button class="btn-primary" type="submit">Add fault</button>
1769
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1770
+ </div>
1771
+ </form>
1772
+ <div id="fault-list"></div>
1773
+ </section>
1774
+ <section class="view" id="view-journal" hidden>
1775
+ <h2>Journal</h2>
1776
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1777
+ <div class="row-actions">
1778
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1779
+ </div>
1780
+ <div id="journal"></div>
1781
+ </section>
1782
+ <section class="view" id="view-routes" hidden>
1783
+ <h2>Routes</h2>
1784
+ <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>
1785
+ <div id="route-list"></div>
1786
+ <form id="route-form" class="card stack">
1787
+ <strong id="route-title">Select a route</strong>
1788
+ <label class="field">JSON body
1789
+ <textarea id="route-body" placeholder="{ }"></textarea>
1790
+ </label>
1791
+ <div class="dialog-actions">
1792
+ <button class="btn-primary" type="submit">Send</button>
1793
+ </div>
1794
+ <pre id="route-result">Response will show here.</pre>
1795
+ </form>
1796
+ </section>
1797
+ </main>
1798
+ </div>
1799
+ </div>
1800
+ <dialog id="editor">
1801
+ <form method="dialog" id="editor-form">
1802
+ <strong id="editor-title">Record</strong>
1803
+ <label class="field">Id
1804
+ <input id="editor-id" required>
1805
+ </label>
1806
+ <label class="field">JSON value
1807
+ <textarea id="editor-value"></textarea>
1808
+ </label>
1809
+ <div class="dialog-actions">
1810
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1811
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1812
+ <button class="btn-primary" type="submit" value="save">Save</button>
1813
+ </div>
1814
+ </form>
1815
+ </dialog>
1816
+ <script>
1817
+ (() => {
1818
+ const STANDARD = new Set(${standard})
1819
+ const state = {
1820
+ namespace: "default",
1821
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1822
+ view: "overview",
1823
+ collection: "",
1824
+ shape: null,
1825
+ route: null,
1826
+ editing: null
1827
+ }
1828
+ const $ = (id) => document.getElementById(id)
1829
+ const banner = $("banner")
1830
+ const keyInput = $("admin-key")
1831
+ keyInput.value = state.key
1832
+ const params = new URLSearchParams(location.search)
1833
+ if (params.get("key")) {
1834
+ state.key = params.get("key")
1835
+ keyInput.value = state.key
1836
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1837
+ params.delete("key")
1838
+ const next = params.toString()
1839
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1840
+ }
1841
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1842
+
1843
+ const showError = (error) => {
1844
+ banner.textContent = error instanceof Error ? error.message : String(error)
1845
+ banner.classList.add("show")
1846
+ }
1847
+ const clearError = () => banner.classList.remove("show")
1848
+
1849
+ async function originGet(path) {
1850
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1851
+ if (!response.ok) throw new Error(response.status + " " + path)
1852
+ return response.json()
1853
+ }
1854
+ async function api(method, path, body) {
1855
+ const headers = { accept: "application/json" }
1856
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1857
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1858
+ if (body !== undefined) headers["content-type"] = "application/json"
1859
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1860
+ method,
1861
+ headers,
1862
+ body: body === undefined ? undefined : JSON.stringify(body)
1863
+ })
1864
+ const text = await response.text()
1865
+ let data = null
1866
+ if (text) {
1867
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1868
+ }
1869
+ if (response.status === 401) {
1870
+ keyInput.focus()
1871
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1872
+ }
1873
+ if (!response.ok) {
1874
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1875
+ }
1876
+ return data
1877
+ }
1878
+ const panelApi = {
1879
+ get: (path) => api("GET", path),
1880
+ send: (method, path, body) => api(method, path, body),
1881
+ namespace: () => state.namespace
1882
+ }
1883
+
1884
+ function setTheme(theme) {
1885
+ if (theme) document.documentElement.dataset.theme = theme
1886
+ else delete document.documentElement.dataset.theme
1887
+ }
1888
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1889
+ if (storedTheme) setTheme(storedTheme)
1890
+ $("theme").addEventListener("click", () => {
1891
+ const current = document.documentElement.dataset.theme
1892
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1893
+ const next = dark ? "light" : "dark"
1894
+ localStorage.setItem("mockingbird-admin-theme", next)
1895
+ setTheme(next)
1896
+ })
1897
+
1898
+ function show(view) {
1899
+ state.view = view
1900
+ for (const button of document.querySelectorAll("#nav button")) {
1901
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1902
+ }
1903
+ for (const section of document.querySelectorAll("main .view")) {
1904
+ section.hidden = section.id !== "view-" + view
1905
+ }
1906
+ }
1907
+ document.getElementById("nav").addEventListener("click", (event) => {
1908
+ const button = event.target.closest("button[data-view]")
1909
+ if (!button) return
1910
+ show(button.dataset.view)
1911
+ refresh().catch(showError)
1912
+ })
1913
+
1914
+ function cards(items) {
1915
+ return '<div class="grid">' + items.map((item) =>
1916
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1917
+ ).join("") + "</div>"
1918
+ }
1919
+ function table(columns, rows) {
1920
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1921
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1922
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1923
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1924
+ ).join("") + "</tr>").join("")
1925
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1926
+ }
1927
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1928
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1929
+ }[char]))
1930
+ const preview = (value) => {
1931
+ const text = JSON.stringify(value)
1932
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1933
+ }
1934
+ const when = (epoch) => {
1935
+ const date = new Date(epoch)
1936
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1937
+ }
1938
+ const clockCard = (epoch) => {
1939
+ const date = new Date(epoch)
1940
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1941
+ const iso = date.toISOString()
1942
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1943
+ }
1944
+
1945
+ async function loadNamespaces() {
1946
+ const data = await api("GET", "/namespaces")
1947
+ const select = $("namespace")
1948
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1949
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1950
+ select.innerHTML = names.map((name) =>
1951
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1952
+ ).join("")
1953
+ select.value = state.namespace
1954
+ }
1955
+
1956
+ async function renderOverview() {
1957
+ const [health, shape, clock, journal] = await Promise.all([
1958
+ originGet("/health"),
1959
+ api("GET", "/state"),
1960
+ api("GET", "/clock"),
1961
+ api("GET", "/requests?limit=8")
1962
+ ])
1963
+ state.shape = shape
1964
+ $("overview-cards").innerHTML = cards([
1965
+ { k: "Service", v: esc(health.service || "${name}") },
1966
+ { k: "Status", v: esc(health.status || "ok") },
1967
+ { k: "Namespace", v: esc(state.namespace) },
1968
+ { k: "Collections", v: String(shape.collections.length) },
1969
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1970
+ { k: "Clock", v: clockCard(clock.now) }
1971
+ ])
1972
+ const requests = (journal && journal.requests) || []
1973
+ $("overview-requests").innerHTML = table(
1974
+ [
1975
+ { label: "Method", cell: (row) => esc(row.method) },
1976
+ { label: "Path", cell: (row) => esc(row.path) },
1977
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1978
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1979
+ ],
1980
+ requests
1981
+ )
1982
+ }
1983
+
1984
+ function schemaChips(collection) {
1985
+ if (!collection || collection.fields.length === 0) {
1986
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
1987
+ }
1988
+ return '<div class="chips">' + collection.fields.map((field) =>
1989
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
1990
+ ).join("") + "</div>"
1991
+ }
1992
+
1993
+ async function renderState() {
1994
+ const shape = await api("GET", "/state")
1995
+ state.shape = shape
1996
+ const host = $("collections")
1997
+ if (shape.collections.length === 0) {
1998
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
1999
+ $("schema").innerHTML = ""
2000
+ $("records").innerHTML = ""
2001
+ return
2002
+ }
2003
+ if (!shape.collections.some((item) => item.name === state.collection)) {
2004
+ state.collection = shape.collections[0].name
2005
+ }
2006
+ host.innerHTML = shape.collections.map((item) =>
2007
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
2008
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
2009
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
2010
+ ).join("")
2011
+ const selected = shape.collections.find((item) => item.name === state.collection)
2012
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
2013
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
2014
+ schemaChips(selected)
2015
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
2016
+ const rows = page.records.map((record) => ({
2017
+ ...record,
2018
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
2019
+ }))
2020
+ $("records").innerHTML = table(
2021
+ [
2022
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
2023
+ { label: "Seq", cell: (row) => esc(row.seq) },
2024
+ { label: "Value", cell: (row) => preview(row.value) }
2025
+ ],
2026
+ rows
2027
+ )
2028
+ }
2029
+
2030
+ async function renderClock() {
2031
+ const clock = await api("GET", "/clock")
2032
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
2033
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
2034
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
2035
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
2036
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
2037
+ }
2038
+
2039
+ async function renderFaults() {
2040
+ const [faults, presets] = await Promise.all([
2041
+ api("GET", "/faults"),
2042
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2043
+ ])
2044
+ const select = $("fault-preset")
2045
+ const current = select.value
2046
+ const list = presets.presets || []
2047
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
2048
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
2049
+ ).join("")
2050
+ select.value = current
2051
+ const rules = faults.faults || []
2052
+ $("fault-list").innerHTML = table(
2053
+ [
2054
+ { label: "Id", cell: (row) => esc(row.id) },
2055
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
2056
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
2057
+ ],
2058
+ rules
2059
+ )
2060
+ }
2061
+
2062
+ async function renderJournal() {
2063
+ const journal = await api("GET", "/requests?limit=100")
2064
+ $("journal").innerHTML = table(
2065
+ [
2066
+ { label: "When", cell: (row) => esc(row.at || "") },
2067
+ { label: "Method", cell: (row) => esc(row.method) },
2068
+ { label: "Path", cell: (row) => esc(row.path) },
2069
+ { label: "Status", cell: (row) => esc(row.status) },
2070
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2071
+ ],
2072
+ journal.requests || []
2073
+ )
2074
+ }
2075
+
2076
+ async function renderRoutes() {
2077
+ const data = await api("GET", "/")
2078
+ const routes = data.routes || []
2079
+ $("route-list").innerHTML = routes.map((route) => {
2080
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
2081
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
2082
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
2083
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
2084
+ }).join("")
2085
+ }
2086
+
2087
+ const renderers = {
2088
+ overview: renderOverview,
2089
+ state: renderState,
2090
+ clock: renderClock,
2091
+ faults: renderFaults,
2092
+ journal: renderJournal,
2093
+ routes: renderRoutes
2094
+ }
2095
+
2096
+ async function refresh() {
2097
+ clearError()
2098
+ if (state.view in renderers) await renderers[state.view]()
2099
+ }
2100
+
2101
+ $("namespace").addEventListener("change", () => {
2102
+ state.namespace = $("namespace").value
2103
+ refresh().catch(showError)
2104
+ })
2105
+ keyInput.addEventListener("change", () => {
2106
+ state.key = keyInput.value.trim()
2107
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
2108
+ refresh().catch(showError)
2109
+ })
2110
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
2111
+
2112
+ $("collections").addEventListener("click", (event) => {
2113
+ const button = event.target.closest("[data-collection]")
2114
+ if (!button) return
2115
+ state.collection = button.dataset.collection
2116
+ renderState().catch(showError)
2117
+ })
2118
+ $("records").addEventListener("click", (event) => {
2119
+ const row = event.target.closest("[data-id]")
2120
+ if (!row) return
2121
+ openEditor(row.dataset.id).catch(showError)
2122
+ })
2123
+
2124
+ const editor = $("editor")
2125
+ async function openEditor(id) {
2126
+ state.editing = id || null
2127
+ $("editor-title").textContent = id ? "Edit record" : "New record"
2128
+ $("editor-id").value = id || ""
2129
+ $("editor-id").readOnly = Boolean(id)
2130
+ $("editor-delete").hidden = !id
2131
+ if (id) {
2132
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2133
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
2134
+ } else {
2135
+ $("editor-value").value = "{\\n \\n}"
2136
+ }
2137
+ editor.showModal()
2138
+ }
2139
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
2140
+ $("editor-form").addEventListener("submit", (event) => {
2141
+ const submitter = event.submitter
2142
+ if (!submitter || submitter.value !== "save") return
2143
+ event.preventDefault()
2144
+ let value
2145
+ try { value = JSON.parse($("editor-value").value) }
2146
+ catch { showError(new Error("Value is not JSON")); return }
2147
+ const id = $("editor-id").value.trim()
2148
+ const path = "/state/" + encodeURIComponent(state.collection)
2149
+ const request = state.editing
2150
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
2151
+ : api("POST", path, { id: id || undefined, value })
2152
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
2153
+ })
2154
+ $("editor-delete").addEventListener("click", () => {
2155
+ const id = state.editing
2156
+ if (!id) return
2157
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2158
+ .then(() => { editor.close(); return renderState() })
2159
+ .catch(showError)
2160
+ })
2161
+
2162
+ document.querySelectorAll("[data-advance]").forEach((button) => {
2163
+ button.addEventListener("click", () => {
2164
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
2165
+ })
2166
+ })
2167
+ $("freeze").addEventListener("click", () => {
2168
+ const frozen = $("freeze").dataset.frozen === "1"
2169
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
2170
+ })
2171
+ $("clock-reset").addEventListener("click", () => {
2172
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
2173
+ })
2174
+ $("clock-set").addEventListener("submit", (event) => {
2175
+ event.preventDefault()
2176
+ const raw = $("clock-instant").value.trim()
2177
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
2178
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
2179
+ })
2180
+
2181
+ $("fault-form").addEventListener("submit", (event) => {
2182
+ event.preventDefault()
2183
+ const preset = $("fault-preset").value
2184
+ const body = preset
2185
+ ? { preset }
2186
+ : {
2187
+ status: Number($("fault-status").value),
2188
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
2189
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
2190
+ }
2191
+ if (!preset && !Number.isFinite(body.status)) {
2192
+ showError(new Error("Status must be a number, or choose a preset"))
2193
+ return
2194
+ }
2195
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
2196
+ })
2197
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
2198
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
2199
+
2200
+ $("route-list").addEventListener("click", (event) => {
2201
+ const button = event.target.closest("[data-route]")
2202
+ if (!button) return
2203
+ state.route = button.dataset.route
2204
+ $("route-title").textContent = state.route
2205
+ const method = state.route.split(" ")[0]
2206
+ $("route-body").disabled = method === "GET" || method === "DELETE"
2207
+ })
2208
+ $("route-form").addEventListener("submit", async (event) => {
2209
+ event.preventDefault()
2210
+ if (!state.route) return showError(new Error("Choose a route first"))
2211
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
2212
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
2213
+ let body
2214
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
2215
+ try { body = JSON.parse($("route-body").value) }
2216
+ catch { return showError(new Error("Body is not JSON")) }
2217
+ }
2218
+ try {
2219
+ const data = await api(method, concrete, body)
2220
+ $("route-result").textContent = JSON.stringify(data, null, 2)
2221
+ } catch (error) {
2222
+ showError(error)
2223
+ }
2224
+ })
2225
+
2226
+ function mountPanels(panels) {
2227
+ const nav = $("nav")
2228
+ const views = $("views")
2229
+ for (const panel of panels) {
2230
+ const button = document.createElement("button")
2231
+ button.type = "button"
2232
+ button.dataset.view = panel.id
2233
+ button.textContent = panel.title
2234
+ nav.append(button)
2235
+ const section = document.createElement("section")
2236
+ section.className = "view"
2237
+ section.id = "view-" + panel.id
2238
+ section.hidden = true
2239
+ const title = document.createElement("h2")
2240
+ title.textContent = panel.title
2241
+ const lede = document.createElement("p")
2242
+ lede.className = "lede"
2243
+ lede.textContent = panel.description || ""
2244
+ const body = document.createElement("div")
2245
+ body.className = "panel-body"
2246
+ body.id = "panel-" + panel.id
2247
+ body.innerHTML = panel.html || ""
2248
+ section.append(title, lede, body)
2249
+ views.append(section)
2250
+ if (panel.script) {
2251
+ try {
2252
+ const run = new Function("root", "api", panel.script)
2253
+ run(body, panelApi)
2254
+ } catch (error) {
2255
+ const note = document.createElement("p")
2256
+ note.className = "banner show"
2257
+ note.textContent = error instanceof Error ? error.message : String(error)
2258
+ body.append(note)
2259
+ }
2260
+ }
2261
+ }
2262
+ }
2263
+
2264
+ loadNamespaces()
2265
+ .then(() => api("GET", "/ui/manifest"))
2266
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2267
+ .catch(showError)
2268
+ })()
2269
+ </script>
2270
+ </body>
2271
+ </html>`;
2272
+ };
2273
+ var htmlResponse = (body) => new Response(body, {
2274
+ status: 200,
2275
+ headers: {
2276
+ "content-type": "text/html; charset=utf-8",
2277
+ "cache-control": "no-store"
2278
+ }
2279
+ });
2280
+ var json2 = (body) => new Response(JSON.stringify(body), {
2281
+ status: 200,
2282
+ headers: { "content-type": "application/json; charset=utf-8" }
2283
+ });
2284
+ var adminUiRoutes = (service, ui) => {
2285
+ const shell = () => renderAdminDocument(service);
2286
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2287
+ return {
2288
+ "GET /ui": () => htmlResponse(document2()),
2289
+ "GET /ui/": () => htmlResponse(document2()),
2290
+ "GET /ui/manifest": () => json2({
2291
+ service,
2292
+ panels: (ui?.panels ?? []).map((panel) => ({
2293
+ id: panel.id,
2294
+ title: panel.title,
2295
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2296
+ html: panel.html,
2297
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2298
+ }))
2299
+ })
2300
+ };
2301
+ };
2302
+
1371
2303
  // ../../openapi/metadata/dist/types.js
1372
2304
  var EXTENSION_KEYS = {
1373
2305
  operation: "x-mockingbird",
@@ -1605,15 +2537,449 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1605
2537
  });
1606
2538
  };
1607
2539
 
2540
+ // ../core/dist/state-view.js
2541
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2542
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2543
+ var SAMPLE = 25;
2544
+ var WALK_LIMIT = 1e4;
2545
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2546
+ var fail2 = (status, message) => ({ ok: false, status, message });
2547
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2548
+ var kindOf = (value) => {
2549
+ if (value === null)
2550
+ return "null";
2551
+ if (Array.isArray(value))
2552
+ return "array";
2553
+ switch (typeof value) {
2554
+ case "string":
2555
+ return "string";
2556
+ case "number":
2557
+ return Number.isFinite(value) ? "number" : "unknown";
2558
+ case "boolean":
2559
+ return "boolean";
2560
+ case "object":
2561
+ return "object";
2562
+ default:
2563
+ return "unknown";
2564
+ }
2565
+ };
2566
+ var humanize = (name) => {
2567
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2568
+ if (words === "")
2569
+ return name;
2570
+ return words.charAt(0).toUpperCase() + words.slice(1);
2571
+ };
2572
+ var jsonValue = (value) => {
2573
+ if (value === void 0)
2574
+ return fail2(400, "value is required");
2575
+ try {
2576
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2577
+ } catch {
2578
+ return fail2(400, "value must be JSON");
2579
+ }
2580
+ };
2581
+ var ctorName = (value) => {
2582
+ const ctor = value.constructor;
2583
+ return typeof ctor?.name === "string" ? ctor.name : "";
2584
+ };
2585
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2586
+ var discoverCollections = (root) => {
2587
+ const found = [];
2588
+ const seen = /* @__PURE__ */ new Set();
2589
+ const visit = (value, depth) => {
2590
+ if (found.length + seen.size > WALK_LIMIT)
2591
+ return;
2592
+ if (value === null || typeof value !== "object")
2593
+ return;
2594
+ if (seen.has(value))
2595
+ return;
2596
+ seen.add(value);
2597
+ if (value instanceof Collection) {
2598
+ found.push(value);
2599
+ return;
2600
+ }
2601
+ if (value instanceof Map) {
2602
+ for (const child of value.values())
2603
+ visit(child, depth + 1);
2604
+ return;
2605
+ }
2606
+ if (value instanceof Set) {
2607
+ for (const child of value.values())
2608
+ visit(child, depth + 1);
2609
+ return;
2610
+ }
2611
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2612
+ return;
2613
+ if (Array.isArray(value)) {
2614
+ const cap = Math.min(value.length, 32);
2615
+ for (let i = 0; i < cap; i++)
2616
+ visit(value[i], depth + 1);
2617
+ return;
2618
+ }
2619
+ let children;
2620
+ try {
2621
+ children = Object.values(value);
2622
+ } catch {
2623
+ return;
2624
+ }
2625
+ for (const child of children)
2626
+ visit(child, depth + 1);
2627
+ };
2628
+ visit(root, 0);
2629
+ return found;
2630
+ };
2631
+ var storedNames = (sqlite, namespace) => {
2632
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2633
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2634
+ return [...records, ...sequences].map((row) => row.name);
2635
+ };
2636
+ var blankAccum = (name) => ({
2637
+ name,
2638
+ kinds: /* @__PURE__ */ new Set(),
2639
+ present: 0,
2640
+ nested: /* @__PURE__ */ new Map()
2641
+ });
2642
+ var absorb = (accum, value) => {
2643
+ const kind = kindOf(value);
2644
+ accum.kinds.add(kind);
2645
+ accum.present++;
2646
+ if (!isRecord3(value))
2647
+ return;
2648
+ for (const [key, child] of Object.entries(value)) {
2649
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2650
+ absorb(nested, child);
2651
+ accum.nested.set(key, nested);
2652
+ }
2653
+ };
2654
+ var finishField = (accum, samples) => {
2655
+ const kinds = [...accum.kinds];
2656
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2657
+ const field = {
2658
+ name: accum.name,
2659
+ kind,
2660
+ optional: accum.present < samples || kinds.includes("null")
2661
+ };
2662
+ if (accum.nested.size > 0) {
2663
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2664
+ }
2665
+ return field;
2666
+ };
2667
+ var inferFields = (records) => {
2668
+ if (records.length === 0)
2669
+ return [];
2670
+ const sample = records.slice(0, SAMPLE);
2671
+ const objects = sample.filter((record) => isRecord3(record.value));
2672
+ if (objects.length === 0) {
2673
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2674
+ const list = [...kinds];
2675
+ return [
2676
+ {
2677
+ name: "(value)",
2678
+ kind: list.length === 1 ? list[0] : "unknown",
2679
+ optional: false
2680
+ }
2681
+ ];
2682
+ }
2683
+ const root = /* @__PURE__ */ new Map();
2684
+ for (const record of objects) {
2685
+ for (const [key, value] of Object.entries(record.value)) {
2686
+ const accum = root.get(key) ?? blankAccum(key);
2687
+ absorb(accum, value);
2688
+ root.set(key, accum);
2689
+ }
2690
+ }
2691
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2692
+ };
2693
+ var mergeFields = (declared, inferred) => {
2694
+ const byName = /* @__PURE__ */ new Map();
2695
+ for (const field of inferred)
2696
+ byName.set(field.name, field);
2697
+ const ordered = [];
2698
+ const seen = /* @__PURE__ */ new Set();
2699
+ for (const field of declared ?? []) {
2700
+ const found = byName.get(field.name);
2701
+ seen.add(field.name);
2702
+ if (!found) {
2703
+ ordered.push({ ...field, optional: field.optional });
2704
+ continue;
2705
+ }
2706
+ ordered.push({
2707
+ ...found,
2708
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2709
+ optional: field.optional || found.optional,
2710
+ ...field.description !== void 0 ? { description: field.description } : {},
2711
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2712
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2713
+ });
2714
+ }
2715
+ for (const field of inferred) {
2716
+ if (!seen.has(field.name))
2717
+ ordered.push(field);
2718
+ }
2719
+ return ordered;
2720
+ };
2721
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2722
+ var readRecord = (collection, id) => {
2723
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2724
+ const row = rows.find((entry) => entry.id === id);
2725
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2726
+ };
2727
+ var inspectState = (scope) => {
2728
+ const declared = /* @__PURE__ */ new Map();
2729
+ for (const declaration of scope.declarations ?? []) {
2730
+ if (COLLECTION_NAME.test(declaration.name))
2731
+ declared.set(declaration.name, declaration);
2732
+ }
2733
+ const names = new Set(declared.keys());
2734
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2735
+ names.add(name);
2736
+ for (const collection of discoverCollections(scope.root)) {
2737
+ if (collection.namespace === scope.storageNamespace)
2738
+ names.add(collection.collectionName);
2739
+ }
2740
+ const collections = [];
2741
+ for (const name of names) {
2742
+ if (!COLLECTION_NAME.test(name))
2743
+ continue;
2744
+ const declaration = declared.get(name);
2745
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2746
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2747
+ const inferred = inferFields(records);
2748
+ const fields = mergeFields(declaration?.fields, inferred);
2749
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2750
+ collections.push({
2751
+ name,
2752
+ label: declaration?.label ?? humanize(name),
2753
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2754
+ count: collection.count(),
2755
+ source,
2756
+ fields,
2757
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2758
+ });
2759
+ }
2760
+ const order = /* @__PURE__ */ new Map();
2761
+ for (const [index, item] of (scope.declarations ?? []).entries())
2762
+ order.set(item.name, index);
2763
+ collections.sort((a, b) => {
2764
+ const left = order.get(a.name);
2765
+ const right = order.get(b.name);
2766
+ if (left !== void 0 && right !== void 0)
2767
+ return left - right;
2768
+ if (left !== void 0)
2769
+ return -1;
2770
+ if (right !== void 0)
2771
+ return 1;
2772
+ return a.name.localeCompare(b.name);
2773
+ });
2774
+ return {
2775
+ namespace: scope.namespace,
2776
+ storageNamespace: scope.storageNamespace,
2777
+ collections
2778
+ };
2779
+ };
2780
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2781
+ if (!COLLECTION_NAME.test(name))
2782
+ return fail2(400, "collection name is not allowed");
2783
+ const limit = query.limit ?? 50;
2784
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2785
+ return fail2(400, "limit must be an integer from 1 to 200");
2786
+ }
2787
+ const order = query.order ?? "newest";
2788
+ if (order !== "newest" && order !== "oldest")
2789
+ return fail2(400, 'order must be "newest" or "oldest"');
2790
+ const collection = collectionOf(sqlite, storageNamespace, name);
2791
+ const rows = collection.list({ order }).filter((row) => {
2792
+ if (query.after === void 0)
2793
+ return true;
2794
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2795
+ });
2796
+ const slice = rows.slice(0, limit);
2797
+ const last = slice.at(-1);
2798
+ return {
2799
+ ok: true,
2800
+ value: {
2801
+ collection: name,
2802
+ count: collection.count(),
2803
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2804
+ next: rows.length > limit && last ? last.seq : null
2805
+ }
2806
+ };
2807
+ };
2808
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2809
+ var readStateRecord = (scope, name, id) => {
2810
+ if (!COLLECTION_NAME.test(name))
2811
+ return fail2(400, "collection name is not allowed");
2812
+ if (!RECORD_ID.test(id))
2813
+ return fail2(400, "record id is not allowed");
2814
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2815
+ return record ? { ok: true, value: record } : fail2(404, `no record ${id} in ${name}`);
2816
+ };
2817
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail2(400, "id must be a single path segment");
2818
+ var createStateRecord = (scope, name, input) => {
2819
+ if (!COLLECTION_NAME.test(name))
2820
+ return fail2(400, "collection name is not allowed");
2821
+ const parsed = jsonValue(input.value);
2822
+ if (!parsed.ok)
2823
+ return parsed;
2824
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2825
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2826
+ const checked = requireId(id);
2827
+ if (!checked.ok)
2828
+ return checked;
2829
+ if (collection.has(checked.value))
2830
+ return fail2(409, `record ${checked.value} already exists`);
2831
+ const stored = collection.insert(checked.value, parsed.value);
2832
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2833
+ };
2834
+ var replaceStateRecord = (scope, name, id, value) => {
2835
+ if (!COLLECTION_NAME.test(name))
2836
+ return fail2(400, "collection name is not allowed");
2837
+ const checked = requireId(id);
2838
+ if (!checked.ok)
2839
+ return checked;
2840
+ const parsed = jsonValue(value);
2841
+ if (!parsed.ok)
2842
+ return parsed;
2843
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2844
+ if (!collection.has(checked.value))
2845
+ return fail2(404, `no record ${checked.value} in ${name}`);
2846
+ const stored = collection.update(checked.value, parsed.value);
2847
+ if (!stored)
2848
+ return fail2(404, `no record ${checked.value} in ${name}`);
2849
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2850
+ };
2851
+ var patchStateRecord = (scope, name, id, value) => {
2852
+ const current = readStateRecord(scope, name, id);
2853
+ if (!current.ok)
2854
+ return current;
2855
+ const parsed = jsonValue(value);
2856
+ if (!parsed.ok)
2857
+ return parsed;
2858
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2859
+ return replaceStateRecord(scope, name, id, next);
2860
+ };
2861
+ var deleteStateRecord = (scope, name, id) => {
2862
+ if (!COLLECTION_NAME.test(name))
2863
+ return fail2(400, "collection name is not allowed");
2864
+ const checked = requireId(id);
2865
+ if (!checked.ok)
2866
+ return checked;
2867
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2868
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail2(404, `no record ${checked.value} in ${name}`);
2869
+ };
2870
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2871
+ status,
2872
+ headers: { "content-type": "application/json; charset=utf-8" }
2873
+ });
2874
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2875
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2876
+ var integerParam = (value) => {
2877
+ if (value === null)
2878
+ return void 0;
2879
+ if (!/^-?\d+$/.test(value))
2880
+ return "bad";
2881
+ return Number(value);
2882
+ };
2883
+ var stateAdminRoutes = (routes) => {
2884
+ const open = (namespace) => {
2885
+ try {
2886
+ return { ok: true, value: routes.open(namespace) };
2887
+ } catch (error) {
2888
+ return fail2(400, error instanceof Error ? error.message : String(error));
2889
+ }
2890
+ };
2891
+ const wrote = (namespace) => {
2892
+ routes.afterWrite?.(namespace);
2893
+ };
2894
+ return {
2895
+ "GET /state": ({ namespace }) => {
2896
+ const scope = open(namespace);
2897
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2898
+ },
2899
+ "GET /state/:collection": ({ namespace, params, url }) => {
2900
+ const scope = open(namespace);
2901
+ if (!scope.ok)
2902
+ return fromResult(scope, 200);
2903
+ const limit = integerParam(url.searchParams.get("limit"));
2904
+ const after = integerParam(url.searchParams.get("after"));
2905
+ if (limit === "bad")
2906
+ return adminError2(400, "limit: expected an integer");
2907
+ if (after === "bad")
2908
+ return adminError2(400, "after: expected a sequence number");
2909
+ const order = url.searchParams.get("order");
2910
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2911
+ ...limit !== void 0 ? { limit } : {},
2912
+ ...after !== void 0 ? { after } : {},
2913
+ ...order === "newest" || order === "oldest" ? { order } : {}
2914
+ }), 200);
2915
+ },
2916
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2917
+ const scope = open(namespace);
2918
+ if (!scope.ok)
2919
+ return fromResult(scope, 200);
2920
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2921
+ },
2922
+ "POST /state/:collection": ({ namespace, params, body }) => {
2923
+ const scope = open(namespace);
2924
+ if (!scope.ok)
2925
+ return fromResult(scope, 201);
2926
+ if (!isRecord3(body) || !("value" in body)) {
2927
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2928
+ }
2929
+ const id = body.id;
2930
+ if (id !== void 0 && typeof id !== "string")
2931
+ return adminError2(400, "id must be a string");
2932
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2933
+ ...typeof id === "string" ? { id } : {},
2934
+ value: body.value
2935
+ });
2936
+ if (created.ok)
2937
+ wrote(namespace);
2938
+ return fromResult(created, 201);
2939
+ },
2940
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2941
+ const scope = open(namespace);
2942
+ if (!scope.ok)
2943
+ return fromResult(scope, 200);
2944
+ if (!isRecord3(body) || !("value" in body))
2945
+ return adminError2(400, 'expected {"value": <json>}');
2946
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2947
+ if (replaced.ok)
2948
+ wrote(namespace);
2949
+ return fromResult(replaced, 200);
2950
+ },
2951
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2952
+ const scope = open(namespace);
2953
+ if (!scope.ok)
2954
+ return fromResult(scope, 200);
2955
+ if (!isRecord3(body) || !("value" in body))
2956
+ return adminError2(400, 'expected {"value": <json>}');
2957
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2958
+ if (patched.ok)
2959
+ wrote(namespace);
2960
+ return fromResult(patched, 200);
2961
+ },
2962
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2963
+ const scope = open(namespace);
2964
+ if (!scope.ok)
2965
+ return fromResult(scope, 200);
2966
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2967
+ if (removed.ok)
2968
+ wrote(namespace);
2969
+ return fromResult(removed, 200);
2970
+ }
2971
+ };
2972
+ };
2973
+
1608
2974
  // ../core/dist/version.js
1609
- var PACKAGE_VERSION = true ? "1.3.0" : UNRELEASED_VERSION;
2975
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1610
2976
 
1611
2977
  // ../core/dist/webhooks.js
1612
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1613
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1614
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2978
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2979
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2980
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1615
2981
  var parseEndpoint = (value) => {
1616
- if (!isRecord3(value) || typeof value.url !== "string")
2982
+ if (!isRecord4(value) || typeof value.url !== "string")
1617
2983
  return "each endpoint needs a url";
1618
2984
  try {
1619
2985
  new URL(value.url);
@@ -1630,18 +2996,18 @@ var parseEndpoint = (value) => {
1630
2996
  const events = value.events ?? value.enabledEvents;
1631
2997
  if (Array.isArray(events))
1632
2998
  endpoint.events = events.map(String);
1633
- if (isRecord3(value.tags)) {
2999
+ if (isRecord4(value.tags)) {
1634
3000
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1635
3001
  }
1636
3002
  if (typeof value.account === "string")
1637
3003
  endpoint.tags = { ...endpoint.tags, account: value.account };
1638
- if (isRecord3(value.headers)) {
3004
+ if (isRecord4(value.headers)) {
1639
3005
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1640
3006
  }
1641
3007
  return endpoint;
1642
3008
  };
1643
3009
  var webhookAdminRoutes = (hub) => ({
1644
- "GET /webhooks": ({ url, namespace }) => json2(200, {
3010
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
1645
3011
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1646
3012
  const type = url.searchParams.get("type");
1647
3013
  return type === null || d.type === type;
@@ -1649,51 +3015,51 @@ var webhookAdminRoutes = (hub) => ({
1649
3015
  }),
1650
3016
  "GET /webhooks/events": ({ url, namespace }) => {
1651
3017
  const type = url.searchParams.get("type");
1652
- return json2(200, {
3018
+ return json4(200, {
1653
3019
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1654
3020
  });
1655
3021
  },
1656
3022
  "POST /webhooks/:id/replay": async ({ params }) => {
1657
3023
  const replayed = await hub.replay(params.id);
1658
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
3024
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1659
3025
  },
1660
3026
  "POST /webhooks/flush": async () => {
1661
3027
  await hub.flush();
1662
- return json2(200, { status: "ok" });
3028
+ return json4(200, { status: "ok" });
1663
3029
  },
1664
3030
  "POST /webhooks/faults": ({ body, namespace }) => {
1665
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1666
- return adminError2(400, "mode must be duplicate, reorder or drop");
3031
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3032
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1667
3033
  }
1668
3034
  const fault = { mode: body.mode };
1669
3035
  if (typeof body.count === "number")
1670
3036
  fault.count = body.count;
1671
3037
  hub.fault(namespace, fault);
1672
- return json2(201, { namespace, ...fault });
3038
+ return json4(201, { namespace, ...fault });
1673
3039
  },
1674
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
3040
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
1675
3041
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1676
3042
  ...rest,
1677
3043
  secret: secret ? "(set)" : null
1678
3044
  }))
1679
3045
  }),
1680
3046
  "PUT /webhook-endpoints": ({ body, namespace }) => {
1681
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
3047
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
1682
3048
  if (!Array.isArray(list))
1683
- return adminError2(400, "expected [{url, secret?, events?}]");
3049
+ return adminError3(400, "expected [{url, secret?, events?}]");
1684
3050
  const parsed = [];
1685
3051
  for (const each of list) {
1686
3052
  const endpoint = parseEndpoint(each);
1687
3053
  if (typeof endpoint === "string")
1688
- return adminError2(400, endpoint);
3054
+ return adminError3(400, endpoint);
1689
3055
  parsed.push(endpoint);
1690
3056
  }
1691
3057
  const set = hub.setEndpoints(namespace, parsed);
1692
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3058
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1693
3059
  },
1694
3060
  "DELETE /webhook-endpoints": ({ namespace }) => {
1695
3061
  hub.setEndpoints(namespace, []);
1696
- return json2(200, { status: "ok" });
3062
+ return json4(200, { status: "ok" });
1697
3063
  }
1698
3064
  });
1699
3065
  var parsePayload = (message) => {
@@ -1758,6 +3124,7 @@ var operationMatcher = (document2) => {
1758
3124
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1759
3125
  };
1760
3126
  var createRuntime = (options) => {
3127
+ assertAdminUi(options.adminUi);
1761
3128
  const sqlite = bootSqlite(options.sqlite);
1762
3129
  const clock = options.clock ?? createClock();
1763
3130
  const rng = createRng(options.seed ?? 0);
@@ -1964,6 +3331,19 @@ var createRuntime = (options) => {
1964
3331
  else
1965
3332
  timeline(name);
1966
3333
  };
3334
+ const declarationsFor = (namespace) => {
3335
+ const declared = options.state;
3336
+ if (!declared)
3337
+ return [];
3338
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3339
+ };
3340
+ const stateScope = (namespace) => ({
3341
+ sqlite,
3342
+ namespace,
3343
+ storageNamespace: storageNamespace(namespace),
3344
+ root: instance(namespace),
3345
+ declarations: declarationsFor(namespace)
3346
+ });
1967
3347
  const runtime = {
1968
3348
  name: options.name,
1969
3349
  sqlite,
@@ -2002,6 +3382,7 @@ var createRuntime = (options) => {
2002
3382
  branch,
2003
3383
  checkout,
2004
3384
  timeline,
3385
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
2005
3386
  fetch: async (incoming) => {
2006
3387
  let request = incoming;
2007
3388
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2195,11 +3576,20 @@ var createRuntime = (options) => {
2195
3576
  ...credentialRoutes(credentials),
2196
3577
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2197
3578
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2198
- ...options.admin?.(runtime) ?? {}
3579
+ ...options.admin?.(runtime) ?? {},
3580
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3581
+ // beside these; it does not replace `/state` or `/ui`.
3582
+ ...stateAdminRoutes({
3583
+ open: stateScope,
3584
+ afterWrite: (namespace) => {
3585
+ checkpoint(namespace, "main");
3586
+ }
3587
+ }),
3588
+ ...adminUiRoutes(options.name, options.adminUi)
2199
3589
  },
2200
3590
  adminKey: options.adminKey
2201
3591
  });
2202
- return runtime;
3592
+ return defineMock(runtime);
2203
3593
  };
2204
3594
  var mutableResponse = (response) => {
2205
3595
  try {
@@ -2413,45 +3803,102 @@ var PLANE_PRESETS = {
2413
3803
  rules: [{ pathPrefix: API, method: "GET", effect: "pagination_repeated_cursor" }]
2414
3804
  }
2415
3805
  };
2416
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2417
- var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2418
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3806
+ var PLANE_STATE = [
3807
+ {
3808
+ name: "projects",
3809
+ label: "Projects",
3810
+ description: "Projects pinned in settings or created through the API."
3811
+ },
3812
+ {
3813
+ name: "states",
3814
+ label: "States",
3815
+ description: "Workflow states, grouped the way Plane groups them."
3816
+ },
3817
+ { name: "labels", label: "Labels" },
3818
+ {
3819
+ name: "work_items",
3820
+ label: "Work items",
3821
+ description: "Issues. The Move panel changes a state by id or by name."
3822
+ },
3823
+ { name: "comments", label: "Comments" },
3824
+ { name: "links", label: "Links" },
3825
+ {
3826
+ name: "settings",
3827
+ label: "Settings",
3828
+ description: "API keys, the rate limit, and pinned projects."
3829
+ },
3830
+ { name: "rate_limits", label: "Rate limits" }
3831
+ ];
3832
+ var MOVE_PANEL_HTML = `<form class="stack">
3833
+ <label class="field">Work item id
3834
+ <input name="id" required autocomplete="off" spellcheck="false">
3835
+ </label>
3836
+ <label class="field">State name or id
3837
+ <input name="state" required placeholder="Done" autocomplete="off">
3838
+ </label>
3839
+ <div class="row-actions">
3840
+ <button class="btn-primary" type="submit">Move</button>
3841
+ </div>
3842
+ <pre data-result hidden></pre>
3843
+ </form>`;
3844
+ var MOVE_PANEL_SCRIPT = `
3845
+ const form = root.querySelector("form")
3846
+ const out = root.querySelector("[data-result]")
3847
+ form.addEventListener("submit", (event) => {
3848
+ event.preventDefault()
3849
+ const data = new FormData(form)
3850
+ const id = String(data.get("id") || "").trim()
3851
+ const stateName = String(data.get("state") || "").trim()
3852
+ api.send("POST", "/work-items/" + encodeURIComponent(id) + "/state", { state: stateName })
3853
+ .then((item) => {
3854
+ out.hidden = false
3855
+ out.textContent = JSON.stringify(item, null, 2)
3856
+ })
3857
+ .catch((error) => {
3858
+ out.hidden = false
3859
+ out.textContent = error instanceof Error ? error.message : String(error)
3860
+ })
3861
+ })
3862
+ `.trim();
3863
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3864
+ var adminError4 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
3865
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2419
3866
  var adminRoutes = (runtime) => ({
2420
- "GET /work-items": ({ namespace }) => json3(200, { work_items: runtime.instance(namespace).workItems() }),
3867
+ "GET /work-items": ({ namespace }) => json5(200, { work_items: runtime.instance(namespace).workItems() }),
2421
3868
  "POST /work-items/:id/state": ({ params, body, namespace }) => {
2422
- if (!isRecord4(body) || typeof body.state !== "string") {
2423
- return adminError3(400, 'expected {"state": "<state id or name, e.g. Done>"}');
3869
+ if (!isRecord5(body) || typeof body.state !== "string") {
3870
+ return adminError4(400, 'expected {"state": "<state id or name, e.g. Done>"}');
2424
3871
  }
2425
3872
  const item = runtime.instance(namespace).moveToState(params.id, body.state);
2426
- return item ? json3(200, item) : adminError3(404, `no work item ${params.id} or state ${body.state}`);
3873
+ return item ? json5(200, item) : adminError4(404, `no work item ${params.id} or state ${body.state}`);
2427
3874
  },
2428
3875
  "POST /projects": ({ body, namespace }) => {
2429
- if (!isRecord4(body) || typeof body.workspace !== "string" || typeof body.project !== "string") {
2430
- return adminError3(400, 'expected {"workspace": "<slug>", "project": "<uuid>"}');
3876
+ if (!isRecord5(body) || typeof body.workspace !== "string" || typeof body.project !== "string") {
3877
+ return adminError4(400, 'expected {"workspace": "<slug>", "project": "<uuid>"}');
2431
3878
  }
2432
3879
  const api = runtime.instance(namespace);
2433
3880
  const project = api.ensureProject(body.workspace, body.project);
2434
- return project ? json3(200, { project, states: api.statesOf(project.id), labels: api.labelsOf(project.id) }) : adminError3(409, "project is not in settings.projects");
3881
+ return project ? json5(200, { project, states: api.statesOf(project.id), labels: api.labelsOf(project.id) }) : adminError4(409, "project is not in settings.projects");
2435
3882
  },
2436
- "GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
3883
+ "GET /settings": ({ namespace }) => json5(200, runtime.instance(namespace).state.current()),
2437
3884
  "PUT /settings": ({ body, namespace }) => {
2438
- if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
3885
+ if (!isRecord5(body)) return adminError4(400, "expected a JSON object");
2439
3886
  const patch = {};
2440
3887
  if (body.apiKeys !== void 0) {
2441
- if (!Array.isArray(body.apiKeys)) return adminError3(400, "apiKeys: string[]");
3888
+ if (!Array.isArray(body.apiKeys)) return adminError4(400, "apiKeys: string[]");
2442
3889
  patch.apiKeys = body.apiKeys.map(String);
2443
3890
  }
2444
3891
  if (body.rateLimitPerMinute !== void 0) {
2445
3892
  if (body.rateLimitPerMinute !== null && typeof body.rateLimitPerMinute !== "number") {
2446
- return adminError3(400, "rateLimitPerMinute: number | null");
3893
+ return adminError4(400, "rateLimitPerMinute: number | null");
2447
3894
  }
2448
3895
  patch.rateLimitPerMinute = body.rateLimitPerMinute;
2449
3896
  }
2450
3897
  if (body.projects !== void 0) {
2451
- if (!Array.isArray(body.projects)) return adminError3(400, 'projects: ["<slug>/<uuid>"]');
3898
+ if (!Array.isArray(body.projects)) return adminError4(400, 'projects: ["<slug>/<uuid>"]');
2452
3899
  patch.projects = body.projects.map(String);
2453
3900
  }
2454
- return json3(200, runtime.instance(namespace).state.update(patch));
3901
+ return json5(200, runtime.instance(namespace).state.update(patch));
2455
3902
  }
2456
3903
  });
2457
3904
  var createRuntime2 = (options = {}) => createRuntime({
@@ -2464,6 +3911,18 @@ var createRuntime2 = (options = {}) => createRuntime({
2464
3911
  ...options.onLog ? { onLog: options.onLog } : {},
2465
3912
  credential: apiKeyCredential,
2466
3913
  presets: PLANE_PRESETS,
3914
+ state: PLANE_STATE,
3915
+ adminUi: {
3916
+ panels: [
3917
+ {
3918
+ id: "move-work-item",
3919
+ title: "Move a work item",
3920
+ description: "Uses Plane's admin route, which resolves a state by id or by name.",
3921
+ html: MOVE_PANEL_HTML,
3922
+ script: MOVE_PANEL_SCRIPT
3923
+ }
3924
+ ]
3925
+ },
2467
3926
  create: ({ sqlite, namespace, clock }) => new PlaneAPI({
2468
3927
  sqlite,
2469
3928
  namespace,
@@ -2880,4 +4339,4 @@ export {
2880
4339
  apiKeyCredential,
2881
4340
  PlaneAPI
2882
4341
  };
2883
- //# sourceMappingURL=chunk-Z2PXMJXO.js.map
4342
+ //# sourceMappingURL=chunk-CCLSLHDJ.js.map