@crvouga/mockingbird-service-aha 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;
@@ -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 fail = (message) => errors.push({ path, message });
697
+ const fail2 = (message) => errors.push({ path, message });
696
698
  const actual = jsonTypeOf(value);
697
699
  if (actual === "undefined") {
698
- fail("value is undefined");
700
+ fail2("value is undefined");
699
701
  return errors;
700
702
  }
701
703
  const types = schemaTypes(s);
702
704
  if (types.length > 0) {
703
705
  const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
704
706
  if (!ok) {
705
- fail(`expected type ${types.join("|")}, got ${actual}`);
707
+ fail2(`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
- fail("value not in enum");
712
+ fail2("value not in enum");
711
713
  }
712
714
  if (s.const !== void 0 && !deepEqual(s.const, value))
713
- fail("value does not equal const");
715
+ fail2("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
- fail(`length ${length} < minLength ${s.minLength}`);
719
+ fail2(`length ${length} < minLength ${s.minLength}`);
718
720
  if (s.maxLength !== void 0 && length > s.maxLength)
719
- fail(`length ${length} > maxLength ${s.maxLength}`);
721
+ fail2(`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
- fail(`does not match pattern ${s.pattern}`);
725
+ fail2(`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
- fail(`does not match format ${s.format}`);
732
+ fail2(`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
- fail(`${value} < minimum ${s.minimum}`);
737
+ fail2(`${value} < minimum ${s.minimum}`);
736
738
  if (s.maximum !== void 0 && value > s.maximum)
737
- fail(`${value} > maximum ${s.maximum}`);
739
+ fail2(`${value} > maximum ${s.maximum}`);
738
740
  if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
739
- fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
741
+ fail2(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
740
742
  if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
741
- fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
743
+ fail2(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
742
744
  if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
743
- fail(`${value} is not a multiple of ${s.multipleOf}`);
745
+ fail2(`${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
- fail(`${value.length} items < minItems ${s.minItems}`);
750
+ fail2(`${value.length} items < minItems ${s.minItems}`);
749
751
  if (s.maxItems !== void 0 && value.length > s.maxItems)
750
- fail(`${value.length} items > maxItems ${s.maxItems}`);
752
+ fail2(`${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
- fail("items are not unique");
754
+ fail2("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(record2);
762
764
  for (const name of s.required ?? [])
763
765
  if (!(name in record2))
764
- fail(`missing required property ${name}`);
766
+ fail2(`missing required property ${name}`);
765
767
  if (s.minProperties !== void 0 && keys.length < s.minProperties)
766
- fail(`${keys.length} properties < minProperties ${s.minProperties}`);
768
+ fail2(`${keys.length} properties < minProperties ${s.minProperties}`);
767
769
  if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
768
- fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
770
+ fail2(`${keys.length} properties > maxProperties ${s.maxProperties}`);
769
771
  for (const key2 of keys) {
770
772
  const property = s.properties?.[key2];
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
- fail(`unexpected property ${key2}`);
778
+ fail2(`unexpected property ${key2}`);
777
779
  else if (typeof s.additionalProperties === "object") {
778
780
  errors.push(...validateValue(document2, s.additionalProperties, record2[key2], [...path, key2]));
779
781
  }
780
782
  if (s.propertyNames) {
781
783
  const nameErrors = validateValue(document2, s.propertyNames, key2, [...path, key2]);
782
784
  if (nameErrors.length > 0)
783
- fail(`property name ${key2} is invalid: ${nameErrors[0]?.message}`);
785
+ fail2(`property name ${key2} 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
- fail("matches no anyOf branch");
793
+ fail2("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
- fail(`matches ${matches2} oneOf branches, expected exactly 1`);
797
+ fail2(`matches ${matches2} oneOf branches, expected exactly 1`);
796
798
  }
797
799
  if (s.not && validateValue(document2, s.not, value).length === 0)
798
- fail("matches forbidden `not` schema");
800
+ fail2("matches forbidden `not` schema");
799
801
  return errors;
800
802
  };
801
803
 
@@ -1387,6 +1389,936 @@ var clearNamespace = (sqlite, namespace) => {
1387
1389
  });
1388
1390
  };
1389
1391
 
1392
+ // ../core/dist/surface.js
1393
+ var defineMock = (runtime) => runtime;
1394
+ var STANDARD_ADMIN_ROUTES = [
1395
+ "GET /",
1396
+ "POST /reset",
1397
+ "GET /namespaces",
1398
+ "GET /clock",
1399
+ "POST /clock",
1400
+ "GET /faults",
1401
+ "POST /faults",
1402
+ "DELETE /faults",
1403
+ "POST /snapshots",
1404
+ "POST /snapshots/:id/restore",
1405
+ "DELETE /snapshots/:id",
1406
+ "GET /timeline",
1407
+ "POST /checkpoints",
1408
+ "POST /branches/:name",
1409
+ "POST /branches/:name/checkout",
1410
+ "GET /requests",
1411
+ "DELETE /requests",
1412
+ "GET /metrics",
1413
+ "DELETE /metrics",
1414
+ "GET /credentials",
1415
+ "PUT /credentials",
1416
+ "DELETE /credentials",
1417
+ "GET /state",
1418
+ "GET /state/:collection",
1419
+ "GET /state/:collection/:id",
1420
+ "POST /state/:collection",
1421
+ "PUT /state/:collection/:id",
1422
+ "PATCH /state/:collection/:id",
1423
+ "DELETE /state/:collection/:id",
1424
+ "GET /ui",
1425
+ "GET /ui/",
1426
+ "GET /ui/manifest"
1427
+ ];
1428
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1429
+ var assertAdminUi = (ui) => {
1430
+ if (!ui?.panels)
1431
+ return;
1432
+ const seen = /* @__PURE__ */ new Set();
1433
+ for (const panel of ui.panels) {
1434
+ if (!PANEL_ID.test(panel.id)) {
1435
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1436
+ }
1437
+ if (seen.has(panel.id))
1438
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1439
+ seen.add(panel.id);
1440
+ if (panel.title.trim() === "")
1441
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1442
+ }
1443
+ };
1444
+
1445
+ // ../core/dist/admin-ui.js
1446
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1447
+ switch (char) {
1448
+ case "&":
1449
+ return "&amp;";
1450
+ case "<":
1451
+ return "&lt;";
1452
+ case ">":
1453
+ return "&gt;";
1454
+ case '"':
1455
+ return "&quot;";
1456
+ default:
1457
+ return "&#39;";
1458
+ }
1459
+ });
1460
+ var renderAdminDocument = (service) => {
1461
+ const name = escapeHtml(service);
1462
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1463
+ return `<!DOCTYPE html>
1464
+ <html lang="en">
1465
+ <head>
1466
+ <meta charset="utf-8">
1467
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1468
+ <meta name="color-scheme" content="light dark">
1469
+ <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">
1470
+ <title>${name} admin</title>
1471
+ <style>
1472
+ :root {
1473
+ color-scheme: light;
1474
+ --bg: #f6f5f2;
1475
+ --bg-elev: #ffffff;
1476
+ --bg-muted: #eeece6;
1477
+ --bg-inset: #f3f1eb;
1478
+ --line: #e2dfd6;
1479
+ --line-strong: #d0ccc1;
1480
+ --ink: #1c1915;
1481
+ --muted: #5e584f;
1482
+ --faint: #8a8378;
1483
+ --accent: #3d4f3a;
1484
+ --accent-ink: #f7f6f2;
1485
+ --accent-soft: #e5ece2;
1486
+ --ok: #1f7a45;
1487
+ --ok-soft: #e5f4eb;
1488
+ --warn: #9a6700;
1489
+ --warn-soft: #fbf3df;
1490
+ --err: #a33b32;
1491
+ --err-soft: #fdecea;
1492
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1493
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1494
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1495
+ --radius: 14px;
1496
+ --header: 60px;
1497
+ --nav: 220px;
1498
+ }
1499
+ :root[data-theme="dark"] {
1500
+ color-scheme: dark;
1501
+ --bg: #141311;
1502
+ --bg-elev: #1e1c19;
1503
+ --bg-muted: #26231f;
1504
+ --bg-inset: #181715;
1505
+ --line: #34302b;
1506
+ --line-strong: #4a453d;
1507
+ --ink: #f4f1ea;
1508
+ --muted: #c4bdb1;
1509
+ --faint: #8f877c;
1510
+ --accent: #c5d5b8;
1511
+ --accent-ink: #1a2118;
1512
+ --accent-soft: #2a3328;
1513
+ --ok: #8fd6a8;
1514
+ --ok-soft: #1a2e22;
1515
+ --warn: #f0cc78;
1516
+ --warn-soft: #332911;
1517
+ --err: #f0a8a2;
1518
+ --err-soft: #3a201e;
1519
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1520
+ }
1521
+ @media (prefers-color-scheme: dark) {
1522
+ :root:not([data-theme="light"]) {
1523
+ color-scheme: dark;
1524
+ --bg: #141311;
1525
+ --bg-elev: #1e1c19;
1526
+ --bg-muted: #26231f;
1527
+ --bg-inset: #181715;
1528
+ --line: #34302b;
1529
+ --line-strong: #4a453d;
1530
+ --ink: #f4f1ea;
1531
+ --muted: #c4bdb1;
1532
+ --faint: #8f877c;
1533
+ --accent: #c5d5b8;
1534
+ --accent-ink: #1a2118;
1535
+ --accent-soft: #2a3328;
1536
+ --ok: #8fd6a8;
1537
+ --ok-soft: #1a2e22;
1538
+ --warn: #f0cc78;
1539
+ --warn-soft: #332911;
1540
+ --err: #f0a8a2;
1541
+ --err-soft: #3a201e;
1542
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1543
+ }
1544
+ }
1545
+ * { box-sizing: border-box; }
1546
+ html, body { margin: 0; height: 100%; }
1547
+ body {
1548
+ font-family: var(--sans);
1549
+ background: var(--bg);
1550
+ color: var(--ink);
1551
+ line-height: 1.45;
1552
+ padding-left: env(safe-area-inset-left);
1553
+ padding-right: env(safe-area-inset-right);
1554
+ -webkit-text-size-adjust: 100%;
1555
+ }
1556
+ button, input, select, textarea { font: inherit; color: inherit; }
1557
+ button { cursor: pointer; }
1558
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1559
+ @media (prefers-reduced-motion: reduce) {
1560
+ * { scroll-behavior: auto !important; transition: none !important; }
1561
+ }
1562
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1563
+ header.top {
1564
+ position: sticky; top: 0; z-index: 5;
1565
+ display: flex; align-items: center; gap: 12px;
1566
+ min-height: var(--header); padding: 10px 16px;
1567
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1568
+ border-bottom: 1px solid var(--line);
1569
+ backdrop-filter: blur(10px);
1570
+ }
1571
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1572
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1573
+ .brand span { color: var(--faint); font-size: 12px; }
1574
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1575
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1576
+ label.field input, label.field select, .controls input[type="password"] {
1577
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1578
+ padding: 7px 8px; min-height: 36px;
1579
+ }
1580
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1581
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1582
+ background: var(--bg-elev);
1583
+ }
1584
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1585
+ .btn-quiet { background: transparent; }
1586
+ .btn-danger { color: var(--err); }
1587
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1588
+ record or the full nav row would widen the page past the viewport. */
1589
+ .layout {
1590
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1591
+ flex: 1; min-height: 0; min-width: 0;
1592
+ }
1593
+ nav.side {
1594
+ border-right: 1px solid var(--line); padding: 12px;
1595
+ display: flex; flex-direction: column; gap: 4px;
1596
+ background: var(--bg-elev);
1597
+ }
1598
+ nav.side button {
1599
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1600
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1601
+ }
1602
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1603
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1604
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1605
+ .lede { margin: 0 0 16px; color: var(--muted); }
1606
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1607
+ .card {
1608
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1609
+ padding: 14px 16px; box-shadow: var(--shadow);
1610
+ }
1611
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1612
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1613
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1614
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1615
+ .collection {
1616
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1617
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1618
+ }
1619
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1620
+ .collection small { display: block; color: var(--faint); }
1621
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1622
+ .chip {
1623
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1624
+ border-radius: 999px; padding: 4px 8px;
1625
+ }
1626
+ .chip i { color: var(--faint); font-style: normal; }
1627
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1628
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1629
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1630
+ tr.clickable { cursor: pointer; }
1631
+ tr.clickable:hover { background: var(--bg-muted); }
1632
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1633
+ pre {
1634
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1635
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1636
+ }
1637
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1638
+ .banner {
1639
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1640
+ background: var(--err-soft); color: var(--err);
1641
+ }
1642
+ .banner.show { display: block; }
1643
+ .empty { color: var(--muted); padding: 24px 8px; }
1644
+ dialog {
1645
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1646
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1647
+ }
1648
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1649
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1650
+ textarea {
1651
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1652
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1653
+ font-family: var(--mono); font-size: 12px;
1654
+ }
1655
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1656
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1657
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1658
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1659
+ .status-2 { color: var(--ok); }
1660
+ .status-4, .status-5, .status-0 { color: var(--err); }
1661
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1662
+ .route {
1663
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1664
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1665
+ }
1666
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1667
+ @media (max-width: 800px) {
1668
+ header.top {
1669
+ align-items: stretch; flex-direction: column;
1670
+ padding-top: max(10px, env(safe-area-inset-top));
1671
+ }
1672
+ input, select, textarea { font-size: 16px; }
1673
+ .controls { width: 100%; }
1674
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1675
+ .layout { grid-template-columns: minmax(0, 1fr); }
1676
+ nav.side {
1677
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1678
+ border-right: 0; border-bottom: 1px solid var(--line);
1679
+ padding: 8px;
1680
+ }
1681
+ nav.side button { white-space: nowrap; flex: none; }
1682
+ .split { grid-template-columns: minmax(0, 1fr); }
1683
+ main { padding: 14px; }
1684
+ table, thead, tbody, tr, th, td { display: block; }
1685
+ thead { display: none; }
1686
+ tr {
1687
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1688
+ background: var(--bg-elev); min-width: 0;
1689
+ }
1690
+ td {
1691
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1692
+ min-width: 0; overflow-wrap: anywhere;
1693
+ }
1694
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1695
+ .route { grid-template-columns: 72px 1fr; }
1696
+ .route button { grid-column: 1 / -1; }
1697
+ }
1698
+ </style>
1699
+ </head>
1700
+ <body>
1701
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1702
+ <header class="top">
1703
+ <div class="brand">
1704
+ <strong>${name}</strong>
1705
+ <span>Mockingbird admin</span>
1706
+ </div>
1707
+ <div class="controls">
1708
+ <label class="field">Namespace
1709
+ <select id="namespace" aria-label="Namespace"></select>
1710
+ </label>
1711
+ <label class="field">Admin key
1712
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1713
+ </label>
1714
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1715
+ <button class="btn" id="refresh" type="button">Refresh</button>
1716
+ </div>
1717
+ </header>
1718
+ <div class="layout">
1719
+ <nav class="side" id="nav" aria-label="Admin sections">
1720
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1721
+ <button type="button" data-view="state">State</button>
1722
+ <button type="button" data-view="clock">Clock</button>
1723
+ <button type="button" data-view="faults">Faults</button>
1724
+ <button type="button" data-view="journal">Journal</button>
1725
+ <button type="button" data-view="routes">Routes</button>
1726
+ </nav>
1727
+ <main id="views">
1728
+ <p class="banner" id="banner" role="alert"></p>
1729
+ <section class="view" id="view-overview">
1730
+ <h2>Overview</h2>
1731
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1732
+ <div class="grid" id="overview-cards"></div>
1733
+ <h3>Recent requests</h3>
1734
+ <div id="overview-requests"></div>
1735
+ </section>
1736
+ <section class="view" id="view-state" hidden>
1737
+ <h2>State</h2>
1738
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1739
+ <div class="split">
1740
+ <div id="collections"></div>
1741
+ <div>
1742
+ <div id="schema"></div>
1743
+ <div class="row-actions">
1744
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1745
+ </div>
1746
+ <div id="records"></div>
1747
+ </div>
1748
+ </div>
1749
+ </section>
1750
+ <section class="view" id="view-clock" hidden>
1751
+ <h2>Clock</h2>
1752
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1753
+ <div class="card" id="clock-readout"></div>
1754
+ <div class="row-actions">
1755
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1756
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1757
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1758
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1759
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1760
+ <button class="btn" id="freeze" type="button">Freeze</button>
1761
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1762
+ </div>
1763
+ <form id="clock-set" class="row-actions">
1764
+ <label class="field">Set instant
1765
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1766
+ </label>
1767
+ <button class="btn-primary" type="submit">Set</button>
1768
+ </form>
1769
+ </section>
1770
+ <section class="view" id="view-faults" hidden>
1771
+ <h2>Faults</h2>
1772
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1773
+ <form id="fault-form" class="card stack">
1774
+ <label class="field">Preset
1775
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1776
+ </label>
1777
+ <label class="field">Status
1778
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1779
+ </label>
1780
+ <label class="field">Path prefix
1781
+ <input id="fault-path" placeholder="/v1">
1782
+ </label>
1783
+ <label class="field">Method
1784
+ <input id="fault-method" placeholder="GET">
1785
+ </label>
1786
+ <div class="dialog-actions">
1787
+ <button class="btn-primary" type="submit">Add fault</button>
1788
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1789
+ </div>
1790
+ </form>
1791
+ <div id="fault-list"></div>
1792
+ </section>
1793
+ <section class="view" id="view-journal" hidden>
1794
+ <h2>Journal</h2>
1795
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1796
+ <div class="row-actions">
1797
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1798
+ </div>
1799
+ <div id="journal"></div>
1800
+ </section>
1801
+ <section class="view" id="view-routes" hidden>
1802
+ <h2>Routes</h2>
1803
+ <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>
1804
+ <div id="route-list"></div>
1805
+ <form id="route-form" class="card stack">
1806
+ <strong id="route-title">Select a route</strong>
1807
+ <label class="field">JSON body
1808
+ <textarea id="route-body" placeholder="{ }"></textarea>
1809
+ </label>
1810
+ <div class="dialog-actions">
1811
+ <button class="btn-primary" type="submit">Send</button>
1812
+ </div>
1813
+ <pre id="route-result">Response will show here.</pre>
1814
+ </form>
1815
+ </section>
1816
+ </main>
1817
+ </div>
1818
+ </div>
1819
+ <dialog id="editor">
1820
+ <form method="dialog" id="editor-form">
1821
+ <strong id="editor-title">Record</strong>
1822
+ <label class="field">Id
1823
+ <input id="editor-id" required>
1824
+ </label>
1825
+ <label class="field">JSON value
1826
+ <textarea id="editor-value"></textarea>
1827
+ </label>
1828
+ <div class="dialog-actions">
1829
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1830
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1831
+ <button class="btn-primary" type="submit" value="save">Save</button>
1832
+ </div>
1833
+ </form>
1834
+ </dialog>
1835
+ <script>
1836
+ (() => {
1837
+ const STANDARD = new Set(${standard})
1838
+ const state = {
1839
+ namespace: "default",
1840
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1841
+ view: "overview",
1842
+ collection: "",
1843
+ shape: null,
1844
+ route: null,
1845
+ editing: null
1846
+ }
1847
+ const $ = (id) => document.getElementById(id)
1848
+ const banner = $("banner")
1849
+ const keyInput = $("admin-key")
1850
+ keyInput.value = state.key
1851
+ const params = new URLSearchParams(location.search)
1852
+ if (params.get("key")) {
1853
+ state.key = params.get("key")
1854
+ keyInput.value = state.key
1855
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1856
+ params.delete("key")
1857
+ const next = params.toString()
1858
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1859
+ }
1860
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1861
+
1862
+ const showError = (error) => {
1863
+ banner.textContent = error instanceof Error ? error.message : String(error)
1864
+ banner.classList.add("show")
1865
+ }
1866
+ const clearError = () => banner.classList.remove("show")
1867
+
1868
+ async function originGet(path) {
1869
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1870
+ if (!response.ok) throw new Error(response.status + " " + path)
1871
+ return response.json()
1872
+ }
1873
+ async function api(method, path, body) {
1874
+ const headers = { accept: "application/json" }
1875
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1876
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1877
+ if (body !== undefined) headers["content-type"] = "application/json"
1878
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1879
+ method,
1880
+ headers,
1881
+ body: body === undefined ? undefined : JSON.stringify(body)
1882
+ })
1883
+ const text = await response.text()
1884
+ let data = null
1885
+ if (text) {
1886
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1887
+ }
1888
+ if (response.status === 401) {
1889
+ keyInput.focus()
1890
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1891
+ }
1892
+ if (!response.ok) {
1893
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1894
+ }
1895
+ return data
1896
+ }
1897
+ const panelApi = {
1898
+ get: (path) => api("GET", path),
1899
+ send: (method, path, body) => api(method, path, body),
1900
+ namespace: () => state.namespace
1901
+ }
1902
+
1903
+ function setTheme(theme) {
1904
+ if (theme) document.documentElement.dataset.theme = theme
1905
+ else delete document.documentElement.dataset.theme
1906
+ }
1907
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1908
+ if (storedTheme) setTheme(storedTheme)
1909
+ $("theme").addEventListener("click", () => {
1910
+ const current = document.documentElement.dataset.theme
1911
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1912
+ const next = dark ? "light" : "dark"
1913
+ localStorage.setItem("mockingbird-admin-theme", next)
1914
+ setTheme(next)
1915
+ })
1916
+
1917
+ function show(view) {
1918
+ state.view = view
1919
+ for (const button of document.querySelectorAll("#nav button")) {
1920
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1921
+ }
1922
+ for (const section of document.querySelectorAll("main .view")) {
1923
+ section.hidden = section.id !== "view-" + view
1924
+ }
1925
+ }
1926
+ document.getElementById("nav").addEventListener("click", (event) => {
1927
+ const button = event.target.closest("button[data-view]")
1928
+ if (!button) return
1929
+ show(button.dataset.view)
1930
+ refresh().catch(showError)
1931
+ })
1932
+
1933
+ function cards(items) {
1934
+ return '<div class="grid">' + items.map((item) =>
1935
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1936
+ ).join("") + "</div>"
1937
+ }
1938
+ function table(columns, rows) {
1939
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1940
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1941
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1942
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1943
+ ).join("") + "</tr>").join("")
1944
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1945
+ }
1946
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1947
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1948
+ }[char]))
1949
+ const preview = (value) => {
1950
+ const text = JSON.stringify(value)
1951
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1952
+ }
1953
+ const when = (epoch) => {
1954
+ const date = new Date(epoch)
1955
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1956
+ }
1957
+ const clockCard = (epoch) => {
1958
+ const date = new Date(epoch)
1959
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1960
+ const iso = date.toISOString()
1961
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1962
+ }
1963
+
1964
+ async function loadNamespaces() {
1965
+ const data = await api("GET", "/namespaces")
1966
+ const select = $("namespace")
1967
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1968
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1969
+ select.innerHTML = names.map((name) =>
1970
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1971
+ ).join("")
1972
+ select.value = state.namespace
1973
+ }
1974
+
1975
+ async function renderOverview() {
1976
+ const [health, shape, clock, journal] = await Promise.all([
1977
+ originGet("/health"),
1978
+ api("GET", "/state"),
1979
+ api("GET", "/clock"),
1980
+ api("GET", "/requests?limit=8")
1981
+ ])
1982
+ state.shape = shape
1983
+ $("overview-cards").innerHTML = cards([
1984
+ { k: "Service", v: esc(health.service || "${name}") },
1985
+ { k: "Status", v: esc(health.status || "ok") },
1986
+ { k: "Namespace", v: esc(state.namespace) },
1987
+ { k: "Collections", v: String(shape.collections.length) },
1988
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1989
+ { k: "Clock", v: clockCard(clock.now) }
1990
+ ])
1991
+ const requests = (journal && journal.requests) || []
1992
+ $("overview-requests").innerHTML = table(
1993
+ [
1994
+ { label: "Method", cell: (row) => esc(row.method) },
1995
+ { label: "Path", cell: (row) => esc(row.path) },
1996
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1997
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1998
+ ],
1999
+ requests
2000
+ )
2001
+ }
2002
+
2003
+ function schemaChips(collection) {
2004
+ if (!collection || collection.fields.length === 0) {
2005
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
2006
+ }
2007
+ return '<div class="chips">' + collection.fields.map((field) =>
2008
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
2009
+ ).join("") + "</div>"
2010
+ }
2011
+
2012
+ async function renderState() {
2013
+ const shape = await api("GET", "/state")
2014
+ state.shape = shape
2015
+ const host = $("collections")
2016
+ if (shape.collections.length === 0) {
2017
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
2018
+ $("schema").innerHTML = ""
2019
+ $("records").innerHTML = ""
2020
+ return
2021
+ }
2022
+ if (!shape.collections.some((item) => item.name === state.collection)) {
2023
+ state.collection = shape.collections[0].name
2024
+ }
2025
+ host.innerHTML = shape.collections.map((item) =>
2026
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
2027
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
2028
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
2029
+ ).join("")
2030
+ const selected = shape.collections.find((item) => item.name === state.collection)
2031
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
2032
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
2033
+ schemaChips(selected)
2034
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
2035
+ const rows = page.records.map((record) => ({
2036
+ ...record,
2037
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
2038
+ }))
2039
+ $("records").innerHTML = table(
2040
+ [
2041
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
2042
+ { label: "Seq", cell: (row) => esc(row.seq) },
2043
+ { label: "Value", cell: (row) => preview(row.value) }
2044
+ ],
2045
+ rows
2046
+ )
2047
+ }
2048
+
2049
+ async function renderClock() {
2050
+ const clock = await api("GET", "/clock")
2051
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
2052
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
2053
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
2054
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
2055
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
2056
+ }
2057
+
2058
+ async function renderFaults() {
2059
+ const [faults, presets] = await Promise.all([
2060
+ api("GET", "/faults"),
2061
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2062
+ ])
2063
+ const select = $("fault-preset")
2064
+ const current = select.value
2065
+ const list = presets.presets || []
2066
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
2067
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
2068
+ ).join("")
2069
+ select.value = current
2070
+ const rules = faults.faults || []
2071
+ $("fault-list").innerHTML = table(
2072
+ [
2073
+ { label: "Id", cell: (row) => esc(row.id) },
2074
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
2075
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
2076
+ ],
2077
+ rules
2078
+ )
2079
+ }
2080
+
2081
+ async function renderJournal() {
2082
+ const journal = await api("GET", "/requests?limit=100")
2083
+ $("journal").innerHTML = table(
2084
+ [
2085
+ { label: "When", cell: (row) => esc(row.at || "") },
2086
+ { label: "Method", cell: (row) => esc(row.method) },
2087
+ { label: "Path", cell: (row) => esc(row.path) },
2088
+ { label: "Status", cell: (row) => esc(row.status) },
2089
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2090
+ ],
2091
+ journal.requests || []
2092
+ )
2093
+ }
2094
+
2095
+ async function renderRoutes() {
2096
+ const data = await api("GET", "/")
2097
+ const routes = data.routes || []
2098
+ $("route-list").innerHTML = routes.map((route) => {
2099
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
2100
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
2101
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
2102
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
2103
+ }).join("")
2104
+ }
2105
+
2106
+ const renderers = {
2107
+ overview: renderOverview,
2108
+ state: renderState,
2109
+ clock: renderClock,
2110
+ faults: renderFaults,
2111
+ journal: renderJournal,
2112
+ routes: renderRoutes
2113
+ }
2114
+
2115
+ async function refresh() {
2116
+ clearError()
2117
+ if (state.view in renderers) await renderers[state.view]()
2118
+ }
2119
+
2120
+ $("namespace").addEventListener("change", () => {
2121
+ state.namespace = $("namespace").value
2122
+ refresh().catch(showError)
2123
+ })
2124
+ keyInput.addEventListener("change", () => {
2125
+ state.key = keyInput.value.trim()
2126
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
2127
+ refresh().catch(showError)
2128
+ })
2129
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
2130
+
2131
+ $("collections").addEventListener("click", (event) => {
2132
+ const button = event.target.closest("[data-collection]")
2133
+ if (!button) return
2134
+ state.collection = button.dataset.collection
2135
+ renderState().catch(showError)
2136
+ })
2137
+ $("records").addEventListener("click", (event) => {
2138
+ const row = event.target.closest("[data-id]")
2139
+ if (!row) return
2140
+ openEditor(row.dataset.id).catch(showError)
2141
+ })
2142
+
2143
+ const editor = $("editor")
2144
+ async function openEditor(id) {
2145
+ state.editing = id || null
2146
+ $("editor-title").textContent = id ? "Edit record" : "New record"
2147
+ $("editor-id").value = id || ""
2148
+ $("editor-id").readOnly = Boolean(id)
2149
+ $("editor-delete").hidden = !id
2150
+ if (id) {
2151
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2152
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
2153
+ } else {
2154
+ $("editor-value").value = "{\\n \\n}"
2155
+ }
2156
+ editor.showModal()
2157
+ }
2158
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
2159
+ $("editor-form").addEventListener("submit", (event) => {
2160
+ const submitter = event.submitter
2161
+ if (!submitter || submitter.value !== "save") return
2162
+ event.preventDefault()
2163
+ let value
2164
+ try { value = JSON.parse($("editor-value").value) }
2165
+ catch { showError(new Error("Value is not JSON")); return }
2166
+ const id = $("editor-id").value.trim()
2167
+ const path = "/state/" + encodeURIComponent(state.collection)
2168
+ const request = state.editing
2169
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
2170
+ : api("POST", path, { id: id || undefined, value })
2171
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
2172
+ })
2173
+ $("editor-delete").addEventListener("click", () => {
2174
+ const id = state.editing
2175
+ if (!id) return
2176
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2177
+ .then(() => { editor.close(); return renderState() })
2178
+ .catch(showError)
2179
+ })
2180
+
2181
+ document.querySelectorAll("[data-advance]").forEach((button) => {
2182
+ button.addEventListener("click", () => {
2183
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
2184
+ })
2185
+ })
2186
+ $("freeze").addEventListener("click", () => {
2187
+ const frozen = $("freeze").dataset.frozen === "1"
2188
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
2189
+ })
2190
+ $("clock-reset").addEventListener("click", () => {
2191
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
2192
+ })
2193
+ $("clock-set").addEventListener("submit", (event) => {
2194
+ event.preventDefault()
2195
+ const raw = $("clock-instant").value.trim()
2196
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
2197
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
2198
+ })
2199
+
2200
+ $("fault-form").addEventListener("submit", (event) => {
2201
+ event.preventDefault()
2202
+ const preset = $("fault-preset").value
2203
+ const body = preset
2204
+ ? { preset }
2205
+ : {
2206
+ status: Number($("fault-status").value),
2207
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
2208
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
2209
+ }
2210
+ if (!preset && !Number.isFinite(body.status)) {
2211
+ showError(new Error("Status must be a number, or choose a preset"))
2212
+ return
2213
+ }
2214
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
2215
+ })
2216
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
2217
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
2218
+
2219
+ $("route-list").addEventListener("click", (event) => {
2220
+ const button = event.target.closest("[data-route]")
2221
+ if (!button) return
2222
+ state.route = button.dataset.route
2223
+ $("route-title").textContent = state.route
2224
+ const method = state.route.split(" ")[0]
2225
+ $("route-body").disabled = method === "GET" || method === "DELETE"
2226
+ })
2227
+ $("route-form").addEventListener("submit", async (event) => {
2228
+ event.preventDefault()
2229
+ if (!state.route) return showError(new Error("Choose a route first"))
2230
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
2231
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
2232
+ let body
2233
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
2234
+ try { body = JSON.parse($("route-body").value) }
2235
+ catch { return showError(new Error("Body is not JSON")) }
2236
+ }
2237
+ try {
2238
+ const data = await api(method, concrete, body)
2239
+ $("route-result").textContent = JSON.stringify(data, null, 2)
2240
+ } catch (error) {
2241
+ showError(error)
2242
+ }
2243
+ })
2244
+
2245
+ function mountPanels(panels) {
2246
+ const nav = $("nav")
2247
+ const views = $("views")
2248
+ for (const panel of panels) {
2249
+ const button = document.createElement("button")
2250
+ button.type = "button"
2251
+ button.dataset.view = panel.id
2252
+ button.textContent = panel.title
2253
+ nav.append(button)
2254
+ const section = document.createElement("section")
2255
+ section.className = "view"
2256
+ section.id = "view-" + panel.id
2257
+ section.hidden = true
2258
+ const title = document.createElement("h2")
2259
+ title.textContent = panel.title
2260
+ const lede = document.createElement("p")
2261
+ lede.className = "lede"
2262
+ lede.textContent = panel.description || ""
2263
+ const body = document.createElement("div")
2264
+ body.className = "panel-body"
2265
+ body.id = "panel-" + panel.id
2266
+ body.innerHTML = panel.html || ""
2267
+ section.append(title, lede, body)
2268
+ views.append(section)
2269
+ if (panel.script) {
2270
+ try {
2271
+ const run = new Function("root", "api", panel.script)
2272
+ run(body, panelApi)
2273
+ } catch (error) {
2274
+ const note = document.createElement("p")
2275
+ note.className = "banner show"
2276
+ note.textContent = error instanceof Error ? error.message : String(error)
2277
+ body.append(note)
2278
+ }
2279
+ }
2280
+ }
2281
+ }
2282
+
2283
+ loadNamespaces()
2284
+ .then(() => api("GET", "/ui/manifest"))
2285
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2286
+ .catch(showError)
2287
+ })()
2288
+ </script>
2289
+ </body>
2290
+ </html>`;
2291
+ };
2292
+ var htmlResponse = (body) => new Response(body, {
2293
+ status: 200,
2294
+ headers: {
2295
+ "content-type": "text/html; charset=utf-8",
2296
+ "cache-control": "no-store"
2297
+ }
2298
+ });
2299
+ var json2 = (body) => new Response(JSON.stringify(body), {
2300
+ status: 200,
2301
+ headers: { "content-type": "application/json; charset=utf-8" }
2302
+ });
2303
+ var adminUiRoutes = (service, ui) => {
2304
+ const shell = () => renderAdminDocument(service);
2305
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2306
+ return {
2307
+ "GET /ui": () => htmlResponse(document2()),
2308
+ "GET /ui/": () => htmlResponse(document2()),
2309
+ "GET /ui/manifest": () => json2({
2310
+ service,
2311
+ panels: (ui?.panels ?? []).map((panel) => ({
2312
+ id: panel.id,
2313
+ title: panel.title,
2314
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2315
+ html: panel.html,
2316
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2317
+ }))
2318
+ })
2319
+ };
2320
+ };
2321
+
1390
2322
  // ../../openapi/metadata/dist/types.js
1391
2323
  var EXTENSION_KEYS = {
1392
2324
  operation: "x-mockingbird",
@@ -1634,8 +2566,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1634
2566
  });
1635
2567
  };
1636
2568
 
2569
+ // ../core/dist/state-view.js
2570
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2571
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2572
+ var SAMPLE = 25;
2573
+ var WALK_LIMIT = 1e4;
2574
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2575
+ var fail = (status, message) => ({ ok: false, status, message });
2576
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2577
+ var kindOf = (value) => {
2578
+ if (value === null)
2579
+ return "null";
2580
+ if (Array.isArray(value))
2581
+ return "array";
2582
+ switch (typeof value) {
2583
+ case "string":
2584
+ return "string";
2585
+ case "number":
2586
+ return Number.isFinite(value) ? "number" : "unknown";
2587
+ case "boolean":
2588
+ return "boolean";
2589
+ case "object":
2590
+ return "object";
2591
+ default:
2592
+ return "unknown";
2593
+ }
2594
+ };
2595
+ var humanize = (name) => {
2596
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2597
+ if (words === "")
2598
+ return name;
2599
+ return words.charAt(0).toUpperCase() + words.slice(1);
2600
+ };
2601
+ var jsonValue = (value) => {
2602
+ if (value === void 0)
2603
+ return fail(400, "value is required");
2604
+ try {
2605
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2606
+ } catch {
2607
+ return fail(400, "value must be JSON");
2608
+ }
2609
+ };
2610
+ var ctorName = (value) => {
2611
+ const ctor = value.constructor;
2612
+ return typeof ctor?.name === "string" ? ctor.name : "";
2613
+ };
2614
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2615
+ var discoverCollections = (root) => {
2616
+ const found = [];
2617
+ const seen = /* @__PURE__ */ new Set();
2618
+ const visit = (value, depth) => {
2619
+ if (found.length + seen.size > WALK_LIMIT)
2620
+ return;
2621
+ if (value === null || typeof value !== "object")
2622
+ return;
2623
+ if (seen.has(value))
2624
+ return;
2625
+ seen.add(value);
2626
+ if (value instanceof Collection) {
2627
+ found.push(value);
2628
+ return;
2629
+ }
2630
+ if (value instanceof Map) {
2631
+ for (const child of value.values())
2632
+ visit(child, depth + 1);
2633
+ return;
2634
+ }
2635
+ if (value instanceof Set) {
2636
+ for (const child of value.values())
2637
+ visit(child, depth + 1);
2638
+ return;
2639
+ }
2640
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2641
+ return;
2642
+ if (Array.isArray(value)) {
2643
+ const cap = Math.min(value.length, 32);
2644
+ for (let i = 0; i < cap; i++)
2645
+ visit(value[i], depth + 1);
2646
+ return;
2647
+ }
2648
+ let children;
2649
+ try {
2650
+ children = Object.values(value);
2651
+ } catch {
2652
+ return;
2653
+ }
2654
+ for (const child of children)
2655
+ visit(child, depth + 1);
2656
+ };
2657
+ visit(root, 0);
2658
+ return found;
2659
+ };
2660
+ var storedNames = (sqlite, namespace) => {
2661
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2662
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2663
+ return [...records, ...sequences].map((row) => row.name);
2664
+ };
2665
+ var blankAccum = (name) => ({
2666
+ name,
2667
+ kinds: /* @__PURE__ */ new Set(),
2668
+ present: 0,
2669
+ nested: /* @__PURE__ */ new Map()
2670
+ });
2671
+ var absorb = (accum, value) => {
2672
+ const kind = kindOf(value);
2673
+ accum.kinds.add(kind);
2674
+ accum.present++;
2675
+ if (!isRecord3(value))
2676
+ return;
2677
+ for (const [key2, child] of Object.entries(value)) {
2678
+ const nested = accum.nested.get(key2) ?? blankAccum(key2);
2679
+ absorb(nested, child);
2680
+ accum.nested.set(key2, nested);
2681
+ }
2682
+ };
2683
+ var finishField = (accum, samples) => {
2684
+ const kinds = [...accum.kinds];
2685
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2686
+ const field = {
2687
+ name: accum.name,
2688
+ kind,
2689
+ optional: accum.present < samples || kinds.includes("null")
2690
+ };
2691
+ if (accum.nested.size > 0) {
2692
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2693
+ }
2694
+ return field;
2695
+ };
2696
+ var inferFields = (records) => {
2697
+ if (records.length === 0)
2698
+ return [];
2699
+ const sample = records.slice(0, SAMPLE);
2700
+ const objects = sample.filter((record2) => isRecord3(record2.value));
2701
+ if (objects.length === 0) {
2702
+ const kinds = new Set(sample.map((record2) => kindOf(record2.value)));
2703
+ const list = [...kinds];
2704
+ return [
2705
+ {
2706
+ name: "(value)",
2707
+ kind: list.length === 1 ? list[0] : "unknown",
2708
+ optional: false
2709
+ }
2710
+ ];
2711
+ }
2712
+ const root = /* @__PURE__ */ new Map();
2713
+ for (const record2 of objects) {
2714
+ for (const [key2, value] of Object.entries(record2.value)) {
2715
+ const accum = root.get(key2) ?? blankAccum(key2);
2716
+ absorb(accum, value);
2717
+ root.set(key2, accum);
2718
+ }
2719
+ }
2720
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2721
+ };
2722
+ var mergeFields = (declared, inferred) => {
2723
+ const byName = /* @__PURE__ */ new Map();
2724
+ for (const field of inferred)
2725
+ byName.set(field.name, field);
2726
+ const ordered = [];
2727
+ const seen = /* @__PURE__ */ new Set();
2728
+ for (const field of declared ?? []) {
2729
+ const found = byName.get(field.name);
2730
+ seen.add(field.name);
2731
+ if (!found) {
2732
+ ordered.push({ ...field, optional: field.optional });
2733
+ continue;
2734
+ }
2735
+ ordered.push({
2736
+ ...found,
2737
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2738
+ optional: field.optional || found.optional,
2739
+ ...field.description !== void 0 ? { description: field.description } : {},
2740
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2741
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2742
+ });
2743
+ }
2744
+ for (const field of inferred) {
2745
+ if (!seen.has(field.name))
2746
+ ordered.push(field);
2747
+ }
2748
+ return ordered;
2749
+ };
2750
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2751
+ var readRecord = (collection, id) => {
2752
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2753
+ const row = rows.find((entry) => entry.id === id);
2754
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2755
+ };
2756
+ var inspectState = (scope) => {
2757
+ const declared = /* @__PURE__ */ new Map();
2758
+ for (const declaration of scope.declarations ?? []) {
2759
+ if (COLLECTION_NAME.test(declaration.name))
2760
+ declared.set(declaration.name, declaration);
2761
+ }
2762
+ const names = new Set(declared.keys());
2763
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2764
+ names.add(name);
2765
+ for (const collection of discoverCollections(scope.root)) {
2766
+ if (collection.namespace === scope.storageNamespace)
2767
+ names.add(collection.collectionName);
2768
+ }
2769
+ const collections = [];
2770
+ for (const name of names) {
2771
+ if (!COLLECTION_NAME.test(name))
2772
+ continue;
2773
+ const declaration = declared.get(name);
2774
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2775
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2776
+ const inferred = inferFields(records);
2777
+ const fields = mergeFields(declaration?.fields, inferred);
2778
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2779
+ collections.push({
2780
+ name,
2781
+ label: declaration?.label ?? humanize(name),
2782
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2783
+ count: collection.count(),
2784
+ source,
2785
+ fields,
2786
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2787
+ });
2788
+ }
2789
+ const order = /* @__PURE__ */ new Map();
2790
+ for (const [index, item] of (scope.declarations ?? []).entries())
2791
+ order.set(item.name, index);
2792
+ collections.sort((a, b) => {
2793
+ const left = order.get(a.name);
2794
+ const right = order.get(b.name);
2795
+ if (left !== void 0 && right !== void 0)
2796
+ return left - right;
2797
+ if (left !== void 0)
2798
+ return -1;
2799
+ if (right !== void 0)
2800
+ return 1;
2801
+ return a.name.localeCompare(b.name);
2802
+ });
2803
+ return {
2804
+ namespace: scope.namespace,
2805
+ storageNamespace: scope.storageNamespace,
2806
+ collections
2807
+ };
2808
+ };
2809
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2810
+ if (!COLLECTION_NAME.test(name))
2811
+ return fail(400, "collection name is not allowed");
2812
+ const limit = query.limit ?? 50;
2813
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2814
+ return fail(400, "limit must be an integer from 1 to 200");
2815
+ }
2816
+ const order = query.order ?? "newest";
2817
+ if (order !== "newest" && order !== "oldest")
2818
+ return fail(400, 'order must be "newest" or "oldest"');
2819
+ const collection = collectionOf(sqlite, storageNamespace, name);
2820
+ const rows = collection.list({ order }).filter((row) => {
2821
+ if (query.after === void 0)
2822
+ return true;
2823
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2824
+ });
2825
+ const slice = rows.slice(0, limit);
2826
+ const last = slice.at(-1);
2827
+ return {
2828
+ ok: true,
2829
+ value: {
2830
+ collection: name,
2831
+ count: collection.count(),
2832
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2833
+ next: rows.length > limit && last ? last.seq : null
2834
+ }
2835
+ };
2836
+ };
2837
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2838
+ var readStateRecord = (scope, name, id) => {
2839
+ if (!COLLECTION_NAME.test(name))
2840
+ return fail(400, "collection name is not allowed");
2841
+ if (!RECORD_ID.test(id))
2842
+ return fail(400, "record id is not allowed");
2843
+ const record2 = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2844
+ return record2 ? { ok: true, value: record2 } : fail(404, `no record ${id} in ${name}`);
2845
+ };
2846
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2847
+ var createStateRecord = (scope, name, input) => {
2848
+ if (!COLLECTION_NAME.test(name))
2849
+ return fail(400, "collection name is not allowed");
2850
+ const parsed = jsonValue(input.value);
2851
+ if (!parsed.ok)
2852
+ return parsed;
2853
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2854
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2855
+ const checked = requireId(id);
2856
+ if (!checked.ok)
2857
+ return checked;
2858
+ if (collection.has(checked.value))
2859
+ return fail(409, `record ${checked.value} already exists`);
2860
+ const stored = collection.insert(checked.value, parsed.value);
2861
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2862
+ };
2863
+ var replaceStateRecord = (scope, name, id, value) => {
2864
+ if (!COLLECTION_NAME.test(name))
2865
+ return fail(400, "collection name is not allowed");
2866
+ const checked = requireId(id);
2867
+ if (!checked.ok)
2868
+ return checked;
2869
+ const parsed = jsonValue(value);
2870
+ if (!parsed.ok)
2871
+ return parsed;
2872
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2873
+ if (!collection.has(checked.value))
2874
+ return fail(404, `no record ${checked.value} in ${name}`);
2875
+ const stored = collection.update(checked.value, parsed.value);
2876
+ if (!stored)
2877
+ return fail(404, `no record ${checked.value} in ${name}`);
2878
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2879
+ };
2880
+ var patchStateRecord = (scope, name, id, value) => {
2881
+ const current = readStateRecord(scope, name, id);
2882
+ if (!current.ok)
2883
+ return current;
2884
+ const parsed = jsonValue(value);
2885
+ if (!parsed.ok)
2886
+ return parsed;
2887
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2888
+ return replaceStateRecord(scope, name, id, next);
2889
+ };
2890
+ var deleteStateRecord = (scope, name, id) => {
2891
+ if (!COLLECTION_NAME.test(name))
2892
+ return fail(400, "collection name is not allowed");
2893
+ const checked = requireId(id);
2894
+ if (!checked.ok)
2895
+ return checked;
2896
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2897
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2898
+ };
2899
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2900
+ status,
2901
+ headers: { "content-type": "application/json; charset=utf-8" }
2902
+ });
2903
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2904
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2905
+ var integerParam = (value) => {
2906
+ if (value === null)
2907
+ return void 0;
2908
+ if (!/^-?\d+$/.test(value))
2909
+ return "bad";
2910
+ return Number(value);
2911
+ };
2912
+ var stateAdminRoutes = (routes) => {
2913
+ const open = (namespace) => {
2914
+ try {
2915
+ return { ok: true, value: routes.open(namespace) };
2916
+ } catch (error2) {
2917
+ return fail(400, error2 instanceof Error ? error2.message : String(error2));
2918
+ }
2919
+ };
2920
+ const wrote = (namespace) => {
2921
+ routes.afterWrite?.(namespace);
2922
+ };
2923
+ return {
2924
+ "GET /state": ({ namespace }) => {
2925
+ const scope = open(namespace);
2926
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2927
+ },
2928
+ "GET /state/:collection": ({ namespace, params, url }) => {
2929
+ const scope = open(namespace);
2930
+ if (!scope.ok)
2931
+ return fromResult(scope, 200);
2932
+ const limit = integerParam(url.searchParams.get("limit"));
2933
+ const after = integerParam(url.searchParams.get("after"));
2934
+ if (limit === "bad")
2935
+ return adminError2(400, "limit: expected an integer");
2936
+ if (after === "bad")
2937
+ return adminError2(400, "after: expected a sequence number");
2938
+ const order = url.searchParams.get("order");
2939
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2940
+ ...limit !== void 0 ? { limit } : {},
2941
+ ...after !== void 0 ? { after } : {},
2942
+ ...order === "newest" || order === "oldest" ? { order } : {}
2943
+ }), 200);
2944
+ },
2945
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2946
+ const scope = open(namespace);
2947
+ if (!scope.ok)
2948
+ return fromResult(scope, 200);
2949
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2950
+ },
2951
+ "POST /state/:collection": ({ namespace, params, body }) => {
2952
+ const scope = open(namespace);
2953
+ if (!scope.ok)
2954
+ return fromResult(scope, 201);
2955
+ if (!isRecord3(body) || !("value" in body)) {
2956
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2957
+ }
2958
+ const id = body.id;
2959
+ if (id !== void 0 && typeof id !== "string")
2960
+ return adminError2(400, "id must be a string");
2961
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2962
+ ...typeof id === "string" ? { id } : {},
2963
+ value: body.value
2964
+ });
2965
+ if (created.ok)
2966
+ wrote(namespace);
2967
+ return fromResult(created, 201);
2968
+ },
2969
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2970
+ const scope = open(namespace);
2971
+ if (!scope.ok)
2972
+ return fromResult(scope, 200);
2973
+ if (!isRecord3(body) || !("value" in body))
2974
+ return adminError2(400, 'expected {"value": <json>}');
2975
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2976
+ if (replaced.ok)
2977
+ wrote(namespace);
2978
+ return fromResult(replaced, 200);
2979
+ },
2980
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2981
+ const scope = open(namespace);
2982
+ if (!scope.ok)
2983
+ return fromResult(scope, 200);
2984
+ if (!isRecord3(body) || !("value" in body))
2985
+ return adminError2(400, 'expected {"value": <json>}');
2986
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2987
+ if (patched.ok)
2988
+ wrote(namespace);
2989
+ return fromResult(patched, 200);
2990
+ },
2991
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2992
+ const scope = open(namespace);
2993
+ if (!scope.ok)
2994
+ return fromResult(scope, 200);
2995
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2996
+ if (removed.ok)
2997
+ wrote(namespace);
2998
+ return fromResult(removed, 200);
2999
+ }
3000
+ };
3001
+ };
3002
+
1637
3003
  // ../core/dist/version.js
1638
- var PACKAGE_VERSION = true ? "1.2.0" : UNRELEASED_VERSION;
3004
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1639
3005
 
1640
3006
  // ../core/dist/signing.js
1641
3007
  var encoder = new TextEncoder();
@@ -1978,11 +3344,11 @@ var createWebhookHub = (options) => {
1978
3344
  };
1979
3345
  return hub;
1980
3346
  };
1981
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1982
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1983
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3347
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3348
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
3349
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1984
3350
  var parseEndpoint = (value) => {
1985
- if (!isRecord3(value) || typeof value.url !== "string")
3351
+ if (!isRecord4(value) || typeof value.url !== "string")
1986
3352
  return "each endpoint needs a url";
1987
3353
  try {
1988
3354
  new URL(value.url);
@@ -1999,18 +3365,18 @@ var parseEndpoint = (value) => {
1999
3365
  const events = value.events ?? value.enabledEvents;
2000
3366
  if (Array.isArray(events))
2001
3367
  endpoint.events = events.map(String);
2002
- if (isRecord3(value.tags)) {
3368
+ if (isRecord4(value.tags)) {
2003
3369
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
2004
3370
  }
2005
3371
  if (typeof value.account === "string")
2006
3372
  endpoint.tags = { ...endpoint.tags, account: value.account };
2007
- if (isRecord3(value.headers)) {
3373
+ if (isRecord4(value.headers)) {
2008
3374
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
2009
3375
  }
2010
3376
  return endpoint;
2011
3377
  };
2012
3378
  var webhookAdminRoutes = (hub) => ({
2013
- "GET /webhooks": ({ url, namespace }) => json2(200, {
3379
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
2014
3380
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
2015
3381
  const type = url.searchParams.get("type");
2016
3382
  return type === null || d.type === type;
@@ -2018,51 +3384,51 @@ var webhookAdminRoutes = (hub) => ({
2018
3384
  }),
2019
3385
  "GET /webhooks/events": ({ url, namespace }) => {
2020
3386
  const type = url.searchParams.get("type");
2021
- return json2(200, {
3387
+ return json4(200, {
2022
3388
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
2023
3389
  });
2024
3390
  },
2025
3391
  "POST /webhooks/:id/replay": async ({ params }) => {
2026
3392
  const replayed = await hub.replay(params.id);
2027
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
3393
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
2028
3394
  },
2029
3395
  "POST /webhooks/flush": async () => {
2030
3396
  await hub.flush();
2031
- return json2(200, { status: "ok" });
3397
+ return json4(200, { status: "ok" });
2032
3398
  },
2033
3399
  "POST /webhooks/faults": ({ body, namespace }) => {
2034
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2035
- return adminError2(400, "mode must be duplicate, reorder or drop");
3400
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3401
+ return adminError3(400, "mode must be duplicate, reorder or drop");
2036
3402
  }
2037
3403
  const fault = { mode: body.mode };
2038
3404
  if (typeof body.count === "number")
2039
3405
  fault.count = body.count;
2040
3406
  hub.fault(namespace, fault);
2041
- return json2(201, { namespace, ...fault });
3407
+ return json4(201, { namespace, ...fault });
2042
3408
  },
2043
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
3409
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
2044
3410
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
2045
3411
  ...rest,
2046
3412
  secret: secret ? "(set)" : null
2047
3413
  }))
2048
3414
  }),
2049
3415
  "PUT /webhook-endpoints": ({ body, namespace }) => {
2050
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
3416
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
2051
3417
  if (!Array.isArray(list))
2052
- return adminError2(400, "expected [{url, secret?, events?}]");
3418
+ return adminError3(400, "expected [{url, secret?, events?}]");
2053
3419
  const parsed = [];
2054
3420
  for (const each of list) {
2055
3421
  const endpoint = parseEndpoint(each);
2056
3422
  if (typeof endpoint === "string")
2057
- return adminError2(400, endpoint);
3423
+ return adminError3(400, endpoint);
2058
3424
  parsed.push(endpoint);
2059
3425
  }
2060
3426
  const set = hub.setEndpoints(namespace, parsed);
2061
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3427
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2062
3428
  },
2063
3429
  "DELETE /webhook-endpoints": ({ namespace }) => {
2064
3430
  hub.setEndpoints(namespace, []);
2065
- return json2(200, { status: "ok" });
3431
+ return json4(200, { status: "ok" });
2066
3432
  }
2067
3433
  });
2068
3434
  var parsePayload = (message) => {
@@ -2127,6 +3493,7 @@ var operationMatcher = (document2) => {
2127
3493
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
2128
3494
  };
2129
3495
  var createRuntime = (options) => {
3496
+ assertAdminUi(options.adminUi);
2130
3497
  const sqlite = bootSqlite(options.sqlite);
2131
3498
  const clock = options.clock ?? createClock();
2132
3499
  const rng = createRng(options.seed ?? 0);
@@ -2333,6 +3700,19 @@ var createRuntime = (options) => {
2333
3700
  else
2334
3701
  timeline(name);
2335
3702
  };
3703
+ const declarationsFor = (namespace) => {
3704
+ const declared = options.state;
3705
+ if (!declared)
3706
+ return [];
3707
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3708
+ };
3709
+ const stateScope = (namespace) => ({
3710
+ sqlite,
3711
+ namespace,
3712
+ storageNamespace: storageNamespace(namespace),
3713
+ root: instance(namespace),
3714
+ declarations: declarationsFor(namespace)
3715
+ });
2336
3716
  const runtime = {
2337
3717
  name: options.name,
2338
3718
  sqlite,
@@ -2371,6 +3751,7 @@ var createRuntime = (options) => {
2371
3751
  branch,
2372
3752
  checkout,
2373
3753
  timeline,
3754
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
2374
3755
  fetch: async (incoming) => {
2375
3756
  let request = incoming;
2376
3757
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2564,11 +3945,20 @@ var createRuntime = (options) => {
2564
3945
  ...credentialRoutes(credentials),
2565
3946
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2566
3947
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2567
- ...options.admin?.(runtime) ?? {}
3948
+ ...options.admin?.(runtime) ?? {},
3949
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3950
+ // beside these; it does not replace `/state` or `/ui`.
3951
+ ...stateAdminRoutes({
3952
+ open: stateScope,
3953
+ afterWrite: (namespace) => {
3954
+ checkpoint(namespace, "main");
3955
+ }
3956
+ }),
3957
+ ...adminUiRoutes(options.name, options.adminUi)
2568
3958
  },
2569
3959
  adminKey: options.adminKey
2570
3960
  });
2571
- return runtime;
3961
+ return defineMock(runtime);
2572
3962
  };
2573
3963
  var mutableResponse = (response) => {
2574
3964
  try {
@@ -2830,13 +4220,13 @@ var AHA_PRESETS = {
2830
4220
  webhook: { mode: "drop" }
2831
4221
  }
2832
4222
  };
2833
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2834
- var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2835
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4223
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4224
+ var adminError4 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
4225
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2836
4226
  var parseAutoSchedule = (value) => {
2837
4227
  if (value === null) return null;
2838
4228
  if (typeof value === "number" && value >= 0) return { afterMs: value };
2839
- if (!isRecord4(value) || typeof value.afterMs !== "number" || value.afterMs < 0) {
4229
+ if (!isRecord5(value) || typeof value.afterMs !== "number" || value.afterMs < 0) {
2840
4230
  return "autoSchedule must be {afterMs, leadMs?}, a number of ms, or null";
2841
4231
  }
2842
4232
  if (value.leadMs !== void 0 && typeof value.leadMs !== "number") return "leadMs: number";
@@ -2849,7 +4239,7 @@ var parseCredentials = (value) => {
2849
4239
  if (!Array.isArray(value)) return "credentials: [{apiKey, apiSecret?}]";
2850
4240
  const out = [];
2851
4241
  for (const each of value) {
2852
- if (!isRecord4(each) || typeof each.apiKey !== "string") return "each credential needs apiKey";
4242
+ if (!isRecord5(each) || typeof each.apiKey !== "string") return "each credential needs apiKey";
2853
4243
  out.push({
2854
4244
  apiKey: each.apiKey,
2855
4245
  ...typeof each.apiSecret === "string" ? { apiSecret: each.apiSecret } : {}
@@ -2865,10 +4255,10 @@ var visible = (settings) => ({
2865
4255
  }))
2866
4256
  });
2867
4257
  var adminRoutes = (runtime) => ({
2868
- "GET /orders": ({ namespace }) => json3(200, { orders: runtime.instance(namespace).orders() }),
4258
+ "GET /orders": ({ namespace }) => json5(200, { orders: runtime.instance(namespace).orders() }),
2869
4259
  "POST /orders/:partnerOrderId/transition": ({ params, body, namespace }) => {
2870
- if (!isRecord4(body) || typeof body.status !== "string") {
2871
- return adminError3(
4260
+ if (!isRecord5(body) || typeof body.status !== "string") {
4261
+ return adminError4(
2872
4262
  400,
2873
4263
  'expected {"status": "<AHA status>", "drawStatus"?, "scheduledAt"?, "timeZone"?}'
2874
4264
  );
@@ -2881,50 +4271,50 @@ var adminRoutes = (runtime) => ({
2881
4271
  if (typeof body.timeZone === "string") input.timeZone = body.timeZone;
2882
4272
  try {
2883
4273
  const moved = runtime.instance(namespace).transition(params.partnerOrderId, input);
2884
- return moved ? json3(200, moved) : adminError3(404, `no order ${params.partnerOrderId}`);
4274
+ return moved ? json5(200, moved) : adminError4(404, `no order ${params.partnerOrderId}`);
2885
4275
  } catch (err) {
2886
- if (err instanceof RangeError) return adminError3(400, err.message);
4276
+ if (err instanceof RangeError) return adminError4(400, err.message);
2887
4277
  throw err;
2888
4278
  }
2889
4279
  },
2890
- "GET /settings": ({ namespace }) => json3(200, visible(runtime.instance(namespace).state.current())),
4280
+ "GET /settings": ({ namespace }) => json5(200, visible(runtime.instance(namespace).state.current())),
2891
4281
  "PUT /settings": ({ body, namespace }) => {
2892
- if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
4282
+ if (!isRecord5(body)) return adminError4(400, "expected a JSON object");
2893
4283
  const patch = {};
2894
4284
  if (body.envelope !== void 0) {
2895
4285
  if (body.envelope !== "raw" && body.envelope !== "wrapped")
2896
- return adminError3(400, 'envelope: "raw" | "wrapped"');
4286
+ return adminError4(400, 'envelope: "raw" | "wrapped"');
2897
4287
  patch.envelope = body.envelope;
2898
4288
  }
2899
4289
  if (body.credentials !== void 0) {
2900
4290
  const parsed = parseCredentials(body.credentials);
2901
- if (typeof parsed === "string") return adminError3(400, parsed);
4291
+ if (typeof parsed === "string") return adminError4(400, parsed);
2902
4292
  patch.credentials = parsed;
2903
4293
  }
2904
4294
  for (const flag of ["allowLegacy", "cancelWebhook"]) {
2905
4295
  if (body[flag] !== void 0) {
2906
- if (typeof body[flag] !== "boolean") return adminError3(400, `${flag}: boolean`);
4296
+ if (typeof body[flag] !== "boolean") return adminError4(400, `${flag}: boolean`);
2907
4297
  patch[flag] = body[flag];
2908
4298
  }
2909
4299
  }
2910
4300
  if (body.timestampToleranceMs !== void 0) {
2911
4301
  if (typeof body.timestampToleranceMs !== "number")
2912
- return adminError3(400, "timestampToleranceMs: number");
4302
+ return adminError4(400, "timestampToleranceMs: number");
2913
4303
  patch.timestampToleranceMs = body.timestampToleranceMs;
2914
4304
  }
2915
4305
  if (body.defaultTimeZone !== void 0) {
2916
4306
  if (typeof body.defaultTimeZone !== "string")
2917
- return adminError3(400, "defaultTimeZone: IANA zone");
4307
+ return adminError4(400, "defaultTimeZone: IANA zone");
2918
4308
  patch.defaultTimeZone = body.defaultTimeZone;
2919
4309
  }
2920
4310
  if (body.autoSchedule !== void 0) {
2921
4311
  const parsed = parseAutoSchedule(body.autoSchedule);
2922
- if (typeof parsed === "string") return adminError3(400, parsed);
4312
+ if (typeof parsed === "string") return adminError4(400, parsed);
2923
4313
  patch.autoSchedule = parsed;
2924
4314
  }
2925
- return json3(200, visible(runtime.instance(namespace).state.update(patch)));
4315
+ return json5(200, visible(runtime.instance(namespace).state.update(patch)));
2926
4316
  },
2927
- "POST /tick": ({ namespace }) => json3(200, { applied: runtime.instance(namespace).tick() })
4317
+ "POST /tick": ({ namespace }) => json5(200, { applied: runtime.instance(namespace).tick() })
2928
4318
  });
2929
4319
  var createRuntime2 = (options = {}) => {
2930
4320
  const { retryDelaysMs, fetch: send, ...endpoint } = options.webhooks ?? { url: "" };
@@ -3328,4 +4718,4 @@ export {
3328
4718
  apiKeyCredential,
3329
4719
  AhaAPI
3330
4720
  };
3331
- //# sourceMappingURL=chunk-7QJZ3SXP.js.map
4721
+ //# sourceMappingURL=chunk-WC5YEEUF.js.map