@crvouga/mockingbird-service-resend 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;
@@ -699,64 +701,64 @@ var graphemeLength = (value) => [...value].length;
699
701
  var validateValue = (document2, schema, value, path = []) => {
700
702
  const errors = [];
701
703
  const s = resolveSchema(document2, schema);
702
- const fail = (message) => errors.push({ path, message });
704
+ const fail2 = (message) => errors.push({ path, message });
703
705
  const actual = jsonTypeOf(value);
704
706
  if (actual === "undefined") {
705
- fail("value is undefined");
707
+ fail2("value is undefined");
706
708
  return errors;
707
709
  }
708
710
  const types = schemaTypes(s);
709
711
  if (types.length > 0) {
710
712
  const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
711
713
  if (!ok) {
712
- fail(`expected type ${types.join("|")}, got ${actual}`);
714
+ fail2(`expected type ${types.join("|")}, got ${actual}`);
713
715
  return errors;
714
716
  }
715
717
  }
716
718
  if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
717
- fail("value not in enum");
719
+ fail2("value not in enum");
718
720
  }
719
721
  if (s.const !== void 0 && !deepEqual(s.const, value))
720
- fail("value does not equal const");
722
+ fail2("value does not equal const");
721
723
  if (typeof value === "string") {
722
724
  const length = graphemeLength(value);
723
725
  if (s.minLength !== void 0 && length < s.minLength)
724
- fail(`length ${length} < minLength ${s.minLength}`);
726
+ fail2(`length ${length} < minLength ${s.minLength}`);
725
727
  if (s.maxLength !== void 0 && length > s.maxLength)
726
- fail(`length ${length} > maxLength ${s.maxLength}`);
728
+ fail2(`length ${length} > maxLength ${s.maxLength}`);
727
729
  if (s.pattern !== void 0) {
728
730
  try {
729
731
  if (!new RegExp(s.pattern, "u").test(value))
730
- fail(`does not match pattern ${s.pattern}`);
732
+ fail2(`does not match pattern ${s.pattern}`);
731
733
  } catch {
732
734
  }
733
735
  }
734
736
  if (s.format !== void 0) {
735
737
  const pattern = FORMAT_PATTERNS[s.format];
736
738
  if (pattern && !pattern.test(value))
737
- fail(`does not match format ${s.format}`);
739
+ fail2(`does not match format ${s.format}`);
738
740
  }
739
741
  }
740
742
  if (typeof value === "number") {
741
743
  if (s.minimum !== void 0 && value < s.minimum)
742
- fail(`${value} < minimum ${s.minimum}`);
744
+ fail2(`${value} < minimum ${s.minimum}`);
743
745
  if (s.maximum !== void 0 && value > s.maximum)
744
- fail(`${value} > maximum ${s.maximum}`);
746
+ fail2(`${value} > maximum ${s.maximum}`);
745
747
  if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
746
- fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
748
+ fail2(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
747
749
  if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
748
- fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
750
+ fail2(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
749
751
  if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
750
- fail(`${value} is not a multiple of ${s.multipleOf}`);
752
+ fail2(`${value} is not a multiple of ${s.multipleOf}`);
751
753
  }
752
754
  }
753
755
  if (Array.isArray(value)) {
754
756
  if (s.minItems !== void 0 && value.length < s.minItems)
755
- fail(`${value.length} items < minItems ${s.minItems}`);
757
+ fail2(`${value.length} items < minItems ${s.minItems}`);
756
758
  if (s.maxItems !== void 0 && value.length > s.maxItems)
757
- fail(`${value.length} items > maxItems ${s.maxItems}`);
759
+ fail2(`${value.length} items > maxItems ${s.maxItems}`);
758
760
  if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
759
- fail("items are not unique");
761
+ fail2("items are not unique");
760
762
  value.forEach((item, i) => {
761
763
  const itemSchema = s.prefixItems?.[i] ?? s.items;
762
764
  if (itemSchema)
@@ -768,11 +770,11 @@ var validateValue = (document2, schema, value, path = []) => {
768
770
  const keys = Object.keys(record);
769
771
  for (const name of s.required ?? [])
770
772
  if (!(name in record))
771
- fail(`missing required property ${name}`);
773
+ fail2(`missing required property ${name}`);
772
774
  if (s.minProperties !== void 0 && keys.length < s.minProperties)
773
- fail(`${keys.length} properties < minProperties ${s.minProperties}`);
775
+ fail2(`${keys.length} properties < minProperties ${s.minProperties}`);
774
776
  if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
775
- fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
777
+ fail2(`${keys.length} properties > maxProperties ${s.maxProperties}`);
776
778
  for (const key of keys) {
777
779
  const property = s.properties?.[key];
778
780
  if (property) {
@@ -780,14 +782,14 @@ var validateValue = (document2, schema, value, path = []) => {
780
782
  continue;
781
783
  }
782
784
  if (s.additionalProperties === false)
783
- fail(`unexpected property ${key}`);
785
+ fail2(`unexpected property ${key}`);
784
786
  else if (typeof s.additionalProperties === "object") {
785
787
  errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
786
788
  }
787
789
  if (s.propertyNames) {
788
790
  const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
789
791
  if (nameErrors.length > 0)
790
- fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
792
+ fail2(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
791
793
  }
792
794
  }
793
795
  }
@@ -795,14 +797,14 @@ var validateValue = (document2, schema, value, path = []) => {
795
797
  for (const branch of s.allOf)
796
798
  errors.push(...validateValue(document2, branch, value, path));
797
799
  if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
798
- fail("matches no anyOf branch");
800
+ fail2("matches no anyOf branch");
799
801
  if (s.oneOf) {
800
802
  const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
801
803
  if (matches2 !== 1)
802
- fail(`matches ${matches2} oneOf branches, expected exactly 1`);
804
+ fail2(`matches ${matches2} oneOf branches, expected exactly 1`);
803
805
  }
804
806
  if (s.not && validateValue(document2, s.not, value).length === 0)
805
- fail("matches forbidden `not` schema");
807
+ fail2("matches forbidden `not` schema");
806
808
  return errors;
807
809
  };
808
810
 
@@ -1471,6 +1473,936 @@ var clearNamespace = (sqlite, namespace) => {
1471
1473
  });
1472
1474
  };
1473
1475
 
1476
+ // ../core/dist/surface.js
1477
+ var defineMock = (runtime) => runtime;
1478
+ var STANDARD_ADMIN_ROUTES = [
1479
+ "GET /",
1480
+ "POST /reset",
1481
+ "GET /namespaces",
1482
+ "GET /clock",
1483
+ "POST /clock",
1484
+ "GET /faults",
1485
+ "POST /faults",
1486
+ "DELETE /faults",
1487
+ "POST /snapshots",
1488
+ "POST /snapshots/:id/restore",
1489
+ "DELETE /snapshots/:id",
1490
+ "GET /timeline",
1491
+ "POST /checkpoints",
1492
+ "POST /branches/:name",
1493
+ "POST /branches/:name/checkout",
1494
+ "GET /requests",
1495
+ "DELETE /requests",
1496
+ "GET /metrics",
1497
+ "DELETE /metrics",
1498
+ "GET /credentials",
1499
+ "PUT /credentials",
1500
+ "DELETE /credentials",
1501
+ "GET /state",
1502
+ "GET /state/:collection",
1503
+ "GET /state/:collection/:id",
1504
+ "POST /state/:collection",
1505
+ "PUT /state/:collection/:id",
1506
+ "PATCH /state/:collection/:id",
1507
+ "DELETE /state/:collection/:id",
1508
+ "GET /ui",
1509
+ "GET /ui/",
1510
+ "GET /ui/manifest"
1511
+ ];
1512
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1513
+ var assertAdminUi = (ui) => {
1514
+ if (!ui?.panels)
1515
+ return;
1516
+ const seen = /* @__PURE__ */ new Set();
1517
+ for (const panel of ui.panels) {
1518
+ if (!PANEL_ID.test(panel.id)) {
1519
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1520
+ }
1521
+ if (seen.has(panel.id))
1522
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1523
+ seen.add(panel.id);
1524
+ if (panel.title.trim() === "")
1525
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1526
+ }
1527
+ };
1528
+
1529
+ // ../core/dist/admin-ui.js
1530
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1531
+ switch (char) {
1532
+ case "&":
1533
+ return "&amp;";
1534
+ case "<":
1535
+ return "&lt;";
1536
+ case ">":
1537
+ return "&gt;";
1538
+ case '"':
1539
+ return "&quot;";
1540
+ default:
1541
+ return "&#39;";
1542
+ }
1543
+ });
1544
+ var renderAdminDocument = (service) => {
1545
+ const name = escapeHtml(service);
1546
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1547
+ return `<!DOCTYPE html>
1548
+ <html lang="en">
1549
+ <head>
1550
+ <meta charset="utf-8">
1551
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1552
+ <meta name="color-scheme" content="light dark">
1553
+ <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">
1554
+ <title>${name} admin</title>
1555
+ <style>
1556
+ :root {
1557
+ color-scheme: light;
1558
+ --bg: #f6f5f2;
1559
+ --bg-elev: #ffffff;
1560
+ --bg-muted: #eeece6;
1561
+ --bg-inset: #f3f1eb;
1562
+ --line: #e2dfd6;
1563
+ --line-strong: #d0ccc1;
1564
+ --ink: #1c1915;
1565
+ --muted: #5e584f;
1566
+ --faint: #8a8378;
1567
+ --accent: #3d4f3a;
1568
+ --accent-ink: #f7f6f2;
1569
+ --accent-soft: #e5ece2;
1570
+ --ok: #1f7a45;
1571
+ --ok-soft: #e5f4eb;
1572
+ --warn: #9a6700;
1573
+ --warn-soft: #fbf3df;
1574
+ --err: #a33b32;
1575
+ --err-soft: #fdecea;
1576
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1577
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1578
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1579
+ --radius: 14px;
1580
+ --header: 60px;
1581
+ --nav: 220px;
1582
+ }
1583
+ :root[data-theme="dark"] {
1584
+ color-scheme: dark;
1585
+ --bg: #141311;
1586
+ --bg-elev: #1e1c19;
1587
+ --bg-muted: #26231f;
1588
+ --bg-inset: #181715;
1589
+ --line: #34302b;
1590
+ --line-strong: #4a453d;
1591
+ --ink: #f4f1ea;
1592
+ --muted: #c4bdb1;
1593
+ --faint: #8f877c;
1594
+ --accent: #c5d5b8;
1595
+ --accent-ink: #1a2118;
1596
+ --accent-soft: #2a3328;
1597
+ --ok: #8fd6a8;
1598
+ --ok-soft: #1a2e22;
1599
+ --warn: #f0cc78;
1600
+ --warn-soft: #332911;
1601
+ --err: #f0a8a2;
1602
+ --err-soft: #3a201e;
1603
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1604
+ }
1605
+ @media (prefers-color-scheme: dark) {
1606
+ :root:not([data-theme="light"]) {
1607
+ color-scheme: dark;
1608
+ --bg: #141311;
1609
+ --bg-elev: #1e1c19;
1610
+ --bg-muted: #26231f;
1611
+ --bg-inset: #181715;
1612
+ --line: #34302b;
1613
+ --line-strong: #4a453d;
1614
+ --ink: #f4f1ea;
1615
+ --muted: #c4bdb1;
1616
+ --faint: #8f877c;
1617
+ --accent: #c5d5b8;
1618
+ --accent-ink: #1a2118;
1619
+ --accent-soft: #2a3328;
1620
+ --ok: #8fd6a8;
1621
+ --ok-soft: #1a2e22;
1622
+ --warn: #f0cc78;
1623
+ --warn-soft: #332911;
1624
+ --err: #f0a8a2;
1625
+ --err-soft: #3a201e;
1626
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1627
+ }
1628
+ }
1629
+ * { box-sizing: border-box; }
1630
+ html, body { margin: 0; height: 100%; }
1631
+ body {
1632
+ font-family: var(--sans);
1633
+ background: var(--bg);
1634
+ color: var(--ink);
1635
+ line-height: 1.45;
1636
+ padding-left: env(safe-area-inset-left);
1637
+ padding-right: env(safe-area-inset-right);
1638
+ -webkit-text-size-adjust: 100%;
1639
+ }
1640
+ button, input, select, textarea { font: inherit; color: inherit; }
1641
+ button { cursor: pointer; }
1642
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1643
+ @media (prefers-reduced-motion: reduce) {
1644
+ * { scroll-behavior: auto !important; transition: none !important; }
1645
+ }
1646
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1647
+ header.top {
1648
+ position: sticky; top: 0; z-index: 5;
1649
+ display: flex; align-items: center; gap: 12px;
1650
+ min-height: var(--header); padding: 10px 16px;
1651
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1652
+ border-bottom: 1px solid var(--line);
1653
+ backdrop-filter: blur(10px);
1654
+ }
1655
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1656
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1657
+ .brand span { color: var(--faint); font-size: 12px; }
1658
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1659
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1660
+ label.field input, label.field select, .controls input[type="password"] {
1661
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1662
+ padding: 7px 8px; min-height: 36px;
1663
+ }
1664
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1665
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1666
+ background: var(--bg-elev);
1667
+ }
1668
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1669
+ .btn-quiet { background: transparent; }
1670
+ .btn-danger { color: var(--err); }
1671
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1672
+ record or the full nav row would widen the page past the viewport. */
1673
+ .layout {
1674
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1675
+ flex: 1; min-height: 0; min-width: 0;
1676
+ }
1677
+ nav.side {
1678
+ border-right: 1px solid var(--line); padding: 12px;
1679
+ display: flex; flex-direction: column; gap: 4px;
1680
+ background: var(--bg-elev);
1681
+ }
1682
+ nav.side button {
1683
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1684
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1685
+ }
1686
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1687
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1688
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1689
+ .lede { margin: 0 0 16px; color: var(--muted); }
1690
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1691
+ .card {
1692
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1693
+ padding: 14px 16px; box-shadow: var(--shadow);
1694
+ }
1695
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1696
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1697
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1698
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1699
+ .collection {
1700
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1701
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1702
+ }
1703
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1704
+ .collection small { display: block; color: var(--faint); }
1705
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1706
+ .chip {
1707
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1708
+ border-radius: 999px; padding: 4px 8px;
1709
+ }
1710
+ .chip i { color: var(--faint); font-style: normal; }
1711
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1712
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1713
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1714
+ tr.clickable { cursor: pointer; }
1715
+ tr.clickable:hover { background: var(--bg-muted); }
1716
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1717
+ pre {
1718
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1719
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1720
+ }
1721
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1722
+ .banner {
1723
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1724
+ background: var(--err-soft); color: var(--err);
1725
+ }
1726
+ .banner.show { display: block; }
1727
+ .empty { color: var(--muted); padding: 24px 8px; }
1728
+ dialog {
1729
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1730
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1731
+ }
1732
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1733
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1734
+ textarea {
1735
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1736
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1737
+ font-family: var(--mono); font-size: 12px;
1738
+ }
1739
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1740
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1741
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1742
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1743
+ .status-2 { color: var(--ok); }
1744
+ .status-4, .status-5, .status-0 { color: var(--err); }
1745
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1746
+ .route {
1747
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1748
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1749
+ }
1750
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1751
+ @media (max-width: 800px) {
1752
+ header.top {
1753
+ align-items: stretch; flex-direction: column;
1754
+ padding-top: max(10px, env(safe-area-inset-top));
1755
+ }
1756
+ input, select, textarea { font-size: 16px; }
1757
+ .controls { width: 100%; }
1758
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1759
+ .layout { grid-template-columns: minmax(0, 1fr); }
1760
+ nav.side {
1761
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1762
+ border-right: 0; border-bottom: 1px solid var(--line);
1763
+ padding: 8px;
1764
+ }
1765
+ nav.side button { white-space: nowrap; flex: none; }
1766
+ .split { grid-template-columns: minmax(0, 1fr); }
1767
+ main { padding: 14px; }
1768
+ table, thead, tbody, tr, th, td { display: block; }
1769
+ thead { display: none; }
1770
+ tr {
1771
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1772
+ background: var(--bg-elev); min-width: 0;
1773
+ }
1774
+ td {
1775
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1776
+ min-width: 0; overflow-wrap: anywhere;
1777
+ }
1778
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1779
+ .route { grid-template-columns: 72px 1fr; }
1780
+ .route button { grid-column: 1 / -1; }
1781
+ }
1782
+ </style>
1783
+ </head>
1784
+ <body>
1785
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1786
+ <header class="top">
1787
+ <div class="brand">
1788
+ <strong>${name}</strong>
1789
+ <span>Mockingbird admin</span>
1790
+ </div>
1791
+ <div class="controls">
1792
+ <label class="field">Namespace
1793
+ <select id="namespace" aria-label="Namespace"></select>
1794
+ </label>
1795
+ <label class="field">Admin key
1796
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1797
+ </label>
1798
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1799
+ <button class="btn" id="refresh" type="button">Refresh</button>
1800
+ </div>
1801
+ </header>
1802
+ <div class="layout">
1803
+ <nav class="side" id="nav" aria-label="Admin sections">
1804
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1805
+ <button type="button" data-view="state">State</button>
1806
+ <button type="button" data-view="clock">Clock</button>
1807
+ <button type="button" data-view="faults">Faults</button>
1808
+ <button type="button" data-view="journal">Journal</button>
1809
+ <button type="button" data-view="routes">Routes</button>
1810
+ </nav>
1811
+ <main id="views">
1812
+ <p class="banner" id="banner" role="alert"></p>
1813
+ <section class="view" id="view-overview">
1814
+ <h2>Overview</h2>
1815
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1816
+ <div class="grid" id="overview-cards"></div>
1817
+ <h3>Recent requests</h3>
1818
+ <div id="overview-requests"></div>
1819
+ </section>
1820
+ <section class="view" id="view-state" hidden>
1821
+ <h2>State</h2>
1822
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1823
+ <div class="split">
1824
+ <div id="collections"></div>
1825
+ <div>
1826
+ <div id="schema"></div>
1827
+ <div class="row-actions">
1828
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1829
+ </div>
1830
+ <div id="records"></div>
1831
+ </div>
1832
+ </div>
1833
+ </section>
1834
+ <section class="view" id="view-clock" hidden>
1835
+ <h2>Clock</h2>
1836
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1837
+ <div class="card" id="clock-readout"></div>
1838
+ <div class="row-actions">
1839
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1840
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1841
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1842
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1843
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1844
+ <button class="btn" id="freeze" type="button">Freeze</button>
1845
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1846
+ </div>
1847
+ <form id="clock-set" class="row-actions">
1848
+ <label class="field">Set instant
1849
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1850
+ </label>
1851
+ <button class="btn-primary" type="submit">Set</button>
1852
+ </form>
1853
+ </section>
1854
+ <section class="view" id="view-faults" hidden>
1855
+ <h2>Faults</h2>
1856
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1857
+ <form id="fault-form" class="card stack">
1858
+ <label class="field">Preset
1859
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1860
+ </label>
1861
+ <label class="field">Status
1862
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1863
+ </label>
1864
+ <label class="field">Path prefix
1865
+ <input id="fault-path" placeholder="/v1">
1866
+ </label>
1867
+ <label class="field">Method
1868
+ <input id="fault-method" placeholder="GET">
1869
+ </label>
1870
+ <div class="dialog-actions">
1871
+ <button class="btn-primary" type="submit">Add fault</button>
1872
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1873
+ </div>
1874
+ </form>
1875
+ <div id="fault-list"></div>
1876
+ </section>
1877
+ <section class="view" id="view-journal" hidden>
1878
+ <h2>Journal</h2>
1879
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1880
+ <div class="row-actions">
1881
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1882
+ </div>
1883
+ <div id="journal"></div>
1884
+ </section>
1885
+ <section class="view" id="view-routes" hidden>
1886
+ <h2>Routes</h2>
1887
+ <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>
1888
+ <div id="route-list"></div>
1889
+ <form id="route-form" class="card stack">
1890
+ <strong id="route-title">Select a route</strong>
1891
+ <label class="field">JSON body
1892
+ <textarea id="route-body" placeholder="{ }"></textarea>
1893
+ </label>
1894
+ <div class="dialog-actions">
1895
+ <button class="btn-primary" type="submit">Send</button>
1896
+ </div>
1897
+ <pre id="route-result">Response will show here.</pre>
1898
+ </form>
1899
+ </section>
1900
+ </main>
1901
+ </div>
1902
+ </div>
1903
+ <dialog id="editor">
1904
+ <form method="dialog" id="editor-form">
1905
+ <strong id="editor-title">Record</strong>
1906
+ <label class="field">Id
1907
+ <input id="editor-id" required>
1908
+ </label>
1909
+ <label class="field">JSON value
1910
+ <textarea id="editor-value"></textarea>
1911
+ </label>
1912
+ <div class="dialog-actions">
1913
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1914
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1915
+ <button class="btn-primary" type="submit" value="save">Save</button>
1916
+ </div>
1917
+ </form>
1918
+ </dialog>
1919
+ <script>
1920
+ (() => {
1921
+ const STANDARD = new Set(${standard})
1922
+ const state = {
1923
+ namespace: "default",
1924
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1925
+ view: "overview",
1926
+ collection: "",
1927
+ shape: null,
1928
+ route: null,
1929
+ editing: null
1930
+ }
1931
+ const $ = (id) => document.getElementById(id)
1932
+ const banner = $("banner")
1933
+ const keyInput = $("admin-key")
1934
+ keyInput.value = state.key
1935
+ const params = new URLSearchParams(location.search)
1936
+ if (params.get("key")) {
1937
+ state.key = params.get("key")
1938
+ keyInput.value = state.key
1939
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1940
+ params.delete("key")
1941
+ const next = params.toString()
1942
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1943
+ }
1944
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1945
+
1946
+ const showError = (error) => {
1947
+ banner.textContent = error instanceof Error ? error.message : String(error)
1948
+ banner.classList.add("show")
1949
+ }
1950
+ const clearError = () => banner.classList.remove("show")
1951
+
1952
+ async function originGet(path) {
1953
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1954
+ if (!response.ok) throw new Error(response.status + " " + path)
1955
+ return response.json()
1956
+ }
1957
+ async function api(method, path, body) {
1958
+ const headers = { accept: "application/json" }
1959
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1960
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1961
+ if (body !== undefined) headers["content-type"] = "application/json"
1962
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1963
+ method,
1964
+ headers,
1965
+ body: body === undefined ? undefined : JSON.stringify(body)
1966
+ })
1967
+ const text = await response.text()
1968
+ let data = null
1969
+ if (text) {
1970
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1971
+ }
1972
+ if (response.status === 401) {
1973
+ keyInput.focus()
1974
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1975
+ }
1976
+ if (!response.ok) {
1977
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1978
+ }
1979
+ return data
1980
+ }
1981
+ const panelApi = {
1982
+ get: (path) => api("GET", path),
1983
+ send: (method, path, body) => api(method, path, body),
1984
+ namespace: () => state.namespace
1985
+ }
1986
+
1987
+ function setTheme(theme) {
1988
+ if (theme) document.documentElement.dataset.theme = theme
1989
+ else delete document.documentElement.dataset.theme
1990
+ }
1991
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1992
+ if (storedTheme) setTheme(storedTheme)
1993
+ $("theme").addEventListener("click", () => {
1994
+ const current = document.documentElement.dataset.theme
1995
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1996
+ const next = dark ? "light" : "dark"
1997
+ localStorage.setItem("mockingbird-admin-theme", next)
1998
+ setTheme(next)
1999
+ })
2000
+
2001
+ function show(view) {
2002
+ state.view = view
2003
+ for (const button of document.querySelectorAll("#nav button")) {
2004
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
2005
+ }
2006
+ for (const section of document.querySelectorAll("main .view")) {
2007
+ section.hidden = section.id !== "view-" + view
2008
+ }
2009
+ }
2010
+ document.getElementById("nav").addEventListener("click", (event) => {
2011
+ const button = event.target.closest("button[data-view]")
2012
+ if (!button) return
2013
+ show(button.dataset.view)
2014
+ refresh().catch(showError)
2015
+ })
2016
+
2017
+ function cards(items) {
2018
+ return '<div class="grid">' + items.map((item) =>
2019
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
2020
+ ).join("") + "</div>"
2021
+ }
2022
+ function table(columns, rows) {
2023
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
2024
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
2025
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
2026
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
2027
+ ).join("") + "</tr>").join("")
2028
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
2029
+ }
2030
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
2031
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
2032
+ }[char]))
2033
+ const preview = (value) => {
2034
+ const text = JSON.stringify(value)
2035
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
2036
+ }
2037
+ const when = (epoch) => {
2038
+ const date = new Date(epoch)
2039
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
2040
+ }
2041
+ const clockCard = (epoch) => {
2042
+ const date = new Date(epoch)
2043
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
2044
+ const iso = date.toISOString()
2045
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
2046
+ }
2047
+
2048
+ async function loadNamespaces() {
2049
+ const data = await api("GET", "/namespaces")
2050
+ const select = $("namespace")
2051
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
2052
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
2053
+ select.innerHTML = names.map((name) =>
2054
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
2055
+ ).join("")
2056
+ select.value = state.namespace
2057
+ }
2058
+
2059
+ async function renderOverview() {
2060
+ const [health, shape, clock, journal] = await Promise.all([
2061
+ originGet("/health"),
2062
+ api("GET", "/state"),
2063
+ api("GET", "/clock"),
2064
+ api("GET", "/requests?limit=8")
2065
+ ])
2066
+ state.shape = shape
2067
+ $("overview-cards").innerHTML = cards([
2068
+ { k: "Service", v: esc(health.service || "${name}") },
2069
+ { k: "Status", v: esc(health.status || "ok") },
2070
+ { k: "Namespace", v: esc(state.namespace) },
2071
+ { k: "Collections", v: String(shape.collections.length) },
2072
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
2073
+ { k: "Clock", v: clockCard(clock.now) }
2074
+ ])
2075
+ const requests = (journal && journal.requests) || []
2076
+ $("overview-requests").innerHTML = table(
2077
+ [
2078
+ { label: "Method", cell: (row) => esc(row.method) },
2079
+ { label: "Path", cell: (row) => esc(row.path) },
2080
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
2081
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
2082
+ ],
2083
+ requests
2084
+ )
2085
+ }
2086
+
2087
+ function schemaChips(collection) {
2088
+ if (!collection || collection.fields.length === 0) {
2089
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
2090
+ }
2091
+ return '<div class="chips">' + collection.fields.map((field) =>
2092
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
2093
+ ).join("") + "</div>"
2094
+ }
2095
+
2096
+ async function renderState() {
2097
+ const shape = await api("GET", "/state")
2098
+ state.shape = shape
2099
+ const host = $("collections")
2100
+ if (shape.collections.length === 0) {
2101
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
2102
+ $("schema").innerHTML = ""
2103
+ $("records").innerHTML = ""
2104
+ return
2105
+ }
2106
+ if (!shape.collections.some((item) => item.name === state.collection)) {
2107
+ state.collection = shape.collections[0].name
2108
+ }
2109
+ host.innerHTML = shape.collections.map((item) =>
2110
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
2111
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
2112
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
2113
+ ).join("")
2114
+ const selected = shape.collections.find((item) => item.name === state.collection)
2115
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
2116
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
2117
+ schemaChips(selected)
2118
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
2119
+ const rows = page.records.map((record) => ({
2120
+ ...record,
2121
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
2122
+ }))
2123
+ $("records").innerHTML = table(
2124
+ [
2125
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
2126
+ { label: "Seq", cell: (row) => esc(row.seq) },
2127
+ { label: "Value", cell: (row) => preview(row.value) }
2128
+ ],
2129
+ rows
2130
+ )
2131
+ }
2132
+
2133
+ async function renderClock() {
2134
+ const clock = await api("GET", "/clock")
2135
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
2136
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
2137
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
2138
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
2139
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
2140
+ }
2141
+
2142
+ async function renderFaults() {
2143
+ const [faults, presets] = await Promise.all([
2144
+ api("GET", "/faults"),
2145
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2146
+ ])
2147
+ const select = $("fault-preset")
2148
+ const current = select.value
2149
+ const list = presets.presets || []
2150
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
2151
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
2152
+ ).join("")
2153
+ select.value = current
2154
+ const rules = faults.faults || []
2155
+ $("fault-list").innerHTML = table(
2156
+ [
2157
+ { label: "Id", cell: (row) => esc(row.id) },
2158
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
2159
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
2160
+ ],
2161
+ rules
2162
+ )
2163
+ }
2164
+
2165
+ async function renderJournal() {
2166
+ const journal = await api("GET", "/requests?limit=100")
2167
+ $("journal").innerHTML = table(
2168
+ [
2169
+ { label: "When", cell: (row) => esc(row.at || "") },
2170
+ { label: "Method", cell: (row) => esc(row.method) },
2171
+ { label: "Path", cell: (row) => esc(row.path) },
2172
+ { label: "Status", cell: (row) => esc(row.status) },
2173
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2174
+ ],
2175
+ journal.requests || []
2176
+ )
2177
+ }
2178
+
2179
+ async function renderRoutes() {
2180
+ const data = await api("GET", "/")
2181
+ const routes = data.routes || []
2182
+ $("route-list").innerHTML = routes.map((route) => {
2183
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
2184
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
2185
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
2186
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
2187
+ }).join("")
2188
+ }
2189
+
2190
+ const renderers = {
2191
+ overview: renderOverview,
2192
+ state: renderState,
2193
+ clock: renderClock,
2194
+ faults: renderFaults,
2195
+ journal: renderJournal,
2196
+ routes: renderRoutes
2197
+ }
2198
+
2199
+ async function refresh() {
2200
+ clearError()
2201
+ if (state.view in renderers) await renderers[state.view]()
2202
+ }
2203
+
2204
+ $("namespace").addEventListener("change", () => {
2205
+ state.namespace = $("namespace").value
2206
+ refresh().catch(showError)
2207
+ })
2208
+ keyInput.addEventListener("change", () => {
2209
+ state.key = keyInput.value.trim()
2210
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
2211
+ refresh().catch(showError)
2212
+ })
2213
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
2214
+
2215
+ $("collections").addEventListener("click", (event) => {
2216
+ const button = event.target.closest("[data-collection]")
2217
+ if (!button) return
2218
+ state.collection = button.dataset.collection
2219
+ renderState().catch(showError)
2220
+ })
2221
+ $("records").addEventListener("click", (event) => {
2222
+ const row = event.target.closest("[data-id]")
2223
+ if (!row) return
2224
+ openEditor(row.dataset.id).catch(showError)
2225
+ })
2226
+
2227
+ const editor = $("editor")
2228
+ async function openEditor(id) {
2229
+ state.editing = id || null
2230
+ $("editor-title").textContent = id ? "Edit record" : "New record"
2231
+ $("editor-id").value = id || ""
2232
+ $("editor-id").readOnly = Boolean(id)
2233
+ $("editor-delete").hidden = !id
2234
+ if (id) {
2235
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2236
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
2237
+ } else {
2238
+ $("editor-value").value = "{\\n \\n}"
2239
+ }
2240
+ editor.showModal()
2241
+ }
2242
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
2243
+ $("editor-form").addEventListener("submit", (event) => {
2244
+ const submitter = event.submitter
2245
+ if (!submitter || submitter.value !== "save") return
2246
+ event.preventDefault()
2247
+ let value
2248
+ try { value = JSON.parse($("editor-value").value) }
2249
+ catch { showError(new Error("Value is not JSON")); return }
2250
+ const id = $("editor-id").value.trim()
2251
+ const path = "/state/" + encodeURIComponent(state.collection)
2252
+ const request = state.editing
2253
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
2254
+ : api("POST", path, { id: id || undefined, value })
2255
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
2256
+ })
2257
+ $("editor-delete").addEventListener("click", () => {
2258
+ const id = state.editing
2259
+ if (!id) return
2260
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2261
+ .then(() => { editor.close(); return renderState() })
2262
+ .catch(showError)
2263
+ })
2264
+
2265
+ document.querySelectorAll("[data-advance]").forEach((button) => {
2266
+ button.addEventListener("click", () => {
2267
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
2268
+ })
2269
+ })
2270
+ $("freeze").addEventListener("click", () => {
2271
+ const frozen = $("freeze").dataset.frozen === "1"
2272
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
2273
+ })
2274
+ $("clock-reset").addEventListener("click", () => {
2275
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
2276
+ })
2277
+ $("clock-set").addEventListener("submit", (event) => {
2278
+ event.preventDefault()
2279
+ const raw = $("clock-instant").value.trim()
2280
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
2281
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
2282
+ })
2283
+
2284
+ $("fault-form").addEventListener("submit", (event) => {
2285
+ event.preventDefault()
2286
+ const preset = $("fault-preset").value
2287
+ const body = preset
2288
+ ? { preset }
2289
+ : {
2290
+ status: Number($("fault-status").value),
2291
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
2292
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
2293
+ }
2294
+ if (!preset && !Number.isFinite(body.status)) {
2295
+ showError(new Error("Status must be a number, or choose a preset"))
2296
+ return
2297
+ }
2298
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
2299
+ })
2300
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
2301
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
2302
+
2303
+ $("route-list").addEventListener("click", (event) => {
2304
+ const button = event.target.closest("[data-route]")
2305
+ if (!button) return
2306
+ state.route = button.dataset.route
2307
+ $("route-title").textContent = state.route
2308
+ const method = state.route.split(" ")[0]
2309
+ $("route-body").disabled = method === "GET" || method === "DELETE"
2310
+ })
2311
+ $("route-form").addEventListener("submit", async (event) => {
2312
+ event.preventDefault()
2313
+ if (!state.route) return showError(new Error("Choose a route first"))
2314
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
2315
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
2316
+ let body
2317
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
2318
+ try { body = JSON.parse($("route-body").value) }
2319
+ catch { return showError(new Error("Body is not JSON")) }
2320
+ }
2321
+ try {
2322
+ const data = await api(method, concrete, body)
2323
+ $("route-result").textContent = JSON.stringify(data, null, 2)
2324
+ } catch (error) {
2325
+ showError(error)
2326
+ }
2327
+ })
2328
+
2329
+ function mountPanels(panels) {
2330
+ const nav = $("nav")
2331
+ const views = $("views")
2332
+ for (const panel of panels) {
2333
+ const button = document.createElement("button")
2334
+ button.type = "button"
2335
+ button.dataset.view = panel.id
2336
+ button.textContent = panel.title
2337
+ nav.append(button)
2338
+ const section = document.createElement("section")
2339
+ section.className = "view"
2340
+ section.id = "view-" + panel.id
2341
+ section.hidden = true
2342
+ const title = document.createElement("h2")
2343
+ title.textContent = panel.title
2344
+ const lede = document.createElement("p")
2345
+ lede.className = "lede"
2346
+ lede.textContent = panel.description || ""
2347
+ const body = document.createElement("div")
2348
+ body.className = "panel-body"
2349
+ body.id = "panel-" + panel.id
2350
+ body.innerHTML = panel.html || ""
2351
+ section.append(title, lede, body)
2352
+ views.append(section)
2353
+ if (panel.script) {
2354
+ try {
2355
+ const run = new Function("root", "api", panel.script)
2356
+ run(body, panelApi)
2357
+ } catch (error) {
2358
+ const note = document.createElement("p")
2359
+ note.className = "banner show"
2360
+ note.textContent = error instanceof Error ? error.message : String(error)
2361
+ body.append(note)
2362
+ }
2363
+ }
2364
+ }
2365
+ }
2366
+
2367
+ loadNamespaces()
2368
+ .then(() => api("GET", "/ui/manifest"))
2369
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2370
+ .catch(showError)
2371
+ })()
2372
+ </script>
2373
+ </body>
2374
+ </html>`;
2375
+ };
2376
+ var htmlResponse = (body) => new Response(body, {
2377
+ status: 200,
2378
+ headers: {
2379
+ "content-type": "text/html; charset=utf-8",
2380
+ "cache-control": "no-store"
2381
+ }
2382
+ });
2383
+ var json3 = (body) => new Response(JSON.stringify(body), {
2384
+ status: 200,
2385
+ headers: { "content-type": "application/json; charset=utf-8" }
2386
+ });
2387
+ var adminUiRoutes = (service, ui) => {
2388
+ const shell = () => renderAdminDocument(service);
2389
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2390
+ return {
2391
+ "GET /ui": () => htmlResponse(document2()),
2392
+ "GET /ui/": () => htmlResponse(document2()),
2393
+ "GET /ui/manifest": () => json3({
2394
+ service,
2395
+ panels: (ui?.panels ?? []).map((panel) => ({
2396
+ id: panel.id,
2397
+ title: panel.title,
2398
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2399
+ html: panel.html,
2400
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2401
+ }))
2402
+ })
2403
+ };
2404
+ };
2405
+
1474
2406
  // ../../openapi/metadata/dist/types.js
1475
2407
  var EXTENSION_KEYS = {
1476
2408
  operation: "x-mockingbird",
@@ -1708,8 +2640,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1708
2640
  });
1709
2641
  };
1710
2642
 
2643
+ // ../core/dist/state-view.js
2644
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2645
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2646
+ var SAMPLE = 25;
2647
+ var WALK_LIMIT = 1e4;
2648
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2649
+ var fail = (status, message) => ({ ok: false, status, message });
2650
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2651
+ var kindOf = (value) => {
2652
+ if (value === null)
2653
+ return "null";
2654
+ if (Array.isArray(value))
2655
+ return "array";
2656
+ switch (typeof value) {
2657
+ case "string":
2658
+ return "string";
2659
+ case "number":
2660
+ return Number.isFinite(value) ? "number" : "unknown";
2661
+ case "boolean":
2662
+ return "boolean";
2663
+ case "object":
2664
+ return "object";
2665
+ default:
2666
+ return "unknown";
2667
+ }
2668
+ };
2669
+ var humanize = (name) => {
2670
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2671
+ if (words === "")
2672
+ return name;
2673
+ return words.charAt(0).toUpperCase() + words.slice(1);
2674
+ };
2675
+ var jsonValue = (value) => {
2676
+ if (value === void 0)
2677
+ return fail(400, "value is required");
2678
+ try {
2679
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2680
+ } catch {
2681
+ return fail(400, "value must be JSON");
2682
+ }
2683
+ };
2684
+ var ctorName = (value) => {
2685
+ const ctor = value.constructor;
2686
+ return typeof ctor?.name === "string" ? ctor.name : "";
2687
+ };
2688
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2689
+ var discoverCollections = (root) => {
2690
+ const found = [];
2691
+ const seen = /* @__PURE__ */ new Set();
2692
+ const visit = (value, depth) => {
2693
+ if (found.length + seen.size > WALK_LIMIT)
2694
+ return;
2695
+ if (value === null || typeof value !== "object")
2696
+ return;
2697
+ if (seen.has(value))
2698
+ return;
2699
+ seen.add(value);
2700
+ if (value instanceof Collection) {
2701
+ found.push(value);
2702
+ return;
2703
+ }
2704
+ if (value instanceof Map) {
2705
+ for (const child of value.values())
2706
+ visit(child, depth + 1);
2707
+ return;
2708
+ }
2709
+ if (value instanceof Set) {
2710
+ for (const child of value.values())
2711
+ visit(child, depth + 1);
2712
+ return;
2713
+ }
2714
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2715
+ return;
2716
+ if (Array.isArray(value)) {
2717
+ const cap = Math.min(value.length, 32);
2718
+ for (let i = 0; i < cap; i++)
2719
+ visit(value[i], depth + 1);
2720
+ return;
2721
+ }
2722
+ let children;
2723
+ try {
2724
+ children = Object.values(value);
2725
+ } catch {
2726
+ return;
2727
+ }
2728
+ for (const child of children)
2729
+ visit(child, depth + 1);
2730
+ };
2731
+ visit(root, 0);
2732
+ return found;
2733
+ };
2734
+ var storedNames = (sqlite, namespace) => {
2735
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2736
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2737
+ return [...records, ...sequences].map((row) => row.name);
2738
+ };
2739
+ var blankAccum = (name) => ({
2740
+ name,
2741
+ kinds: /* @__PURE__ */ new Set(),
2742
+ present: 0,
2743
+ nested: /* @__PURE__ */ new Map()
2744
+ });
2745
+ var absorb = (accum, value) => {
2746
+ const kind = kindOf(value);
2747
+ accum.kinds.add(kind);
2748
+ accum.present++;
2749
+ if (!isRecord3(value))
2750
+ return;
2751
+ for (const [key, child] of Object.entries(value)) {
2752
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2753
+ absorb(nested, child);
2754
+ accum.nested.set(key, nested);
2755
+ }
2756
+ };
2757
+ var finishField = (accum, samples) => {
2758
+ const kinds = [...accum.kinds];
2759
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2760
+ const field = {
2761
+ name: accum.name,
2762
+ kind,
2763
+ optional: accum.present < samples || kinds.includes("null")
2764
+ };
2765
+ if (accum.nested.size > 0) {
2766
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2767
+ }
2768
+ return field;
2769
+ };
2770
+ var inferFields = (records) => {
2771
+ if (records.length === 0)
2772
+ return [];
2773
+ const sample = records.slice(0, SAMPLE);
2774
+ const objects = sample.filter((record) => isRecord3(record.value));
2775
+ if (objects.length === 0) {
2776
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2777
+ const list2 = [...kinds];
2778
+ return [
2779
+ {
2780
+ name: "(value)",
2781
+ kind: list2.length === 1 ? list2[0] : "unknown",
2782
+ optional: false
2783
+ }
2784
+ ];
2785
+ }
2786
+ const root = /* @__PURE__ */ new Map();
2787
+ for (const record of objects) {
2788
+ for (const [key, value] of Object.entries(record.value)) {
2789
+ const accum = root.get(key) ?? blankAccum(key);
2790
+ absorb(accum, value);
2791
+ root.set(key, accum);
2792
+ }
2793
+ }
2794
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2795
+ };
2796
+ var mergeFields = (declared, inferred) => {
2797
+ const byName = /* @__PURE__ */ new Map();
2798
+ for (const field of inferred)
2799
+ byName.set(field.name, field);
2800
+ const ordered = [];
2801
+ const seen = /* @__PURE__ */ new Set();
2802
+ for (const field of declared ?? []) {
2803
+ const found = byName.get(field.name);
2804
+ seen.add(field.name);
2805
+ if (!found) {
2806
+ ordered.push({ ...field, optional: field.optional });
2807
+ continue;
2808
+ }
2809
+ ordered.push({
2810
+ ...found,
2811
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2812
+ optional: field.optional || found.optional,
2813
+ ...field.description !== void 0 ? { description: field.description } : {},
2814
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2815
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2816
+ });
2817
+ }
2818
+ for (const field of inferred) {
2819
+ if (!seen.has(field.name))
2820
+ ordered.push(field);
2821
+ }
2822
+ return ordered;
2823
+ };
2824
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2825
+ var readRecord = (collection, id) => {
2826
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2827
+ const row = rows.find((entry) => entry.id === id);
2828
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2829
+ };
2830
+ var inspectState = (scope) => {
2831
+ const declared = /* @__PURE__ */ new Map();
2832
+ for (const declaration of scope.declarations ?? []) {
2833
+ if (COLLECTION_NAME.test(declaration.name))
2834
+ declared.set(declaration.name, declaration);
2835
+ }
2836
+ const names = new Set(declared.keys());
2837
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2838
+ names.add(name);
2839
+ for (const collection of discoverCollections(scope.root)) {
2840
+ if (collection.namespace === scope.storageNamespace)
2841
+ names.add(collection.collectionName);
2842
+ }
2843
+ const collections = [];
2844
+ for (const name of names) {
2845
+ if (!COLLECTION_NAME.test(name))
2846
+ continue;
2847
+ const declaration = declared.get(name);
2848
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2849
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2850
+ const inferred = inferFields(records);
2851
+ const fields = mergeFields(declaration?.fields, inferred);
2852
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2853
+ collections.push({
2854
+ name,
2855
+ label: declaration?.label ?? humanize(name),
2856
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2857
+ count: collection.count(),
2858
+ source,
2859
+ fields,
2860
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2861
+ });
2862
+ }
2863
+ const order = /* @__PURE__ */ new Map();
2864
+ for (const [index, item] of (scope.declarations ?? []).entries())
2865
+ order.set(item.name, index);
2866
+ collections.sort((a, b) => {
2867
+ const left = order.get(a.name);
2868
+ const right = order.get(b.name);
2869
+ if (left !== void 0 && right !== void 0)
2870
+ return left - right;
2871
+ if (left !== void 0)
2872
+ return -1;
2873
+ if (right !== void 0)
2874
+ return 1;
2875
+ return a.name.localeCompare(b.name);
2876
+ });
2877
+ return {
2878
+ namespace: scope.namespace,
2879
+ storageNamespace: scope.storageNamespace,
2880
+ collections
2881
+ };
2882
+ };
2883
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2884
+ if (!COLLECTION_NAME.test(name))
2885
+ return fail(400, "collection name is not allowed");
2886
+ const limit = query.limit ?? 50;
2887
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2888
+ return fail(400, "limit must be an integer from 1 to 200");
2889
+ }
2890
+ const order = query.order ?? "newest";
2891
+ if (order !== "newest" && order !== "oldest")
2892
+ return fail(400, 'order must be "newest" or "oldest"');
2893
+ const collection = collectionOf(sqlite, storageNamespace, name);
2894
+ const rows = collection.list({ order }).filter((row) => {
2895
+ if (query.after === void 0)
2896
+ return true;
2897
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2898
+ });
2899
+ const slice = rows.slice(0, limit);
2900
+ const last = slice.at(-1);
2901
+ return {
2902
+ ok: true,
2903
+ value: {
2904
+ collection: name,
2905
+ count: collection.count(),
2906
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2907
+ next: rows.length > limit && last ? last.seq : null
2908
+ }
2909
+ };
2910
+ };
2911
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2912
+ var readStateRecord = (scope, name, id) => {
2913
+ if (!COLLECTION_NAME.test(name))
2914
+ return fail(400, "collection name is not allowed");
2915
+ if (!RECORD_ID.test(id))
2916
+ return fail(400, "record id is not allowed");
2917
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2918
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
2919
+ };
2920
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2921
+ var createStateRecord = (scope, name, input) => {
2922
+ if (!COLLECTION_NAME.test(name))
2923
+ return fail(400, "collection name is not allowed");
2924
+ const parsed = jsonValue(input.value);
2925
+ if (!parsed.ok)
2926
+ return parsed;
2927
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2928
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2929
+ const checked = requireId(id);
2930
+ if (!checked.ok)
2931
+ return checked;
2932
+ if (collection.has(checked.value))
2933
+ return fail(409, `record ${checked.value} already exists`);
2934
+ const stored = collection.insert(checked.value, parsed.value);
2935
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2936
+ };
2937
+ var replaceStateRecord = (scope, name, id, value) => {
2938
+ if (!COLLECTION_NAME.test(name))
2939
+ return fail(400, "collection name is not allowed");
2940
+ const checked = requireId(id);
2941
+ if (!checked.ok)
2942
+ return checked;
2943
+ const parsed = jsonValue(value);
2944
+ if (!parsed.ok)
2945
+ return parsed;
2946
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2947
+ if (!collection.has(checked.value))
2948
+ return fail(404, `no record ${checked.value} in ${name}`);
2949
+ const stored = collection.update(checked.value, parsed.value);
2950
+ if (!stored)
2951
+ return fail(404, `no record ${checked.value} in ${name}`);
2952
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2953
+ };
2954
+ var patchStateRecord = (scope, name, id, value) => {
2955
+ const current = readStateRecord(scope, name, id);
2956
+ if (!current.ok)
2957
+ return current;
2958
+ const parsed = jsonValue(value);
2959
+ if (!parsed.ok)
2960
+ return parsed;
2961
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2962
+ return replaceStateRecord(scope, name, id, next);
2963
+ };
2964
+ var deleteStateRecord = (scope, name, id) => {
2965
+ if (!COLLECTION_NAME.test(name))
2966
+ return fail(400, "collection name is not allowed");
2967
+ const checked = requireId(id);
2968
+ if (!checked.ok)
2969
+ return checked;
2970
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2971
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2972
+ };
2973
+ var json4 = (status, body) => new Response(JSON.stringify(body), {
2974
+ status,
2975
+ headers: { "content-type": "application/json; charset=utf-8" }
2976
+ });
2977
+ var adminError2 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2978
+ var fromResult = (result, status) => result.ok ? json4(status, result.value) : adminError2(result.status, result.message);
2979
+ var integerParam = (value) => {
2980
+ if (value === null)
2981
+ return void 0;
2982
+ if (!/^-?\d+$/.test(value))
2983
+ return "bad";
2984
+ return Number(value);
2985
+ };
2986
+ var stateAdminRoutes = (routes) => {
2987
+ const open = (namespace) => {
2988
+ try {
2989
+ return { ok: true, value: routes.open(namespace) };
2990
+ } catch (error2) {
2991
+ return fail(400, error2 instanceof Error ? error2.message : String(error2));
2992
+ }
2993
+ };
2994
+ const wrote = (namespace) => {
2995
+ routes.afterWrite?.(namespace);
2996
+ };
2997
+ return {
2998
+ "GET /state": ({ namespace }) => {
2999
+ const scope = open(namespace);
3000
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
3001
+ },
3002
+ "GET /state/:collection": ({ namespace, params, url }) => {
3003
+ const scope = open(namespace);
3004
+ if (!scope.ok)
3005
+ return fromResult(scope, 200);
3006
+ const limit = integerParam(url.searchParams.get("limit"));
3007
+ const after = integerParam(url.searchParams.get("after"));
3008
+ if (limit === "bad")
3009
+ return adminError2(400, "limit: expected an integer");
3010
+ if (after === "bad")
3011
+ return adminError2(400, "after: expected a sequence number");
3012
+ const order = url.searchParams.get("order");
3013
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
3014
+ ...limit !== void 0 ? { limit } : {},
3015
+ ...after !== void 0 ? { after } : {},
3016
+ ...order === "newest" || order === "oldest" ? { order } : {}
3017
+ }), 200);
3018
+ },
3019
+ "GET /state/:collection/:id": ({ namespace, params }) => {
3020
+ const scope = open(namespace);
3021
+ if (!scope.ok)
3022
+ return fromResult(scope, 200);
3023
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
3024
+ },
3025
+ "POST /state/:collection": ({ namespace, params, body }) => {
3026
+ const scope = open(namespace);
3027
+ if (!scope.ok)
3028
+ return fromResult(scope, 201);
3029
+ if (!isRecord3(body) || !("value" in body)) {
3030
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
3031
+ }
3032
+ const id = body.id;
3033
+ if (id !== void 0 && typeof id !== "string")
3034
+ return adminError2(400, "id must be a string");
3035
+ const created = createStateRecord(scope.value, params.collection ?? "", {
3036
+ ...typeof id === "string" ? { id } : {},
3037
+ value: body.value
3038
+ });
3039
+ if (created.ok)
3040
+ wrote(namespace);
3041
+ return fromResult(created, 201);
3042
+ },
3043
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
3044
+ const scope = open(namespace);
3045
+ if (!scope.ok)
3046
+ return fromResult(scope, 200);
3047
+ if (!isRecord3(body) || !("value" in body))
3048
+ return adminError2(400, 'expected {"value": <json>}');
3049
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3050
+ if (replaced.ok)
3051
+ wrote(namespace);
3052
+ return fromResult(replaced, 200);
3053
+ },
3054
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
3055
+ const scope = open(namespace);
3056
+ if (!scope.ok)
3057
+ return fromResult(scope, 200);
3058
+ if (!isRecord3(body) || !("value" in body))
3059
+ return adminError2(400, 'expected {"value": <json>}');
3060
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3061
+ if (patched.ok)
3062
+ wrote(namespace);
3063
+ return fromResult(patched, 200);
3064
+ },
3065
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
3066
+ const scope = open(namespace);
3067
+ if (!scope.ok)
3068
+ return fromResult(scope, 200);
3069
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
3070
+ if (removed.ok)
3071
+ wrote(namespace);
3072
+ return fromResult(removed, 200);
3073
+ }
3074
+ };
3075
+ };
3076
+
1711
3077
  // ../core/dist/version.js
1712
- var PACKAGE_VERSION = true ? "1.2.0" : UNRELEASED_VERSION;
3078
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1713
3079
 
1714
3080
  // ../core/dist/signing.js
1715
3081
  var encoder = new TextEncoder();
@@ -2044,11 +3410,11 @@ var createWebhookHub = (options) => {
2044
3410
  };
2045
3411
  return hub;
2046
3412
  };
2047
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2048
- var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2049
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3413
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3414
+ var adminError3 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
3415
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2050
3416
  var parseEndpoint = (value) => {
2051
- if (!isRecord3(value) || typeof value.url !== "string")
3417
+ if (!isRecord4(value) || typeof value.url !== "string")
2052
3418
  return "each endpoint needs a url";
2053
3419
  try {
2054
3420
  new URL(value.url);
@@ -2065,18 +3431,18 @@ var parseEndpoint = (value) => {
2065
3431
  const events = value.events ?? value.enabledEvents;
2066
3432
  if (Array.isArray(events))
2067
3433
  endpoint.events = events.map(String);
2068
- if (isRecord3(value.tags)) {
3434
+ if (isRecord4(value.tags)) {
2069
3435
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
2070
3436
  }
2071
3437
  if (typeof value.account === "string")
2072
3438
  endpoint.tags = { ...endpoint.tags, account: value.account };
2073
- if (isRecord3(value.headers)) {
3439
+ if (isRecord4(value.headers)) {
2074
3440
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
2075
3441
  }
2076
3442
  return endpoint;
2077
3443
  };
2078
3444
  var webhookAdminRoutes = (hub) => ({
2079
- "GET /webhooks": ({ url, namespace }) => json3(200, {
3445
+ "GET /webhooks": ({ url, namespace }) => json5(200, {
2080
3446
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
2081
3447
  const type = url.searchParams.get("type");
2082
3448
  return type === null || d.type === type;
@@ -2084,51 +3450,51 @@ var webhookAdminRoutes = (hub) => ({
2084
3450
  }),
2085
3451
  "GET /webhooks/events": ({ url, namespace }) => {
2086
3452
  const type = url.searchParams.get("type");
2087
- return json3(200, {
3453
+ return json5(200, {
2088
3454
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
2089
3455
  });
2090
3456
  },
2091
3457
  "POST /webhooks/:id/replay": async ({ params }) => {
2092
3458
  const replayed = await hub.replay(params.id);
2093
- return replayed ? json3(200, replayed) : adminError2(404, `no delivery ${params.id}`);
3459
+ return replayed ? json5(200, replayed) : adminError3(404, `no delivery ${params.id}`);
2094
3460
  },
2095
3461
  "POST /webhooks/flush": async () => {
2096
3462
  await hub.flush();
2097
- return json3(200, { status: "ok" });
3463
+ return json5(200, { status: "ok" });
2098
3464
  },
2099
3465
  "POST /webhooks/faults": ({ body, namespace }) => {
2100
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2101
- return adminError2(400, "mode must be duplicate, reorder or drop");
3466
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3467
+ return adminError3(400, "mode must be duplicate, reorder or drop");
2102
3468
  }
2103
3469
  const fault = { mode: body.mode };
2104
3470
  if (typeof body.count === "number")
2105
3471
  fault.count = body.count;
2106
3472
  hub.fault(namespace, fault);
2107
- return json3(201, { namespace, ...fault });
3473
+ return json5(201, { namespace, ...fault });
2108
3474
  },
2109
- "GET /webhook-endpoints": ({ namespace }) => json3(200, {
3475
+ "GET /webhook-endpoints": ({ namespace }) => json5(200, {
2110
3476
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
2111
3477
  ...rest,
2112
3478
  secret: secret ? "(set)" : null
2113
3479
  }))
2114
3480
  }),
2115
3481
  "PUT /webhook-endpoints": ({ body, namespace }) => {
2116
- const list2 = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
3482
+ const list2 = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
2117
3483
  if (!Array.isArray(list2))
2118
- return adminError2(400, "expected [{url, secret?, events?}]");
3484
+ return adminError3(400, "expected [{url, secret?, events?}]");
2119
3485
  const parsed = [];
2120
3486
  for (const each of list2) {
2121
3487
  const endpoint = parseEndpoint(each);
2122
3488
  if (typeof endpoint === "string")
2123
- return adminError2(400, endpoint);
3489
+ return adminError3(400, endpoint);
2124
3490
  parsed.push(endpoint);
2125
3491
  }
2126
3492
  const set = hub.setEndpoints(namespace, parsed);
2127
- return json3(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3493
+ return json5(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2128
3494
  },
2129
3495
  "DELETE /webhook-endpoints": ({ namespace }) => {
2130
3496
  hub.setEndpoints(namespace, []);
2131
- return json3(200, { status: "ok" });
3497
+ return json5(200, { status: "ok" });
2132
3498
  }
2133
3499
  });
2134
3500
  var parsePayload = (message) => {
@@ -2191,6 +3557,7 @@ var operationMatcher = (document2) => {
2191
3557
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
2192
3558
  };
2193
3559
  var createRuntime = (options) => {
3560
+ assertAdminUi(options.adminUi);
2194
3561
  const sqlite = bootSqlite(options.sqlite);
2195
3562
  const clock = options.clock ?? createClock();
2196
3563
  const rng = createRng(options.seed ?? 0);
@@ -2397,6 +3764,19 @@ var createRuntime = (options) => {
2397
3764
  else
2398
3765
  timeline(name);
2399
3766
  };
3767
+ const declarationsFor = (namespace) => {
3768
+ const declared = options.state;
3769
+ if (!declared)
3770
+ return [];
3771
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3772
+ };
3773
+ const stateScope = (namespace) => ({
3774
+ sqlite,
3775
+ namespace,
3776
+ storageNamespace: storageNamespace(namespace),
3777
+ root: instance(namespace),
3778
+ declarations: declarationsFor(namespace)
3779
+ });
2400
3780
  const runtime = {
2401
3781
  name: options.name,
2402
3782
  sqlite,
@@ -2435,6 +3815,7 @@ var createRuntime = (options) => {
2435
3815
  branch,
2436
3816
  checkout,
2437
3817
  timeline,
3818
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
2438
3819
  fetch: async (incoming) => {
2439
3820
  let request = incoming;
2440
3821
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2628,11 +4009,20 @@ var createRuntime = (options) => {
2628
4009
  ...credentialRoutes(credentials),
2629
4010
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2630
4011
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2631
- ...options.admin?.(runtime) ?? {}
4012
+ ...options.admin?.(runtime) ?? {},
4013
+ // Standard state and UI routes win a colliding key. A service adds its own keys
4014
+ // beside these; it does not replace `/state` or `/ui`.
4015
+ ...stateAdminRoutes({
4016
+ open: stateScope,
4017
+ afterWrite: (namespace) => {
4018
+ checkpoint(namespace, "main");
4019
+ }
4020
+ }),
4021
+ ...adminUiRoutes(options.name, options.adminUi)
2632
4022
  },
2633
4023
  adminKey: options.adminKey
2634
4024
  });
2635
- return runtime;
4025
+ return defineMock(runtime);
2636
4026
  };
2637
4027
  var mutableResponse = (response) => {
2638
4028
  try {
@@ -2854,12 +4244,12 @@ var forwardToInbox = async (target, email, namespace) => {
2854
4244
  await response.body?.cancel();
2855
4245
  return response.ok;
2856
4246
  };
2857
- var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2858
- var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2859
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4247
+ var json6 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4248
+ var adminError4 = (status, message) => json6(status, { error: { type: "mockingbird_admin", message } });
4249
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2860
4250
  var isAddressList = (value) => typeof value === "string" || Array.isArray(value) && value.every((v) => typeof v === "string");
2861
4251
  var inboundInput = (body) => {
2862
- if (!isRecord4(body)) return "expected a JSON object";
4252
+ if (!isRecord5(body)) return "expected a JSON object";
2863
4253
  if (typeof body.from !== "string" || body.from === "") return "from: the sender address";
2864
4254
  if (!isAddressList(body.to) || Array.isArray(body.to) && body.to.length === 0) {
2865
4255
  return "to: a recipient address or a non-empty list of them";
@@ -2872,10 +4262,10 @@ var inboundInput = (body) => {
2872
4262
  return `${key}: a string`;
2873
4263
  }
2874
4264
  }
2875
- if (body.headers !== void 0 && !isRecord4(body.headers)) return "headers: {name: value}";
4265
+ if (body.headers !== void 0 && !isRecord5(body.headers)) return "headers: {name: value}";
2876
4266
  if (body.attachments !== void 0) {
2877
4267
  if (!Array.isArray(body.attachments) || body.attachments.some(
2878
- (a) => !isRecord4(a) || typeof a.filename !== "string" || typeof a.content !== "string"
4268
+ (a) => !isRecord5(a) || typeof a.filename !== "string" || typeof a.content !== "string"
2879
4269
  )) {
2880
4270
  return "attachments: [{filename, content (base64), contentType?, contentId?}]";
2881
4271
  }
@@ -2899,13 +4289,13 @@ var adminRoutes = (hub) => (runtime) => ({
2899
4289
  ),
2900
4290
  "GET /outbox/:id/links": ({ params, namespace }) => {
2901
4291
  const email = runtime.instance(namespace).state.outbox.get(params.id);
2902
- if (!email) return adminError3(404, `no email ${params.id}`);
4292
+ if (!email) return adminError4(404, `no email ${params.id}`);
2903
4293
  const links = email.html ? extractLinks(email.html) : [...(email.text ?? "").matchAll(/\bhttps?:\/\/[^\s<>"')\]]+/g)].map((m) => m[0]);
2904
- return json4(200, { id: email.id, links });
4294
+ return json6(200, { id: email.id, links });
2905
4295
  },
2906
4296
  "POST /inbound": ({ body, namespace, url }) => {
2907
4297
  const input = inboundInput(body);
2908
- if (typeof input === "string") return adminError3(400, input);
4298
+ if (typeof input === "string") return adminError4(400, input);
2909
4299
  const { email, event } = runtime.instance(namespace).receive(input, url.origin);
2910
4300
  const message = hub.publish({
2911
4301
  namespace,
@@ -2913,9 +4303,9 @@ var adminRoutes = (hub) => (runtime) => ({
2913
4303
  body: event,
2914
4304
  id: `msg_${email.id.replace(/-/g, "")}`
2915
4305
  });
2916
- return json4(201, { id: email.id, webhook: message.id, event });
4306
+ return json6(201, { id: email.id, webhook: message.id, event });
2917
4307
  },
2918
- "GET /inbound": ({ namespace }) => json4(200, { emails: runtime.instance(namespace).inbound() })
4308
+ "GET /inbound": ({ namespace }) => json6(200, { emails: runtime.instance(namespace).inbound() })
2919
4309
  });
2920
4310
  var createRuntime2 = (options = {}) => {
2921
4311
  const { retryDelaysMs, fetch: send, ...endpoint } = options.webhooks ?? { url: "" };
@@ -2964,7 +4354,7 @@ var createRuntime2 = (options = {}) => {
2964
4354
  }),
2965
4355
  admin: (base) => ({
2966
4356
  ...adminRoutes(hub)(base),
2967
- "GET /forwarding": () => json4(200, { target: target?.url ?? null, ...stats })
4357
+ "GET /forwarding": () => json6(200, { target: target?.url ?? null, ...stats })
2968
4358
  })
2969
4359
  });
2970
4360
  return Object.assign(runtime, { webhooks: hub, forwarding: () => ({ ...stats }) });
@@ -3314,4 +4704,4 @@ export {
3314
4704
  bareAddress,
3315
4705
  ResendAPI
3316
4706
  };
3317
- //# sourceMappingURL=chunk-7FXSQV6B.js.map
4707
+ //# sourceMappingURL=chunk-EBT2U6V2.js.map