@crvouga/mockingbird-service-intercom 1.4.0 → 1.5.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 matches3 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
801
803
  if (matches3 !== 1)
802
- fail(`matches ${matches3} oneOf branches, expected exactly 1`);
804
+ fail2(`matches ${matches3} 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
 
@@ -1442,6 +1444,936 @@ var clearNamespace = (sqlite, namespace) => {
1442
1444
  });
1443
1445
  };
1444
1446
 
1447
+ // ../core/dist/surface.js
1448
+ var defineMock = (runtime) => runtime;
1449
+ var STANDARD_ADMIN_ROUTES = [
1450
+ "GET /",
1451
+ "POST /reset",
1452
+ "GET /namespaces",
1453
+ "GET /clock",
1454
+ "POST /clock",
1455
+ "GET /faults",
1456
+ "POST /faults",
1457
+ "DELETE /faults",
1458
+ "POST /snapshots",
1459
+ "POST /snapshots/:id/restore",
1460
+ "DELETE /snapshots/:id",
1461
+ "GET /timeline",
1462
+ "POST /checkpoints",
1463
+ "POST /branches/:name",
1464
+ "POST /branches/:name/checkout",
1465
+ "GET /requests",
1466
+ "DELETE /requests",
1467
+ "GET /metrics",
1468
+ "DELETE /metrics",
1469
+ "GET /credentials",
1470
+ "PUT /credentials",
1471
+ "DELETE /credentials",
1472
+ "GET /state",
1473
+ "GET /state/:collection",
1474
+ "GET /state/:collection/:id",
1475
+ "POST /state/:collection",
1476
+ "PUT /state/:collection/:id",
1477
+ "PATCH /state/:collection/:id",
1478
+ "DELETE /state/:collection/:id",
1479
+ "GET /ui",
1480
+ "GET /ui/",
1481
+ "GET /ui/manifest"
1482
+ ];
1483
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1484
+ var assertAdminUi = (ui) => {
1485
+ if (!ui?.panels)
1486
+ return;
1487
+ const seen = /* @__PURE__ */ new Set();
1488
+ for (const panel of ui.panels) {
1489
+ if (!PANEL_ID.test(panel.id)) {
1490
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1491
+ }
1492
+ if (seen.has(panel.id))
1493
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1494
+ seen.add(panel.id);
1495
+ if (panel.title.trim() === "")
1496
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1497
+ }
1498
+ };
1499
+
1500
+ // ../core/dist/admin-ui.js
1501
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1502
+ switch (char) {
1503
+ case "&":
1504
+ return "&amp;";
1505
+ case "<":
1506
+ return "&lt;";
1507
+ case ">":
1508
+ return "&gt;";
1509
+ case '"':
1510
+ return "&quot;";
1511
+ default:
1512
+ return "&#39;";
1513
+ }
1514
+ });
1515
+ var renderAdminDocument = (service) => {
1516
+ const name = escapeHtml(service);
1517
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1518
+ return `<!DOCTYPE html>
1519
+ <html lang="en">
1520
+ <head>
1521
+ <meta charset="utf-8">
1522
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1523
+ <meta name="color-scheme" content="light dark">
1524
+ <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">
1525
+ <title>${name} admin</title>
1526
+ <style>
1527
+ :root {
1528
+ color-scheme: light;
1529
+ --bg: #f6f5f2;
1530
+ --bg-elev: #ffffff;
1531
+ --bg-muted: #eeece6;
1532
+ --bg-inset: #f3f1eb;
1533
+ --line: #e2dfd6;
1534
+ --line-strong: #d0ccc1;
1535
+ --ink: #1c1915;
1536
+ --muted: #5e584f;
1537
+ --faint: #8a8378;
1538
+ --accent: #3d4f3a;
1539
+ --accent-ink: #f7f6f2;
1540
+ --accent-soft: #e5ece2;
1541
+ --ok: #1f7a45;
1542
+ --ok-soft: #e5f4eb;
1543
+ --warn: #9a6700;
1544
+ --warn-soft: #fbf3df;
1545
+ --err: #a33b32;
1546
+ --err-soft: #fdecea;
1547
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1548
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1549
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1550
+ --radius: 14px;
1551
+ --header: 60px;
1552
+ --nav: 220px;
1553
+ }
1554
+ :root[data-theme="dark"] {
1555
+ color-scheme: dark;
1556
+ --bg: #141311;
1557
+ --bg-elev: #1e1c19;
1558
+ --bg-muted: #26231f;
1559
+ --bg-inset: #181715;
1560
+ --line: #34302b;
1561
+ --line-strong: #4a453d;
1562
+ --ink: #f4f1ea;
1563
+ --muted: #c4bdb1;
1564
+ --faint: #8f877c;
1565
+ --accent: #c5d5b8;
1566
+ --accent-ink: #1a2118;
1567
+ --accent-soft: #2a3328;
1568
+ --ok: #8fd6a8;
1569
+ --ok-soft: #1a2e22;
1570
+ --warn: #f0cc78;
1571
+ --warn-soft: #332911;
1572
+ --err: #f0a8a2;
1573
+ --err-soft: #3a201e;
1574
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1575
+ }
1576
+ @media (prefers-color-scheme: dark) {
1577
+ :root:not([data-theme="light"]) {
1578
+ color-scheme: dark;
1579
+ --bg: #141311;
1580
+ --bg-elev: #1e1c19;
1581
+ --bg-muted: #26231f;
1582
+ --bg-inset: #181715;
1583
+ --line: #34302b;
1584
+ --line-strong: #4a453d;
1585
+ --ink: #f4f1ea;
1586
+ --muted: #c4bdb1;
1587
+ --faint: #8f877c;
1588
+ --accent: #c5d5b8;
1589
+ --accent-ink: #1a2118;
1590
+ --accent-soft: #2a3328;
1591
+ --ok: #8fd6a8;
1592
+ --ok-soft: #1a2e22;
1593
+ --warn: #f0cc78;
1594
+ --warn-soft: #332911;
1595
+ --err: #f0a8a2;
1596
+ --err-soft: #3a201e;
1597
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1598
+ }
1599
+ }
1600
+ * { box-sizing: border-box; }
1601
+ html, body { margin: 0; height: 100%; }
1602
+ body {
1603
+ font-family: var(--sans);
1604
+ background: var(--bg);
1605
+ color: var(--ink);
1606
+ line-height: 1.45;
1607
+ padding-left: env(safe-area-inset-left);
1608
+ padding-right: env(safe-area-inset-right);
1609
+ -webkit-text-size-adjust: 100%;
1610
+ }
1611
+ button, input, select, textarea { font: inherit; color: inherit; }
1612
+ button { cursor: pointer; }
1613
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1614
+ @media (prefers-reduced-motion: reduce) {
1615
+ * { scroll-behavior: auto !important; transition: none !important; }
1616
+ }
1617
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1618
+ header.top {
1619
+ position: sticky; top: 0; z-index: 5;
1620
+ display: flex; align-items: center; gap: 12px;
1621
+ min-height: var(--header); padding: 10px 16px;
1622
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1623
+ border-bottom: 1px solid var(--line);
1624
+ backdrop-filter: blur(10px);
1625
+ }
1626
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1627
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1628
+ .brand span { color: var(--faint); font-size: 12px; }
1629
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1630
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1631
+ label.field input, label.field select, .controls input[type="password"] {
1632
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1633
+ padding: 7px 8px; min-height: 36px;
1634
+ }
1635
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1636
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1637
+ background: var(--bg-elev);
1638
+ }
1639
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1640
+ .btn-quiet { background: transparent; }
1641
+ .btn-danger { color: var(--err); }
1642
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1643
+ record or the full nav row would widen the page past the viewport. */
1644
+ .layout {
1645
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1646
+ flex: 1; min-height: 0; min-width: 0;
1647
+ }
1648
+ nav.side {
1649
+ border-right: 1px solid var(--line); padding: 12px;
1650
+ display: flex; flex-direction: column; gap: 4px;
1651
+ background: var(--bg-elev);
1652
+ }
1653
+ nav.side button {
1654
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1655
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1656
+ }
1657
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1658
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1659
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1660
+ .lede { margin: 0 0 16px; color: var(--muted); }
1661
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1662
+ .card {
1663
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1664
+ padding: 14px 16px; box-shadow: var(--shadow);
1665
+ }
1666
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1667
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1668
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1669
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1670
+ .collection {
1671
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1672
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1673
+ }
1674
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1675
+ .collection small { display: block; color: var(--faint); }
1676
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1677
+ .chip {
1678
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1679
+ border-radius: 999px; padding: 4px 8px;
1680
+ }
1681
+ .chip i { color: var(--faint); font-style: normal; }
1682
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1683
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1684
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1685
+ tr.clickable { cursor: pointer; }
1686
+ tr.clickable:hover { background: var(--bg-muted); }
1687
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1688
+ pre {
1689
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1690
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1691
+ }
1692
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1693
+ .banner {
1694
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1695
+ background: var(--err-soft); color: var(--err);
1696
+ }
1697
+ .banner.show { display: block; }
1698
+ .empty { color: var(--muted); padding: 24px 8px; }
1699
+ dialog {
1700
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1701
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1702
+ }
1703
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1704
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1705
+ textarea {
1706
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1707
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1708
+ font-family: var(--mono); font-size: 12px;
1709
+ }
1710
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1711
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1712
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1713
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1714
+ .status-2 { color: var(--ok); }
1715
+ .status-4, .status-5, .status-0 { color: var(--err); }
1716
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1717
+ .route {
1718
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1719
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1720
+ }
1721
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1722
+ @media (max-width: 800px) {
1723
+ header.top {
1724
+ align-items: stretch; flex-direction: column;
1725
+ padding-top: max(10px, env(safe-area-inset-top));
1726
+ }
1727
+ input, select, textarea { font-size: 16px; }
1728
+ .controls { width: 100%; }
1729
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1730
+ .layout { grid-template-columns: minmax(0, 1fr); }
1731
+ nav.side {
1732
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1733
+ border-right: 0; border-bottom: 1px solid var(--line);
1734
+ padding: 8px;
1735
+ }
1736
+ nav.side button { white-space: nowrap; flex: none; }
1737
+ .split { grid-template-columns: minmax(0, 1fr); }
1738
+ main { padding: 14px; }
1739
+ table, thead, tbody, tr, th, td { display: block; }
1740
+ thead { display: none; }
1741
+ tr {
1742
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1743
+ background: var(--bg-elev); min-width: 0;
1744
+ }
1745
+ td {
1746
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1747
+ min-width: 0; overflow-wrap: anywhere;
1748
+ }
1749
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1750
+ .route { grid-template-columns: 72px 1fr; }
1751
+ .route button { grid-column: 1 / -1; }
1752
+ }
1753
+ </style>
1754
+ </head>
1755
+ <body>
1756
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1757
+ <header class="top">
1758
+ <div class="brand">
1759
+ <strong>${name}</strong>
1760
+ <span>Mockingbird admin</span>
1761
+ </div>
1762
+ <div class="controls">
1763
+ <label class="field">Namespace
1764
+ <select id="namespace" aria-label="Namespace"></select>
1765
+ </label>
1766
+ <label class="field">Admin key
1767
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1768
+ </label>
1769
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1770
+ <button class="btn" id="refresh" type="button">Refresh</button>
1771
+ </div>
1772
+ </header>
1773
+ <div class="layout">
1774
+ <nav class="side" id="nav" aria-label="Admin sections">
1775
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1776
+ <button type="button" data-view="state">State</button>
1777
+ <button type="button" data-view="clock">Clock</button>
1778
+ <button type="button" data-view="faults">Faults</button>
1779
+ <button type="button" data-view="journal">Journal</button>
1780
+ <button type="button" data-view="routes">Routes</button>
1781
+ </nav>
1782
+ <main id="views">
1783
+ <p class="banner" id="banner" role="alert"></p>
1784
+ <section class="view" id="view-overview">
1785
+ <h2>Overview</h2>
1786
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1787
+ <div class="grid" id="overview-cards"></div>
1788
+ <h3>Recent requests</h3>
1789
+ <div id="overview-requests"></div>
1790
+ </section>
1791
+ <section class="view" id="view-state" hidden>
1792
+ <h2>State</h2>
1793
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1794
+ <div class="split">
1795
+ <div id="collections"></div>
1796
+ <div>
1797
+ <div id="schema"></div>
1798
+ <div class="row-actions">
1799
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1800
+ </div>
1801
+ <div id="records"></div>
1802
+ </div>
1803
+ </div>
1804
+ </section>
1805
+ <section class="view" id="view-clock" hidden>
1806
+ <h2>Clock</h2>
1807
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1808
+ <div class="card" id="clock-readout"></div>
1809
+ <div class="row-actions">
1810
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1811
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1812
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1813
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1814
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1815
+ <button class="btn" id="freeze" type="button">Freeze</button>
1816
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1817
+ </div>
1818
+ <form id="clock-set" class="row-actions">
1819
+ <label class="field">Set instant
1820
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1821
+ </label>
1822
+ <button class="btn-primary" type="submit">Set</button>
1823
+ </form>
1824
+ </section>
1825
+ <section class="view" id="view-faults" hidden>
1826
+ <h2>Faults</h2>
1827
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1828
+ <form id="fault-form" class="card stack">
1829
+ <label class="field">Preset
1830
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1831
+ </label>
1832
+ <label class="field">Status
1833
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1834
+ </label>
1835
+ <label class="field">Path prefix
1836
+ <input id="fault-path" placeholder="/v1">
1837
+ </label>
1838
+ <label class="field">Method
1839
+ <input id="fault-method" placeholder="GET">
1840
+ </label>
1841
+ <div class="dialog-actions">
1842
+ <button class="btn-primary" type="submit">Add fault</button>
1843
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1844
+ </div>
1845
+ </form>
1846
+ <div id="fault-list"></div>
1847
+ </section>
1848
+ <section class="view" id="view-journal" hidden>
1849
+ <h2>Journal</h2>
1850
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1851
+ <div class="row-actions">
1852
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1853
+ </div>
1854
+ <div id="journal"></div>
1855
+ </section>
1856
+ <section class="view" id="view-routes" hidden>
1857
+ <h2>Routes</h2>
1858
+ <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>
1859
+ <div id="route-list"></div>
1860
+ <form id="route-form" class="card stack">
1861
+ <strong id="route-title">Select a route</strong>
1862
+ <label class="field">JSON body
1863
+ <textarea id="route-body" placeholder="{ }"></textarea>
1864
+ </label>
1865
+ <div class="dialog-actions">
1866
+ <button class="btn-primary" type="submit">Send</button>
1867
+ </div>
1868
+ <pre id="route-result">Response will show here.</pre>
1869
+ </form>
1870
+ </section>
1871
+ </main>
1872
+ </div>
1873
+ </div>
1874
+ <dialog id="editor">
1875
+ <form method="dialog" id="editor-form">
1876
+ <strong id="editor-title">Record</strong>
1877
+ <label class="field">Id
1878
+ <input id="editor-id" required>
1879
+ </label>
1880
+ <label class="field">JSON value
1881
+ <textarea id="editor-value"></textarea>
1882
+ </label>
1883
+ <div class="dialog-actions">
1884
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1885
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1886
+ <button class="btn-primary" type="submit" value="save">Save</button>
1887
+ </div>
1888
+ </form>
1889
+ </dialog>
1890
+ <script>
1891
+ (() => {
1892
+ const STANDARD = new Set(${standard})
1893
+ const state = {
1894
+ namespace: "default",
1895
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1896
+ view: "overview",
1897
+ collection: "",
1898
+ shape: null,
1899
+ route: null,
1900
+ editing: null
1901
+ }
1902
+ const $ = (id) => document.getElementById(id)
1903
+ const banner = $("banner")
1904
+ const keyInput = $("admin-key")
1905
+ keyInput.value = state.key
1906
+ const params = new URLSearchParams(location.search)
1907
+ if (params.get("key")) {
1908
+ state.key = params.get("key")
1909
+ keyInput.value = state.key
1910
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1911
+ params.delete("key")
1912
+ const next = params.toString()
1913
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1914
+ }
1915
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1916
+
1917
+ const showError = (error) => {
1918
+ banner.textContent = error instanceof Error ? error.message : String(error)
1919
+ banner.classList.add("show")
1920
+ }
1921
+ const clearError = () => banner.classList.remove("show")
1922
+
1923
+ async function originGet(path) {
1924
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1925
+ if (!response.ok) throw new Error(response.status + " " + path)
1926
+ return response.json()
1927
+ }
1928
+ async function api(method, path, body) {
1929
+ const headers = { accept: "application/json" }
1930
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1931
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1932
+ if (body !== undefined) headers["content-type"] = "application/json"
1933
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1934
+ method,
1935
+ headers,
1936
+ body: body === undefined ? undefined : JSON.stringify(body)
1937
+ })
1938
+ const text = await response.text()
1939
+ let data = null
1940
+ if (text) {
1941
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1942
+ }
1943
+ if (response.status === 401) {
1944
+ keyInput.focus()
1945
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1946
+ }
1947
+ if (!response.ok) {
1948
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1949
+ }
1950
+ return data
1951
+ }
1952
+ const panelApi = {
1953
+ get: (path) => api("GET", path),
1954
+ send: (method, path, body) => api(method, path, body),
1955
+ namespace: () => state.namespace
1956
+ }
1957
+
1958
+ function setTheme(theme) {
1959
+ if (theme) document.documentElement.dataset.theme = theme
1960
+ else delete document.documentElement.dataset.theme
1961
+ }
1962
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1963
+ if (storedTheme) setTheme(storedTheme)
1964
+ $("theme").addEventListener("click", () => {
1965
+ const current = document.documentElement.dataset.theme
1966
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1967
+ const next = dark ? "light" : "dark"
1968
+ localStorage.setItem("mockingbird-admin-theme", next)
1969
+ setTheme(next)
1970
+ })
1971
+
1972
+ function show(view) {
1973
+ state.view = view
1974
+ for (const button of document.querySelectorAll("#nav button")) {
1975
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1976
+ }
1977
+ for (const section of document.querySelectorAll("main .view")) {
1978
+ section.hidden = section.id !== "view-" + view
1979
+ }
1980
+ }
1981
+ document.getElementById("nav").addEventListener("click", (event) => {
1982
+ const button = event.target.closest("button[data-view]")
1983
+ if (!button) return
1984
+ show(button.dataset.view)
1985
+ refresh().catch(showError)
1986
+ })
1987
+
1988
+ function cards(items) {
1989
+ return '<div class="grid">' + items.map((item) =>
1990
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1991
+ ).join("") + "</div>"
1992
+ }
1993
+ function table(columns, rows) {
1994
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1995
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1996
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1997
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1998
+ ).join("") + "</tr>").join("")
1999
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
2000
+ }
2001
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
2002
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
2003
+ }[char]))
2004
+ const preview = (value) => {
2005
+ const text = JSON.stringify(value)
2006
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
2007
+ }
2008
+ const when = (epoch) => {
2009
+ const date = new Date(epoch)
2010
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
2011
+ }
2012
+ const clockCard = (epoch) => {
2013
+ const date = new Date(epoch)
2014
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
2015
+ const iso = date.toISOString()
2016
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
2017
+ }
2018
+
2019
+ async function loadNamespaces() {
2020
+ const data = await api("GET", "/namespaces")
2021
+ const select = $("namespace")
2022
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
2023
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
2024
+ select.innerHTML = names.map((name) =>
2025
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
2026
+ ).join("")
2027
+ select.value = state.namespace
2028
+ }
2029
+
2030
+ async function renderOverview() {
2031
+ const [health, shape, clock, journal] = await Promise.all([
2032
+ originGet("/health"),
2033
+ api("GET", "/state"),
2034
+ api("GET", "/clock"),
2035
+ api("GET", "/requests?limit=8")
2036
+ ])
2037
+ state.shape = shape
2038
+ $("overview-cards").innerHTML = cards([
2039
+ { k: "Service", v: esc(health.service || "${name}") },
2040
+ { k: "Status", v: esc(health.status || "ok") },
2041
+ { k: "Namespace", v: esc(state.namespace) },
2042
+ { k: "Collections", v: String(shape.collections.length) },
2043
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
2044
+ { k: "Clock", v: clockCard(clock.now) }
2045
+ ])
2046
+ const requests = (journal && journal.requests) || []
2047
+ $("overview-requests").innerHTML = table(
2048
+ [
2049
+ { label: "Method", cell: (row) => esc(row.method) },
2050
+ { label: "Path", cell: (row) => esc(row.path) },
2051
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
2052
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
2053
+ ],
2054
+ requests
2055
+ )
2056
+ }
2057
+
2058
+ function schemaChips(collection) {
2059
+ if (!collection || collection.fields.length === 0) {
2060
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
2061
+ }
2062
+ return '<div class="chips">' + collection.fields.map((field) =>
2063
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
2064
+ ).join("") + "</div>"
2065
+ }
2066
+
2067
+ async function renderState() {
2068
+ const shape = await api("GET", "/state")
2069
+ state.shape = shape
2070
+ const host = $("collections")
2071
+ if (shape.collections.length === 0) {
2072
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
2073
+ $("schema").innerHTML = ""
2074
+ $("records").innerHTML = ""
2075
+ return
2076
+ }
2077
+ if (!shape.collections.some((item) => item.name === state.collection)) {
2078
+ state.collection = shape.collections[0].name
2079
+ }
2080
+ host.innerHTML = shape.collections.map((item) =>
2081
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
2082
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
2083
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
2084
+ ).join("")
2085
+ const selected = shape.collections.find((item) => item.name === state.collection)
2086
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
2087
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
2088
+ schemaChips(selected)
2089
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
2090
+ const rows = page.records.map((record) => ({
2091
+ ...record,
2092
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
2093
+ }))
2094
+ $("records").innerHTML = table(
2095
+ [
2096
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
2097
+ { label: "Seq", cell: (row) => esc(row.seq) },
2098
+ { label: "Value", cell: (row) => preview(row.value) }
2099
+ ],
2100
+ rows
2101
+ )
2102
+ }
2103
+
2104
+ async function renderClock() {
2105
+ const clock = await api("GET", "/clock")
2106
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
2107
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
2108
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
2109
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
2110
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
2111
+ }
2112
+
2113
+ async function renderFaults() {
2114
+ const [faults, presets] = await Promise.all([
2115
+ api("GET", "/faults"),
2116
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2117
+ ])
2118
+ const select = $("fault-preset")
2119
+ const current = select.value
2120
+ const list = presets.presets || []
2121
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
2122
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
2123
+ ).join("")
2124
+ select.value = current
2125
+ const rules = faults.faults || []
2126
+ $("fault-list").innerHTML = table(
2127
+ [
2128
+ { label: "Id", cell: (row) => esc(row.id) },
2129
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
2130
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
2131
+ ],
2132
+ rules
2133
+ )
2134
+ }
2135
+
2136
+ async function renderJournal() {
2137
+ const journal = await api("GET", "/requests?limit=100")
2138
+ $("journal").innerHTML = table(
2139
+ [
2140
+ { label: "When", cell: (row) => esc(row.at || "") },
2141
+ { label: "Method", cell: (row) => esc(row.method) },
2142
+ { label: "Path", cell: (row) => esc(row.path) },
2143
+ { label: "Status", cell: (row) => esc(row.status) },
2144
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2145
+ ],
2146
+ journal.requests || []
2147
+ )
2148
+ }
2149
+
2150
+ async function renderRoutes() {
2151
+ const data = await api("GET", "/")
2152
+ const routes = data.routes || []
2153
+ $("route-list").innerHTML = routes.map((route) => {
2154
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
2155
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
2156
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
2157
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
2158
+ }).join("")
2159
+ }
2160
+
2161
+ const renderers = {
2162
+ overview: renderOverview,
2163
+ state: renderState,
2164
+ clock: renderClock,
2165
+ faults: renderFaults,
2166
+ journal: renderJournal,
2167
+ routes: renderRoutes
2168
+ }
2169
+
2170
+ async function refresh() {
2171
+ clearError()
2172
+ if (state.view in renderers) await renderers[state.view]()
2173
+ }
2174
+
2175
+ $("namespace").addEventListener("change", () => {
2176
+ state.namespace = $("namespace").value
2177
+ refresh().catch(showError)
2178
+ })
2179
+ keyInput.addEventListener("change", () => {
2180
+ state.key = keyInput.value.trim()
2181
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
2182
+ refresh().catch(showError)
2183
+ })
2184
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
2185
+
2186
+ $("collections").addEventListener("click", (event) => {
2187
+ const button = event.target.closest("[data-collection]")
2188
+ if (!button) return
2189
+ state.collection = button.dataset.collection
2190
+ renderState().catch(showError)
2191
+ })
2192
+ $("records").addEventListener("click", (event) => {
2193
+ const row = event.target.closest("[data-id]")
2194
+ if (!row) return
2195
+ openEditor(row.dataset.id).catch(showError)
2196
+ })
2197
+
2198
+ const editor = $("editor")
2199
+ async function openEditor(id) {
2200
+ state.editing = id || null
2201
+ $("editor-title").textContent = id ? "Edit record" : "New record"
2202
+ $("editor-id").value = id || ""
2203
+ $("editor-id").readOnly = Boolean(id)
2204
+ $("editor-delete").hidden = !id
2205
+ if (id) {
2206
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2207
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
2208
+ } else {
2209
+ $("editor-value").value = "{\\n \\n}"
2210
+ }
2211
+ editor.showModal()
2212
+ }
2213
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
2214
+ $("editor-form").addEventListener("submit", (event) => {
2215
+ const submitter = event.submitter
2216
+ if (!submitter || submitter.value !== "save") return
2217
+ event.preventDefault()
2218
+ let value
2219
+ try { value = JSON.parse($("editor-value").value) }
2220
+ catch { showError(new Error("Value is not JSON")); return }
2221
+ const id = $("editor-id").value.trim()
2222
+ const path = "/state/" + encodeURIComponent(state.collection)
2223
+ const request = state.editing
2224
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
2225
+ : api("POST", path, { id: id || undefined, value })
2226
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
2227
+ })
2228
+ $("editor-delete").addEventListener("click", () => {
2229
+ const id = state.editing
2230
+ if (!id) return
2231
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2232
+ .then(() => { editor.close(); return renderState() })
2233
+ .catch(showError)
2234
+ })
2235
+
2236
+ document.querySelectorAll("[data-advance]").forEach((button) => {
2237
+ button.addEventListener("click", () => {
2238
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
2239
+ })
2240
+ })
2241
+ $("freeze").addEventListener("click", () => {
2242
+ const frozen = $("freeze").dataset.frozen === "1"
2243
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
2244
+ })
2245
+ $("clock-reset").addEventListener("click", () => {
2246
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
2247
+ })
2248
+ $("clock-set").addEventListener("submit", (event) => {
2249
+ event.preventDefault()
2250
+ const raw = $("clock-instant").value.trim()
2251
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
2252
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
2253
+ })
2254
+
2255
+ $("fault-form").addEventListener("submit", (event) => {
2256
+ event.preventDefault()
2257
+ const preset = $("fault-preset").value
2258
+ const body = preset
2259
+ ? { preset }
2260
+ : {
2261
+ status: Number($("fault-status").value),
2262
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
2263
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
2264
+ }
2265
+ if (!preset && !Number.isFinite(body.status)) {
2266
+ showError(new Error("Status must be a number, or choose a preset"))
2267
+ return
2268
+ }
2269
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
2270
+ })
2271
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
2272
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
2273
+
2274
+ $("route-list").addEventListener("click", (event) => {
2275
+ const button = event.target.closest("[data-route]")
2276
+ if (!button) return
2277
+ state.route = button.dataset.route
2278
+ $("route-title").textContent = state.route
2279
+ const method = state.route.split(" ")[0]
2280
+ $("route-body").disabled = method === "GET" || method === "DELETE"
2281
+ })
2282
+ $("route-form").addEventListener("submit", async (event) => {
2283
+ event.preventDefault()
2284
+ if (!state.route) return showError(new Error("Choose a route first"))
2285
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
2286
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
2287
+ let body
2288
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
2289
+ try { body = JSON.parse($("route-body").value) }
2290
+ catch { return showError(new Error("Body is not JSON")) }
2291
+ }
2292
+ try {
2293
+ const data = await api(method, concrete, body)
2294
+ $("route-result").textContent = JSON.stringify(data, null, 2)
2295
+ } catch (error) {
2296
+ showError(error)
2297
+ }
2298
+ })
2299
+
2300
+ function mountPanels(panels) {
2301
+ const nav = $("nav")
2302
+ const views = $("views")
2303
+ for (const panel of panels) {
2304
+ const button = document.createElement("button")
2305
+ button.type = "button"
2306
+ button.dataset.view = panel.id
2307
+ button.textContent = panel.title
2308
+ nav.append(button)
2309
+ const section = document.createElement("section")
2310
+ section.className = "view"
2311
+ section.id = "view-" + panel.id
2312
+ section.hidden = true
2313
+ const title = document.createElement("h2")
2314
+ title.textContent = panel.title
2315
+ const lede = document.createElement("p")
2316
+ lede.className = "lede"
2317
+ lede.textContent = panel.description || ""
2318
+ const body = document.createElement("div")
2319
+ body.className = "panel-body"
2320
+ body.id = "panel-" + panel.id
2321
+ body.innerHTML = panel.html || ""
2322
+ section.append(title, lede, body)
2323
+ views.append(section)
2324
+ if (panel.script) {
2325
+ try {
2326
+ const run = new Function("root", "api", panel.script)
2327
+ run(body, panelApi)
2328
+ } catch (error) {
2329
+ const note = document.createElement("p")
2330
+ note.className = "banner show"
2331
+ note.textContent = error instanceof Error ? error.message : String(error)
2332
+ body.append(note)
2333
+ }
2334
+ }
2335
+ }
2336
+ }
2337
+
2338
+ loadNamespaces()
2339
+ .then(() => api("GET", "/ui/manifest"))
2340
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2341
+ .catch(showError)
2342
+ })()
2343
+ </script>
2344
+ </body>
2345
+ </html>`;
2346
+ };
2347
+ var htmlResponse = (body) => new Response(body, {
2348
+ status: 200,
2349
+ headers: {
2350
+ "content-type": "text/html; charset=utf-8",
2351
+ "cache-control": "no-store"
2352
+ }
2353
+ });
2354
+ var json3 = (body) => new Response(JSON.stringify(body), {
2355
+ status: 200,
2356
+ headers: { "content-type": "application/json; charset=utf-8" }
2357
+ });
2358
+ var adminUiRoutes = (service, ui) => {
2359
+ const shell = () => renderAdminDocument(service);
2360
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2361
+ return {
2362
+ "GET /ui": () => htmlResponse(document2()),
2363
+ "GET /ui/": () => htmlResponse(document2()),
2364
+ "GET /ui/manifest": () => json3({
2365
+ service,
2366
+ panels: (ui?.panels ?? []).map((panel) => ({
2367
+ id: panel.id,
2368
+ title: panel.title,
2369
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2370
+ html: panel.html,
2371
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2372
+ }))
2373
+ })
2374
+ };
2375
+ };
2376
+
1445
2377
  // ../../openapi/metadata/dist/types.js
1446
2378
  var EXTENSION_KEYS = {
1447
2379
  operation: "x-mockingbird",
@@ -1679,8 +2611,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1679
2611
  });
1680
2612
  };
1681
2613
 
2614
+ // ../core/dist/state-view.js
2615
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2616
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2617
+ var SAMPLE = 25;
2618
+ var WALK_LIMIT = 1e4;
2619
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2620
+ var fail = (status, message) => ({ ok: false, status, message });
2621
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2622
+ var kindOf = (value) => {
2623
+ if (value === null)
2624
+ return "null";
2625
+ if (Array.isArray(value))
2626
+ return "array";
2627
+ switch (typeof value) {
2628
+ case "string":
2629
+ return "string";
2630
+ case "number":
2631
+ return Number.isFinite(value) ? "number" : "unknown";
2632
+ case "boolean":
2633
+ return "boolean";
2634
+ case "object":
2635
+ return "object";
2636
+ default:
2637
+ return "unknown";
2638
+ }
2639
+ };
2640
+ var humanize = (name) => {
2641
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2642
+ if (words === "")
2643
+ return name;
2644
+ return words.charAt(0).toUpperCase() + words.slice(1);
2645
+ };
2646
+ var jsonValue = (value) => {
2647
+ if (value === void 0)
2648
+ return fail(400, "value is required");
2649
+ try {
2650
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2651
+ } catch {
2652
+ return fail(400, "value must be JSON");
2653
+ }
2654
+ };
2655
+ var ctorName = (value) => {
2656
+ const ctor = value.constructor;
2657
+ return typeof ctor?.name === "string" ? ctor.name : "";
2658
+ };
2659
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2660
+ var discoverCollections = (root) => {
2661
+ const found = [];
2662
+ const seen = /* @__PURE__ */ new Set();
2663
+ const visit = (value, depth) => {
2664
+ if (found.length + seen.size > WALK_LIMIT)
2665
+ return;
2666
+ if (value === null || typeof value !== "object")
2667
+ return;
2668
+ if (seen.has(value))
2669
+ return;
2670
+ seen.add(value);
2671
+ if (value instanceof Collection) {
2672
+ found.push(value);
2673
+ return;
2674
+ }
2675
+ if (value instanceof Map) {
2676
+ for (const child of value.values())
2677
+ visit(child, depth + 1);
2678
+ return;
2679
+ }
2680
+ if (value instanceof Set) {
2681
+ for (const child of value.values())
2682
+ visit(child, depth + 1);
2683
+ return;
2684
+ }
2685
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2686
+ return;
2687
+ if (Array.isArray(value)) {
2688
+ const cap = Math.min(value.length, 32);
2689
+ for (let i = 0; i < cap; i++)
2690
+ visit(value[i], depth + 1);
2691
+ return;
2692
+ }
2693
+ let children;
2694
+ try {
2695
+ children = Object.values(value);
2696
+ } catch {
2697
+ return;
2698
+ }
2699
+ for (const child of children)
2700
+ visit(child, depth + 1);
2701
+ };
2702
+ visit(root, 0);
2703
+ return found;
2704
+ };
2705
+ var storedNames = (sqlite, namespace) => {
2706
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2707
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2708
+ return [...records, ...sequences].map((row) => row.name);
2709
+ };
2710
+ var blankAccum = (name) => ({
2711
+ name,
2712
+ kinds: /* @__PURE__ */ new Set(),
2713
+ present: 0,
2714
+ nested: /* @__PURE__ */ new Map()
2715
+ });
2716
+ var absorb = (accum, value) => {
2717
+ const kind = kindOf(value);
2718
+ accum.kinds.add(kind);
2719
+ accum.present++;
2720
+ if (!isRecord3(value))
2721
+ return;
2722
+ for (const [key, child] of Object.entries(value)) {
2723
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2724
+ absorb(nested, child);
2725
+ accum.nested.set(key, nested);
2726
+ }
2727
+ };
2728
+ var finishField = (accum, samples) => {
2729
+ const kinds = [...accum.kinds];
2730
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2731
+ const field = {
2732
+ name: accum.name,
2733
+ kind,
2734
+ optional: accum.present < samples || kinds.includes("null")
2735
+ };
2736
+ if (accum.nested.size > 0) {
2737
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2738
+ }
2739
+ return field;
2740
+ };
2741
+ var inferFields = (records) => {
2742
+ if (records.length === 0)
2743
+ return [];
2744
+ const sample = records.slice(0, SAMPLE);
2745
+ const objects = sample.filter((record) => isRecord3(record.value));
2746
+ if (objects.length === 0) {
2747
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2748
+ const list = [...kinds];
2749
+ return [
2750
+ {
2751
+ name: "(value)",
2752
+ kind: list.length === 1 ? list[0] : "unknown",
2753
+ optional: false
2754
+ }
2755
+ ];
2756
+ }
2757
+ const root = /* @__PURE__ */ new Map();
2758
+ for (const record of objects) {
2759
+ for (const [key, value] of Object.entries(record.value)) {
2760
+ const accum = root.get(key) ?? blankAccum(key);
2761
+ absorb(accum, value);
2762
+ root.set(key, accum);
2763
+ }
2764
+ }
2765
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2766
+ };
2767
+ var mergeFields = (declared, inferred) => {
2768
+ const byName = /* @__PURE__ */ new Map();
2769
+ for (const field of inferred)
2770
+ byName.set(field.name, field);
2771
+ const ordered = [];
2772
+ const seen = /* @__PURE__ */ new Set();
2773
+ for (const field of declared ?? []) {
2774
+ const found = byName.get(field.name);
2775
+ seen.add(field.name);
2776
+ if (!found) {
2777
+ ordered.push({ ...field, optional: field.optional });
2778
+ continue;
2779
+ }
2780
+ ordered.push({
2781
+ ...found,
2782
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2783
+ optional: field.optional || found.optional,
2784
+ ...field.description !== void 0 ? { description: field.description } : {},
2785
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2786
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2787
+ });
2788
+ }
2789
+ for (const field of inferred) {
2790
+ if (!seen.has(field.name))
2791
+ ordered.push(field);
2792
+ }
2793
+ return ordered;
2794
+ };
2795
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2796
+ var readRecord = (collection, id) => {
2797
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2798
+ const row = rows.find((entry) => entry.id === id);
2799
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2800
+ };
2801
+ var inspectState = (scope) => {
2802
+ const declared = /* @__PURE__ */ new Map();
2803
+ for (const declaration of scope.declarations ?? []) {
2804
+ if (COLLECTION_NAME.test(declaration.name))
2805
+ declared.set(declaration.name, declaration);
2806
+ }
2807
+ const names = new Set(declared.keys());
2808
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2809
+ names.add(name);
2810
+ for (const collection of discoverCollections(scope.root)) {
2811
+ if (collection.namespace === scope.storageNamespace)
2812
+ names.add(collection.collectionName);
2813
+ }
2814
+ const collections = [];
2815
+ for (const name of names) {
2816
+ if (!COLLECTION_NAME.test(name))
2817
+ continue;
2818
+ const declaration = declared.get(name);
2819
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2820
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2821
+ const inferred = inferFields(records);
2822
+ const fields = mergeFields(declaration?.fields, inferred);
2823
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2824
+ collections.push({
2825
+ name,
2826
+ label: declaration?.label ?? humanize(name),
2827
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2828
+ count: collection.count(),
2829
+ source,
2830
+ fields,
2831
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2832
+ });
2833
+ }
2834
+ const order = /* @__PURE__ */ new Map();
2835
+ for (const [index, item] of (scope.declarations ?? []).entries())
2836
+ order.set(item.name, index);
2837
+ collections.sort((a, b) => {
2838
+ const left = order.get(a.name);
2839
+ const right = order.get(b.name);
2840
+ if (left !== void 0 && right !== void 0)
2841
+ return left - right;
2842
+ if (left !== void 0)
2843
+ return -1;
2844
+ if (right !== void 0)
2845
+ return 1;
2846
+ return a.name.localeCompare(b.name);
2847
+ });
2848
+ return {
2849
+ namespace: scope.namespace,
2850
+ storageNamespace: scope.storageNamespace,
2851
+ collections
2852
+ };
2853
+ };
2854
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2855
+ if (!COLLECTION_NAME.test(name))
2856
+ return fail(400, "collection name is not allowed");
2857
+ const limit = query.limit ?? 50;
2858
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2859
+ return fail(400, "limit must be an integer from 1 to 200");
2860
+ }
2861
+ const order = query.order ?? "newest";
2862
+ if (order !== "newest" && order !== "oldest")
2863
+ return fail(400, 'order must be "newest" or "oldest"');
2864
+ const collection = collectionOf(sqlite, storageNamespace, name);
2865
+ const rows = collection.list({ order }).filter((row) => {
2866
+ if (query.after === void 0)
2867
+ return true;
2868
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2869
+ });
2870
+ const slice = rows.slice(0, limit);
2871
+ const last = slice.at(-1);
2872
+ return {
2873
+ ok: true,
2874
+ value: {
2875
+ collection: name,
2876
+ count: collection.count(),
2877
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2878
+ next: rows.length > limit && last ? last.seq : null
2879
+ }
2880
+ };
2881
+ };
2882
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2883
+ var readStateRecord = (scope, name, id) => {
2884
+ if (!COLLECTION_NAME.test(name))
2885
+ return fail(400, "collection name is not allowed");
2886
+ if (!RECORD_ID.test(id))
2887
+ return fail(400, "record id is not allowed");
2888
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2889
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
2890
+ };
2891
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2892
+ var createStateRecord = (scope, name, input) => {
2893
+ if (!COLLECTION_NAME.test(name))
2894
+ return fail(400, "collection name is not allowed");
2895
+ const parsed = jsonValue(input.value);
2896
+ if (!parsed.ok)
2897
+ return parsed;
2898
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2899
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2900
+ const checked = requireId(id);
2901
+ if (!checked.ok)
2902
+ return checked;
2903
+ if (collection.has(checked.value))
2904
+ return fail(409, `record ${checked.value} already exists`);
2905
+ const stored = collection.insert(checked.value, parsed.value);
2906
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2907
+ };
2908
+ var replaceStateRecord = (scope, name, id, value) => {
2909
+ if (!COLLECTION_NAME.test(name))
2910
+ return fail(400, "collection name is not allowed");
2911
+ const checked = requireId(id);
2912
+ if (!checked.ok)
2913
+ return checked;
2914
+ const parsed = jsonValue(value);
2915
+ if (!parsed.ok)
2916
+ return parsed;
2917
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2918
+ if (!collection.has(checked.value))
2919
+ return fail(404, `no record ${checked.value} in ${name}`);
2920
+ const stored = collection.update(checked.value, parsed.value);
2921
+ if (!stored)
2922
+ return fail(404, `no record ${checked.value} in ${name}`);
2923
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2924
+ };
2925
+ var patchStateRecord = (scope, name, id, value) => {
2926
+ const current = readStateRecord(scope, name, id);
2927
+ if (!current.ok)
2928
+ return current;
2929
+ const parsed = jsonValue(value);
2930
+ if (!parsed.ok)
2931
+ return parsed;
2932
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2933
+ return replaceStateRecord(scope, name, id, next);
2934
+ };
2935
+ var deleteStateRecord = (scope, name, id) => {
2936
+ if (!COLLECTION_NAME.test(name))
2937
+ return fail(400, "collection name is not allowed");
2938
+ const checked = requireId(id);
2939
+ if (!checked.ok)
2940
+ return checked;
2941
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2942
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2943
+ };
2944
+ var json4 = (status, body) => new Response(JSON.stringify(body), {
2945
+ status,
2946
+ headers: { "content-type": "application/json; charset=utf-8" }
2947
+ });
2948
+ var adminError2 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2949
+ var fromResult = (result, status) => result.ok ? json4(status, result.value) : adminError2(result.status, result.message);
2950
+ var integerParam = (value) => {
2951
+ if (value === null)
2952
+ return void 0;
2953
+ if (!/^-?\d+$/.test(value))
2954
+ return "bad";
2955
+ return Number(value);
2956
+ };
2957
+ var stateAdminRoutes = (routes) => {
2958
+ const open = (namespace) => {
2959
+ try {
2960
+ return { ok: true, value: routes.open(namespace) };
2961
+ } catch (error) {
2962
+ return fail(400, error instanceof Error ? error.message : String(error));
2963
+ }
2964
+ };
2965
+ const wrote = (namespace) => {
2966
+ routes.afterWrite?.(namespace);
2967
+ };
2968
+ return {
2969
+ "GET /state": ({ namespace }) => {
2970
+ const scope = open(namespace);
2971
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2972
+ },
2973
+ "GET /state/:collection": ({ namespace, params, url }) => {
2974
+ const scope = open(namespace);
2975
+ if (!scope.ok)
2976
+ return fromResult(scope, 200);
2977
+ const limit = integerParam(url.searchParams.get("limit"));
2978
+ const after = integerParam(url.searchParams.get("after"));
2979
+ if (limit === "bad")
2980
+ return adminError2(400, "limit: expected an integer");
2981
+ if (after === "bad")
2982
+ return adminError2(400, "after: expected a sequence number");
2983
+ const order = url.searchParams.get("order");
2984
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2985
+ ...limit !== void 0 ? { limit } : {},
2986
+ ...after !== void 0 ? { after } : {},
2987
+ ...order === "newest" || order === "oldest" ? { order } : {}
2988
+ }), 200);
2989
+ },
2990
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2991
+ const scope = open(namespace);
2992
+ if (!scope.ok)
2993
+ return fromResult(scope, 200);
2994
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2995
+ },
2996
+ "POST /state/:collection": ({ namespace, params, body }) => {
2997
+ const scope = open(namespace);
2998
+ if (!scope.ok)
2999
+ return fromResult(scope, 201);
3000
+ if (!isRecord3(body) || !("value" in body)) {
3001
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
3002
+ }
3003
+ const id = body.id;
3004
+ if (id !== void 0 && typeof id !== "string")
3005
+ return adminError2(400, "id must be a string");
3006
+ const created = createStateRecord(scope.value, params.collection ?? "", {
3007
+ ...typeof id === "string" ? { id } : {},
3008
+ value: body.value
3009
+ });
3010
+ if (created.ok)
3011
+ wrote(namespace);
3012
+ return fromResult(created, 201);
3013
+ },
3014
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
3015
+ const scope = open(namespace);
3016
+ if (!scope.ok)
3017
+ return fromResult(scope, 200);
3018
+ if (!isRecord3(body) || !("value" in body))
3019
+ return adminError2(400, 'expected {"value": <json>}');
3020
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3021
+ if (replaced.ok)
3022
+ wrote(namespace);
3023
+ return fromResult(replaced, 200);
3024
+ },
3025
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
3026
+ const scope = open(namespace);
3027
+ if (!scope.ok)
3028
+ return fromResult(scope, 200);
3029
+ if (!isRecord3(body) || !("value" in body))
3030
+ return adminError2(400, 'expected {"value": <json>}');
3031
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
3032
+ if (patched.ok)
3033
+ wrote(namespace);
3034
+ return fromResult(patched, 200);
3035
+ },
3036
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
3037
+ const scope = open(namespace);
3038
+ if (!scope.ok)
3039
+ return fromResult(scope, 200);
3040
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
3041
+ if (removed.ok)
3042
+ wrote(namespace);
3043
+ return fromResult(removed, 200);
3044
+ }
3045
+ };
3046
+ };
3047
+
1682
3048
  // ../core/dist/version.js
1683
- var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
3049
+ var PACKAGE_VERSION = true ? "1.5.0" : UNRELEASED_VERSION;
1684
3050
 
1685
3051
  // ../core/dist/signing.js
1686
3052
  var encoder = new TextEncoder();
@@ -2015,11 +3381,11 @@ var createWebhookHub = (options) => {
2015
3381
  };
2016
3382
  return hub;
2017
3383
  };
2018
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2019
- var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2020
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3384
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3385
+ var adminError3 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
3386
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2021
3387
  var parseEndpoint = (value) => {
2022
- if (!isRecord3(value) || typeof value.url !== "string")
3388
+ if (!isRecord4(value) || typeof value.url !== "string")
2023
3389
  return "each endpoint needs a url";
2024
3390
  try {
2025
3391
  new URL(value.url);
@@ -2036,18 +3402,18 @@ var parseEndpoint = (value) => {
2036
3402
  const events = value.events ?? value.enabledEvents;
2037
3403
  if (Array.isArray(events))
2038
3404
  endpoint.events = events.map(String);
2039
- if (isRecord3(value.tags)) {
3405
+ if (isRecord4(value.tags)) {
2040
3406
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
2041
3407
  }
2042
3408
  if (typeof value.account === "string")
2043
3409
  endpoint.tags = { ...endpoint.tags, account: value.account };
2044
- if (isRecord3(value.headers)) {
3410
+ if (isRecord4(value.headers)) {
2045
3411
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
2046
3412
  }
2047
3413
  return endpoint;
2048
3414
  };
2049
3415
  var webhookAdminRoutes = (hub) => ({
2050
- "GET /webhooks": ({ url, namespace }) => json3(200, {
3416
+ "GET /webhooks": ({ url, namespace }) => json5(200, {
2051
3417
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
2052
3418
  const type = url.searchParams.get("type");
2053
3419
  return type === null || d.type === type;
@@ -2055,51 +3421,51 @@ var webhookAdminRoutes = (hub) => ({
2055
3421
  }),
2056
3422
  "GET /webhooks/events": ({ url, namespace }) => {
2057
3423
  const type = url.searchParams.get("type");
2058
- return json3(200, {
3424
+ return json5(200, {
2059
3425
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
2060
3426
  });
2061
3427
  },
2062
3428
  "POST /webhooks/:id/replay": async ({ params }) => {
2063
3429
  const replayed = await hub.replay(params.id);
2064
- return replayed ? json3(200, replayed) : adminError2(404, `no delivery ${params.id}`);
3430
+ return replayed ? json5(200, replayed) : adminError3(404, `no delivery ${params.id}`);
2065
3431
  },
2066
3432
  "POST /webhooks/flush": async () => {
2067
3433
  await hub.flush();
2068
- return json3(200, { status: "ok" });
3434
+ return json5(200, { status: "ok" });
2069
3435
  },
2070
3436
  "POST /webhooks/faults": ({ body, namespace }) => {
2071
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2072
- return adminError2(400, "mode must be duplicate, reorder or drop");
3437
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3438
+ return adminError3(400, "mode must be duplicate, reorder or drop");
2073
3439
  }
2074
3440
  const fault = { mode: body.mode };
2075
3441
  if (typeof body.count === "number")
2076
3442
  fault.count = body.count;
2077
3443
  hub.fault(namespace, fault);
2078
- return json3(201, { namespace, ...fault });
3444
+ return json5(201, { namespace, ...fault });
2079
3445
  },
2080
- "GET /webhook-endpoints": ({ namespace }) => json3(200, {
3446
+ "GET /webhook-endpoints": ({ namespace }) => json5(200, {
2081
3447
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
2082
3448
  ...rest,
2083
3449
  secret: secret ? "(set)" : null
2084
3450
  }))
2085
3451
  }),
2086
3452
  "PUT /webhook-endpoints": ({ body, namespace }) => {
2087
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
3453
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
2088
3454
  if (!Array.isArray(list))
2089
- return adminError2(400, "expected [{url, secret?, events?}]");
3455
+ return adminError3(400, "expected [{url, secret?, events?}]");
2090
3456
  const parsed = [];
2091
3457
  for (const each of list) {
2092
3458
  const endpoint = parseEndpoint(each);
2093
3459
  if (typeof endpoint === "string")
2094
- return adminError2(400, endpoint);
3460
+ return adminError3(400, endpoint);
2095
3461
  parsed.push(endpoint);
2096
3462
  }
2097
3463
  const set = hub.setEndpoints(namespace, parsed);
2098
- return json3(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3464
+ return json5(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2099
3465
  },
2100
3466
  "DELETE /webhook-endpoints": ({ namespace }) => {
2101
3467
  hub.setEndpoints(namespace, []);
2102
- return json3(200, { status: "ok" });
3468
+ return json5(200, { status: "ok" });
2103
3469
  }
2104
3470
  });
2105
3471
  var parsePayload = (message) => {
@@ -2164,6 +3530,7 @@ var operationMatcher = (document2) => {
2164
3530
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
2165
3531
  };
2166
3532
  var createRuntime = (options) => {
3533
+ assertAdminUi(options.adminUi);
2167
3534
  const sqlite = bootSqlite(options.sqlite);
2168
3535
  const clock = options.clock ?? createClock();
2169
3536
  const rng = createRng(options.seed ?? 0);
@@ -2370,6 +3737,19 @@ var createRuntime = (options) => {
2370
3737
  else
2371
3738
  timeline(name);
2372
3739
  };
3740
+ const declarationsFor = (namespace) => {
3741
+ const declared = options.state;
3742
+ if (!declared)
3743
+ return [];
3744
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3745
+ };
3746
+ const stateScope = (namespace) => ({
3747
+ sqlite,
3748
+ namespace,
3749
+ storageNamespace: storageNamespace(namespace),
3750
+ root: instance(namespace),
3751
+ declarations: declarationsFor(namespace)
3752
+ });
2373
3753
  const runtime = {
2374
3754
  name: options.name,
2375
3755
  sqlite,
@@ -2408,6 +3788,7 @@ var createRuntime = (options) => {
2408
3788
  branch,
2409
3789
  checkout,
2410
3790
  timeline,
3791
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
2411
3792
  fetch: async (incoming) => {
2412
3793
  let request = incoming;
2413
3794
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2601,11 +3982,20 @@ var createRuntime = (options) => {
2601
3982
  ...credentialRoutes(credentials),
2602
3983
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2603
3984
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2604
- ...options.admin?.(runtime) ?? {}
3985
+ ...options.admin?.(runtime) ?? {},
3986
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3987
+ // beside these; it does not replace `/state` or `/ui`.
3988
+ ...stateAdminRoutes({
3989
+ open: stateScope,
3990
+ afterWrite: (namespace) => {
3991
+ checkpoint(namespace, "main");
3992
+ }
3993
+ }),
3994
+ ...adminUiRoutes(options.name, options.adminUi)
2605
3995
  },
2606
3996
  adminKey: options.adminKey
2607
3997
  });
2608
- return runtime;
3998
+ return defineMock(runtime);
2609
3999
  };
2610
4000
  var mutableResponse = (response) => {
2611
4001
  try {
@@ -2690,9 +4080,9 @@ var supportedOperationIds = ["SearchContacts", "CreateContact", "GetContact", "U
2690
4080
  var QueryError = class extends Error {
2691
4081
  };
2692
4082
  var FILTER_OPERATORS = ["=", "!=", "IN", "NIN", "<", ">", "~", "!~", "^", "$"];
2693
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4083
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2694
4084
  var parseQuery = (value, fields, depth = 0) => {
2695
- if (!isRecord4(value)) throw new QueryError("query must be an object");
4085
+ if (!isRecord5(value)) throw new QueryError("query must be an object");
2696
4086
  const operator = value.operator;
2697
4087
  if (operator === "AND" || operator === "OR") {
2698
4088
  if (depth >= 2) throw new QueryError("queries can be nested at most two levels deep");
@@ -2767,7 +4157,7 @@ var decodeCursor = (cursor) => {
2767
4157
  throw new QueryError("starting_after is not a valid cursor");
2768
4158
  };
2769
4159
  var paginate = (items, pagination, defaultPerPage) => {
2770
- const options = isRecord4(pagination) ? pagination : {};
4160
+ const options = isRecord5(pagination) ? pagination : {};
2771
4161
  const perPage = options.per_page === void 0 ? defaultPerPage : Number(options.per_page);
2772
4162
  if (!Number.isInteger(perPage) || perPage < 1 || perPage > 150) {
2773
4163
  throw new QueryError("per_page must be between 1 and 150");
@@ -2788,10 +4178,10 @@ var paginate = (items, pagination, defaultPerPage) => {
2788
4178
  }
2789
4179
  };
2790
4180
  };
2791
- var escapeHtml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
4181
+ var escapeHtml2 = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2792
4182
  var toHtml = (body) => {
2793
4183
  if (/<[a-z][\s\S]*>/i.test(body)) return body;
2794
- return body.split(/\r?\n/).map((line) => `<p>${escapeHtml(line)}</p>`).join("");
4184
+ return body.split(/\r?\n/).map((line) => `<p>${escapeHtml2(line)}</p>`).join("");
2795
4185
  };
2796
4186
  var toPlaintext = (html) => {
2797
4187
  if (html === null) return null;
@@ -2963,14 +4353,14 @@ var INTERCOM_PRESETS = {
2963
4353
  webhook: { mode: "drop" }
2964
4354
  }
2965
4355
  };
2966
- var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2967
- var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2968
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4356
+ var json6 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4357
+ var adminError4 = (status, message) => json6(status, { error: { type: "mockingbird_admin", message } });
4358
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2969
4359
  var guard = (run) => {
2970
4360
  try {
2971
4361
  return run();
2972
4362
  } catch (error) {
2973
- if (error instanceof IntercomError) return adminError3(error.status, error.message);
4363
+ if (error instanceof IntercomError) return adminError4(error.status, error.message);
2974
4364
  throw error;
2975
4365
  }
2976
4366
  };
@@ -2980,27 +4370,27 @@ var adminRoutes = (runtime) => {
2980
4370
  const defaultAdmin = (namespace) => api(namespace).state.admins.list({ order: "oldest" }).at(0)?.value.id ?? "";
2981
4371
  return {
2982
4372
  ...outboxAdminRoutes(runtime, (instance) => instance.state.outbox),
2983
- "GET /contacts": ({ namespace }) => json4(200, { contacts: api(namespace).contacts() }),
2984
- "GET /conversations": ({ namespace }) => json4(200, { conversations: api(namespace).conversations() }),
4373
+ "GET /contacts": ({ namespace }) => json6(200, { contacts: api(namespace).contacts() }),
4374
+ "GET /conversations": ({ namespace }) => json6(200, { conversations: api(namespace).conversations() }),
2985
4375
  "POST /conversations": ({ body, namespace }) => guard(() => {
2986
- if (!isRecord5(body) || typeof body.body !== "string") {
2987
- return adminError3(400, 'expected {"contactId" | "externalId", "adminId"?, "body"}');
4376
+ if (!isRecord6(body) || typeof body.body !== "string") {
4377
+ return adminError4(400, 'expected {"contactId" | "externalId", "adminId"?, "body"}');
2988
4378
  }
2989
4379
  const state = api(namespace).state;
2990
4380
  const contactId = typeof body.contactId === "string" ? body.contactId : typeof body.externalId === "string" ? state.findContact((c) => c.external_id === body.externalId)?.id : void 0;
2991
- if (!contactId) return adminError3(404, "no such contact");
4381
+ if (!contactId) return adminError4(404, "no such contact");
2992
4382
  const created = api(namespace).startAdminConversation({
2993
4383
  contactId,
2994
4384
  adminId: typeof body.adminId === "string" ? body.adminId : defaultAdmin(namespace),
2995
4385
  body: body.body
2996
4386
  });
2997
- return json4(201, created);
4387
+ return json6(201, created);
2998
4388
  }),
2999
4389
  "POST /conversations/:id/admin-reply": ({ params, body, namespace }) => guard(() => {
3000
4390
  const found = conversation(namespace, params.id);
3001
- if (!found) return adminError3(404, `no conversation ${params.id}`);
3002
- if (!isRecord5(body) || typeof body.body !== "string") {
3003
- return adminError3(
4391
+ if (!found) return adminError4(404, `no conversation ${params.id}`);
4392
+ if (!isRecord6(body) || typeof body.body !== "string") {
4393
+ return adminError4(
3004
4394
  400,
3005
4395
  'expected {"adminId" | "admin_id"?, "body", "messageType"?: "comment" | "note"}'
3006
4396
  );
@@ -3010,30 +4400,30 @@ var adminRoutes = (runtime) => {
3010
4400
  const author = instance.state.admins.get(
3011
4401
  typeof requested === "string" ? requested : defaultAdmin(namespace)
3012
4402
  );
3013
- if (!author) return adminError3(404, `no admin ${String(requested)}`);
4403
+ if (!author) return adminError4(404, `no admin ${String(requested)}`);
3014
4404
  const next = instance.appendPart(found, {
3015
4405
  partType: body.messageType === "note" ? "note" : "comment",
3016
4406
  author: { type: "admin", id: author.id, name: author.name, email: author.email },
3017
4407
  body: toHtml(body.body)
3018
4408
  });
3019
- return json4(200, next);
4409
+ return json6(200, next);
3020
4410
  }),
3021
4411
  "POST /conversations/:id/close": ({ params, body, namespace }) => guard(() => {
3022
4412
  const found = conversation(namespace, params.id);
3023
- if (!found) return adminError3(404, `no conversation ${params.id}`);
3024
- const adminId = isRecord5(body) && typeof body.adminId === "string" ? body.adminId : defaultAdmin(namespace);
3025
- return json4(200, api(namespace).manage(found, { action: "close", adminId }));
4413
+ if (!found) return adminError4(404, `no conversation ${params.id}`);
4414
+ const adminId = isRecord6(body) && typeof body.adminId === "string" ? body.adminId : defaultAdmin(namespace);
4415
+ return json6(200, api(namespace).manage(found, { action: "close", adminId }));
3026
4416
  }),
3027
4417
  "POST /conversations/:id/open": ({ params, body, namespace }) => guard(() => {
3028
4418
  const found = conversation(namespace, params.id);
3029
- if (!found) return adminError3(404, `no conversation ${params.id}`);
3030
- const adminId = isRecord5(body) && typeof body.adminId === "string" ? body.adminId : defaultAdmin(namespace);
3031
- return json4(200, api(namespace).manage(found, { action: "open", adminId }));
4419
+ if (!found) return adminError4(404, `no conversation ${params.id}`);
4420
+ const adminId = isRecord6(body) && typeof body.adminId === "string" ? body.adminId : defaultAdmin(namespace);
4421
+ return json6(200, api(namespace).manage(found, { action: "open", adminId }));
3032
4422
  }),
3033
4423
  "PUT /admins": ({ body, namespace }) => {
3034
- const list = Array.isArray(body) ? body : isRecord5(body) ? body.admins : void 0;
3035
- if (!Array.isArray(list) || !list.every((a) => isRecord5(a) && typeof a.id === "string")) {
3036
- return adminError3(400, "expected [{id, name, email}, \u2026]");
4424
+ const list = Array.isArray(body) ? body : isRecord6(body) ? body.admins : void 0;
4425
+ if (!Array.isArray(list) || !list.every((a) => isRecord6(a) && typeof a.id === "string")) {
4426
+ return adminError4(400, "expected [{id, name, email}, \u2026]");
3037
4427
  }
3038
4428
  const state = api(namespace).state;
3039
4429
  for (const row of state.admins.list()) state.admins.delete(row.id);
@@ -3050,23 +4440,23 @@ var adminRoutes = (runtime) => {
3050
4440
  team_ids: []
3051
4441
  });
3052
4442
  }
3053
- return json4(200, { admins: state.admins.list({ order: "oldest" }).map((row) => row.value) });
4443
+ return json6(200, { admins: state.admins.list({ order: "oldest" }).map((row) => row.value) });
3054
4444
  },
3055
- "GET /settings": ({ namespace }) => json4(200, api(namespace).state.current()),
4445
+ "GET /settings": ({ namespace }) => json6(200, api(namespace).state.current()),
3056
4446
  "PUT /settings": ({ body, namespace }) => {
3057
- if (!isRecord5(body)) return adminError3(400, "expected a JSON object");
4447
+ if (!isRecord6(body)) return adminError4(400, "expected a JSON object");
3058
4448
  const patch = {};
3059
4449
  if (body.tokens !== void 0) {
3060
- if (!Array.isArray(body.tokens)) return adminError3(400, "tokens: string[]");
4450
+ if (!Array.isArray(body.tokens)) return adminError4(400, "tokens: string[]");
3061
4451
  patch.tokens = body.tokens.map(String);
3062
4452
  }
3063
4453
  if (body.customAttributes !== void 0) {
3064
4454
  if (body.customAttributes !== null && !Array.isArray(body.customAttributes)) {
3065
- return adminError3(400, "customAttributes: string[] | null");
4455
+ return adminError4(400, "customAttributes: string[] | null");
3066
4456
  }
3067
4457
  patch.customAttributes = body.customAttributes === null ? null : body.customAttributes.map(String);
3068
4458
  }
3069
- return json4(200, api(namespace).state.update(patch));
4459
+ return json6(200, api(namespace).state.update(patch));
3070
4460
  }
3071
4461
  };
3072
4462
  };
@@ -3169,7 +4559,7 @@ var CONVERSATION_FIELDS = [
3169
4559
  "source.author.name",
3170
4560
  "source.author.email"
3171
4561
  ];
3172
- var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4562
+ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3173
4563
  var str = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
3174
4564
  var IntercomError = class extends Error {
3175
4565
  constructor(status, code, message) {
@@ -3314,7 +4704,7 @@ var IntercomAPI = class {
3314
4704
  `${[first.path, missing[1]].filter(Boolean).join(".")} is required`
3315
4705
  ) : new IntercomError(400, "parameter_invalid", `${first.path || "body"} ${first.message}`);
3316
4706
  }
3317
- return context.body.kind === "json" && isRecord6(context.body.value) ? context.body.value : {};
4707
+ return context.body.kind === "json" && isRecord7(context.body.value) ? context.body.value : {};
3318
4708
  }
3319
4709
  // ─── Contacts ───────────────────────────────────────────────────────────────────────────
3320
4710
  contactBody(contact) {
@@ -3375,7 +4765,7 @@ var IntercomAPI = class {
3375
4765
  checkCustomAttributes(attributes) {
3376
4766
  if (attributes === void 0) return {};
3377
4767
  const defined = this.state.current().customAttributes;
3378
- const given = isRecord6(attributes) ? attributes : {};
4768
+ const given = isRecord7(attributes) ? attributes : {};
3379
4769
  if (defined !== null) {
3380
4770
  const unknown = Object.keys(given).find((key) => !defined.includes(key));
3381
4771
  if (unknown !== void 0) {
@@ -3609,7 +4999,7 @@ var IntercomAPI = class {
3609
4999
  ...typeof body.title === "string" ? { title: body.title } : {},
3610
5000
  custom_attributes: {
3611
5001
  ...conversation.custom_attributes,
3612
- ...isRecord6(body.custom_attributes) ? body.custom_attributes : {}
5002
+ ...isRecord7(body.custom_attributes) ? body.custom_attributes : {}
3613
5003
  },
3614
5004
  updated_at: this.seconds()
3615
5005
  };
@@ -3929,7 +5319,7 @@ var IntercomAPI = class {
3929
5319
  if (field.startsWith("source.")) {
3930
5320
  let value = conversation.source;
3931
5321
  for (const key of field.slice("source.".length).split(".")) {
3932
- value = isRecord6(value) ? value[key] : void 0;
5322
+ value = isRecord7(value) ? value[key] : void 0;
3933
5323
  }
3934
5324
  return value;
3935
5325
  }
@@ -4031,4 +5421,4 @@ export {
4031
5421
  IntercomError,
4032
5422
  IntercomAPI
4033
5423
  };
4034
- //# sourceMappingURL=chunk-4XH3F7DQ.js.map
5424
+ //# sourceMappingURL=chunk-T56VJH23.js.map