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