@crvouga/mockingbird-service-fullscript 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,30 +38,30 @@ var createClock = (source = Date.now) => {
38
38
  var Collection = class {
39
39
  sqlite;
40
40
  namespace;
41
- name;
42
- constructor(sqlite, namespace, name) {
41
+ collectionName;
42
+ constructor(sqlite, namespace, collectionName) {
43
43
  this.sqlite = sqlite;
44
44
  this.namespace = namespace;
45
- this.name = name;
45
+ this.collectionName = collectionName;
46
46
  }
47
47
  bumpCollectionSeq() {
48
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
48
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.collectionName);
49
49
  const next = (row?.value ?? 0) + 1;
50
50
  this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
51
- ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
51
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.collectionName, next);
52
52
  return next;
53
53
  }
54
54
  nextSequence() {
55
55
  return this.sqlite.transaction(() => this.bumpCollectionSeq());
56
56
  }
57
57
  get(id) {
58
- const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
58
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
59
59
  if (!row)
60
60
  return void 0;
61
61
  return JSON.parse(row.value).value;
62
62
  }
63
63
  has(id) {
64
- const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
64
+ const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
65
65
  return row !== void 0;
66
66
  }
67
67
  /** Insert a new record, assigning it the next sequence number. */
@@ -71,32 +71,32 @@ var Collection = class {
71
71
  const stored = { seq, value };
72
72
  this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
73
73
  VALUES (?, ?, ?, ?, ?)
74
- ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
74
+ ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.collectionName, id, seq, JSON.stringify(stored));
75
75
  return stored;
76
76
  });
77
77
  }
78
78
  /** Replace an existing record's value, keeping its position. */
79
79
  update(id, value) {
80
80
  return this.sqlite.transaction(() => {
81
- const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
81
+ const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
82
82
  if (!row)
83
83
  return void 0;
84
84
  const stored = { seq: row.seq, value };
85
- this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
85
+ this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.collectionName, id);
86
86
  return stored;
87
87
  });
88
88
  }
89
89
  delete(id) {
90
- const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
90
+ const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.collectionName, id);
91
91
  return result.changes > 0;
92
92
  }
93
93
  /** How many records the collection holds, without reading them. */
94
94
  count() {
95
- const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
95
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.collectionName);
96
96
  return Number(row?.n ?? 0);
97
97
  }
98
98
  list(options = {}) {
99
- const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
99
+ const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.collectionName);
100
100
  const out = [];
101
101
  for (const row of rows) {
102
102
  const stored = JSON.parse(row.value);
@@ -353,16 +353,18 @@ var createControlPlane = (context) => {
353
353
  uptimeMs: context.wallNow() - context.startedAt,
354
354
  clock: context.clock.state(),
355
355
  namespaces: context.namespaces().length,
356
+ adminUi: `${ADMIN_PREFIX}/ui`,
356
357
  ...context.describe()
357
358
  });
358
359
  }
359
360
  if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
360
361
  return void 0;
361
362
  }
362
- if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
364
+ const shell = request.method === "GET" && (path === "/ui" || path === "/ui/");
365
+ if (!shell && context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
366
  return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
364
367
  }
365
- const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
366
368
  for (const route of routes) {
367
369
  if (route.method !== request.method)
368
370
  continue;
@@ -699,64 +701,64 @@ var graphemeLength = (value) => [...value].length;
699
701
  var validateValue = (document2, schema, value, path = []) => {
700
702
  const errors = [];
701
703
  const s = resolveSchema(document2, schema);
702
- const fail2 = (message) => errors.push({ path, message });
704
+ const fail3 = (message) => errors.push({ path, message });
703
705
  const actual = jsonTypeOf(value);
704
706
  if (actual === "undefined") {
705
- fail2("value is undefined");
707
+ fail3("value is undefined");
706
708
  return errors;
707
709
  }
708
710
  const types = schemaTypes(s);
709
711
  if (types.length > 0) {
710
712
  const ok2 = types.some((t) => t === actual || t === "number" && actual === "integer");
711
713
  if (!ok2) {
712
- fail2(`expected type ${types.join("|")}, got ${actual}`);
714
+ fail3(`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
- fail2("value not in enum");
719
+ fail3("value not in enum");
718
720
  }
719
721
  if (s.const !== void 0 && !deepEqual(s.const, value))
720
- fail2("value does not equal const");
722
+ fail3("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
- fail2(`length ${length} < minLength ${s.minLength}`);
726
+ fail3(`length ${length} < minLength ${s.minLength}`);
725
727
  if (s.maxLength !== void 0 && length > s.maxLength)
726
- fail2(`length ${length} > maxLength ${s.maxLength}`);
728
+ fail3(`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
- fail2(`does not match pattern ${s.pattern}`);
732
+ fail3(`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
- fail2(`does not match format ${s.format}`);
739
+ fail3(`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
- fail2(`${value} < minimum ${s.minimum}`);
744
+ fail3(`${value} < minimum ${s.minimum}`);
743
745
  if (s.maximum !== void 0 && value > s.maximum)
744
- fail2(`${value} > maximum ${s.maximum}`);
746
+ fail3(`${value} > maximum ${s.maximum}`);
745
747
  if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
746
- fail2(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
748
+ fail3(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
747
749
  if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
748
- fail2(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
750
+ fail3(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
749
751
  if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
750
- fail2(`${value} is not a multiple of ${s.multipleOf}`);
752
+ fail3(`${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
- fail2(`${value.length} items < minItems ${s.minItems}`);
757
+ fail3(`${value.length} items < minItems ${s.minItems}`);
756
758
  if (s.maxItems !== void 0 && value.length > s.maxItems)
757
- fail2(`${value.length} items > maxItems ${s.maxItems}`);
759
+ fail3(`${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
- fail2("items are not unique");
761
+ fail3("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
- fail2(`missing required property ${name}`);
773
+ fail3(`missing required property ${name}`);
772
774
  if (s.minProperties !== void 0 && keys.length < s.minProperties)
773
- fail2(`${keys.length} properties < minProperties ${s.minProperties}`);
775
+ fail3(`${keys.length} properties < minProperties ${s.minProperties}`);
774
776
  if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
775
- fail2(`${keys.length} properties > maxProperties ${s.maxProperties}`);
777
+ fail3(`${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
- fail2(`unexpected property ${key}`);
785
+ fail3(`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
- fail2(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
792
+ fail3(`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
- fail2("matches no anyOf branch");
800
+ fail3("matches no anyOf branch");
799
801
  if (s.oneOf) {
800
802
  const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
801
803
  if (matches2 !== 1)
802
- fail2(`matches ${matches2} oneOf branches, expected exactly 1`);
804
+ fail3(`matches ${matches2} oneOf branches, expected exactly 1`);
803
805
  }
804
806
  if (s.not && validateValue(document2, s.not, value).length === 0)
805
- fail2("matches forbidden `not` schema");
807
+ fail3("matches forbidden `not` schema");
806
808
  return errors;
807
809
  };
808
810
 
@@ -1356,6 +1358,936 @@ var clearNamespace = (sqlite, namespace) => {
1356
1358
  });
1357
1359
  };
1358
1360
 
1361
+ // ../core/dist/surface.js
1362
+ var defineMock = (runtime) => runtime;
1363
+ var STANDARD_ADMIN_ROUTES = [
1364
+ "GET /",
1365
+ "POST /reset",
1366
+ "GET /namespaces",
1367
+ "GET /clock",
1368
+ "POST /clock",
1369
+ "GET /faults",
1370
+ "POST /faults",
1371
+ "DELETE /faults",
1372
+ "POST /snapshots",
1373
+ "POST /snapshots/:id/restore",
1374
+ "DELETE /snapshots/:id",
1375
+ "GET /timeline",
1376
+ "POST /checkpoints",
1377
+ "POST /branches/:name",
1378
+ "POST /branches/:name/checkout",
1379
+ "GET /requests",
1380
+ "DELETE /requests",
1381
+ "GET /metrics",
1382
+ "DELETE /metrics",
1383
+ "GET /credentials",
1384
+ "PUT /credentials",
1385
+ "DELETE /credentials",
1386
+ "GET /state",
1387
+ "GET /state/:collection",
1388
+ "GET /state/:collection/:id",
1389
+ "POST /state/:collection",
1390
+ "PUT /state/:collection/:id",
1391
+ "PATCH /state/:collection/:id",
1392
+ "DELETE /state/:collection/:id",
1393
+ "GET /ui",
1394
+ "GET /ui/",
1395
+ "GET /ui/manifest"
1396
+ ];
1397
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1398
+ var assertAdminUi = (ui) => {
1399
+ if (!ui?.panels)
1400
+ return;
1401
+ const seen = /* @__PURE__ */ new Set();
1402
+ for (const panel of ui.panels) {
1403
+ if (!PANEL_ID.test(panel.id)) {
1404
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1405
+ }
1406
+ if (seen.has(panel.id))
1407
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1408
+ seen.add(panel.id);
1409
+ if (panel.title.trim() === "")
1410
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1411
+ }
1412
+ };
1413
+
1414
+ // ../core/dist/admin-ui.js
1415
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1416
+ switch (char) {
1417
+ case "&":
1418
+ return "&amp;";
1419
+ case "<":
1420
+ return "&lt;";
1421
+ case ">":
1422
+ return "&gt;";
1423
+ case '"':
1424
+ return "&quot;";
1425
+ default:
1426
+ return "&#39;";
1427
+ }
1428
+ });
1429
+ var renderAdminDocument = (service) => {
1430
+ const name = escapeHtml(service);
1431
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1432
+ return `<!DOCTYPE html>
1433
+ <html lang="en">
1434
+ <head>
1435
+ <meta charset="utf-8">
1436
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1437
+ <meta name="color-scheme" content="light dark">
1438
+ <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">
1439
+ <title>${name} admin</title>
1440
+ <style>
1441
+ :root {
1442
+ color-scheme: light;
1443
+ --bg: #f6f5f2;
1444
+ --bg-elev: #ffffff;
1445
+ --bg-muted: #eeece6;
1446
+ --bg-inset: #f3f1eb;
1447
+ --line: #e2dfd6;
1448
+ --line-strong: #d0ccc1;
1449
+ --ink: #1c1915;
1450
+ --muted: #5e584f;
1451
+ --faint: #8a8378;
1452
+ --accent: #3d4f3a;
1453
+ --accent-ink: #f7f6f2;
1454
+ --accent-soft: #e5ece2;
1455
+ --ok: #1f7a45;
1456
+ --ok-soft: #e5f4eb;
1457
+ --warn: #9a6700;
1458
+ --warn-soft: #fbf3df;
1459
+ --err: #a33b32;
1460
+ --err-soft: #fdecea;
1461
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1462
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1463
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1464
+ --radius: 14px;
1465
+ --header: 60px;
1466
+ --nav: 220px;
1467
+ }
1468
+ :root[data-theme="dark"] {
1469
+ color-scheme: dark;
1470
+ --bg: #141311;
1471
+ --bg-elev: #1e1c19;
1472
+ --bg-muted: #26231f;
1473
+ --bg-inset: #181715;
1474
+ --line: #34302b;
1475
+ --line-strong: #4a453d;
1476
+ --ink: #f4f1ea;
1477
+ --muted: #c4bdb1;
1478
+ --faint: #8f877c;
1479
+ --accent: #c5d5b8;
1480
+ --accent-ink: #1a2118;
1481
+ --accent-soft: #2a3328;
1482
+ --ok: #8fd6a8;
1483
+ --ok-soft: #1a2e22;
1484
+ --warn: #f0cc78;
1485
+ --warn-soft: #332911;
1486
+ --err: #f0a8a2;
1487
+ --err-soft: #3a201e;
1488
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1489
+ }
1490
+ @media (prefers-color-scheme: dark) {
1491
+ :root:not([data-theme="light"]) {
1492
+ color-scheme: dark;
1493
+ --bg: #141311;
1494
+ --bg-elev: #1e1c19;
1495
+ --bg-muted: #26231f;
1496
+ --bg-inset: #181715;
1497
+ --line: #34302b;
1498
+ --line-strong: #4a453d;
1499
+ --ink: #f4f1ea;
1500
+ --muted: #c4bdb1;
1501
+ --faint: #8f877c;
1502
+ --accent: #c5d5b8;
1503
+ --accent-ink: #1a2118;
1504
+ --accent-soft: #2a3328;
1505
+ --ok: #8fd6a8;
1506
+ --ok-soft: #1a2e22;
1507
+ --warn: #f0cc78;
1508
+ --warn-soft: #332911;
1509
+ --err: #f0a8a2;
1510
+ --err-soft: #3a201e;
1511
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1512
+ }
1513
+ }
1514
+ * { box-sizing: border-box; }
1515
+ html, body { margin: 0; height: 100%; }
1516
+ body {
1517
+ font-family: var(--sans);
1518
+ background: var(--bg);
1519
+ color: var(--ink);
1520
+ line-height: 1.45;
1521
+ padding-left: env(safe-area-inset-left);
1522
+ padding-right: env(safe-area-inset-right);
1523
+ -webkit-text-size-adjust: 100%;
1524
+ }
1525
+ button, input, select, textarea { font: inherit; color: inherit; }
1526
+ button { cursor: pointer; }
1527
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1528
+ @media (prefers-reduced-motion: reduce) {
1529
+ * { scroll-behavior: auto !important; transition: none !important; }
1530
+ }
1531
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1532
+ header.top {
1533
+ position: sticky; top: 0; z-index: 5;
1534
+ display: flex; align-items: center; gap: 12px;
1535
+ min-height: var(--header); padding: 10px 16px;
1536
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1537
+ border-bottom: 1px solid var(--line);
1538
+ backdrop-filter: blur(10px);
1539
+ }
1540
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1541
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1542
+ .brand span { color: var(--faint); font-size: 12px; }
1543
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1544
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1545
+ label.field input, label.field select, .controls input[type="password"] {
1546
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1547
+ padding: 7px 8px; min-height: 36px;
1548
+ }
1549
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1550
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1551
+ background: var(--bg-elev);
1552
+ }
1553
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1554
+ .btn-quiet { background: transparent; }
1555
+ .btn-danger { color: var(--err); }
1556
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1557
+ record or the full nav row would widen the page past the viewport. */
1558
+ .layout {
1559
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1560
+ flex: 1; min-height: 0; min-width: 0;
1561
+ }
1562
+ nav.side {
1563
+ border-right: 1px solid var(--line); padding: 12px;
1564
+ display: flex; flex-direction: column; gap: 4px;
1565
+ background: var(--bg-elev);
1566
+ }
1567
+ nav.side button {
1568
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1569
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1570
+ }
1571
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1572
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1573
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1574
+ .lede { margin: 0 0 16px; color: var(--muted); }
1575
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1576
+ .card {
1577
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1578
+ padding: 14px 16px; box-shadow: var(--shadow);
1579
+ }
1580
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1581
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1582
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1583
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1584
+ .collection {
1585
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1586
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1587
+ }
1588
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1589
+ .collection small { display: block; color: var(--faint); }
1590
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1591
+ .chip {
1592
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1593
+ border-radius: 999px; padding: 4px 8px;
1594
+ }
1595
+ .chip i { color: var(--faint); font-style: normal; }
1596
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1597
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1598
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1599
+ tr.clickable { cursor: pointer; }
1600
+ tr.clickable:hover { background: var(--bg-muted); }
1601
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1602
+ pre {
1603
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1604
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1605
+ }
1606
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1607
+ .banner {
1608
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1609
+ background: var(--err-soft); color: var(--err);
1610
+ }
1611
+ .banner.show { display: block; }
1612
+ .empty { color: var(--muted); padding: 24px 8px; }
1613
+ dialog {
1614
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1615
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1616
+ }
1617
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1618
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1619
+ textarea {
1620
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1621
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1622
+ font-family: var(--mono); font-size: 12px;
1623
+ }
1624
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1625
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1626
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1627
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1628
+ .status-2 { color: var(--ok); }
1629
+ .status-4, .status-5, .status-0 { color: var(--err); }
1630
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1631
+ .route {
1632
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1633
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1634
+ }
1635
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1636
+ @media (max-width: 800px) {
1637
+ header.top {
1638
+ align-items: stretch; flex-direction: column;
1639
+ padding-top: max(10px, env(safe-area-inset-top));
1640
+ }
1641
+ input, select, textarea { font-size: 16px; }
1642
+ .controls { width: 100%; }
1643
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1644
+ .layout { grid-template-columns: minmax(0, 1fr); }
1645
+ nav.side {
1646
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1647
+ border-right: 0; border-bottom: 1px solid var(--line);
1648
+ padding: 8px;
1649
+ }
1650
+ nav.side button { white-space: nowrap; flex: none; }
1651
+ .split { grid-template-columns: minmax(0, 1fr); }
1652
+ main { padding: 14px; }
1653
+ table, thead, tbody, tr, th, td { display: block; }
1654
+ thead { display: none; }
1655
+ tr {
1656
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1657
+ background: var(--bg-elev); min-width: 0;
1658
+ }
1659
+ td {
1660
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1661
+ min-width: 0; overflow-wrap: anywhere;
1662
+ }
1663
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1664
+ .route { grid-template-columns: 72px 1fr; }
1665
+ .route button { grid-column: 1 / -1; }
1666
+ }
1667
+ </style>
1668
+ </head>
1669
+ <body>
1670
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1671
+ <header class="top">
1672
+ <div class="brand">
1673
+ <strong>${name}</strong>
1674
+ <span>Mockingbird admin</span>
1675
+ </div>
1676
+ <div class="controls">
1677
+ <label class="field">Namespace
1678
+ <select id="namespace" aria-label="Namespace"></select>
1679
+ </label>
1680
+ <label class="field">Admin key
1681
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1682
+ </label>
1683
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1684
+ <button class="btn" id="refresh" type="button">Refresh</button>
1685
+ </div>
1686
+ </header>
1687
+ <div class="layout">
1688
+ <nav class="side" id="nav" aria-label="Admin sections">
1689
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1690
+ <button type="button" data-view="state">State</button>
1691
+ <button type="button" data-view="clock">Clock</button>
1692
+ <button type="button" data-view="faults">Faults</button>
1693
+ <button type="button" data-view="journal">Journal</button>
1694
+ <button type="button" data-view="routes">Routes</button>
1695
+ </nav>
1696
+ <main id="views">
1697
+ <p class="banner" id="banner" role="alert"></p>
1698
+ <section class="view" id="view-overview">
1699
+ <h2>Overview</h2>
1700
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1701
+ <div class="grid" id="overview-cards"></div>
1702
+ <h3>Recent requests</h3>
1703
+ <div id="overview-requests"></div>
1704
+ </section>
1705
+ <section class="view" id="view-state" hidden>
1706
+ <h2>State</h2>
1707
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1708
+ <div class="split">
1709
+ <div id="collections"></div>
1710
+ <div>
1711
+ <div id="schema"></div>
1712
+ <div class="row-actions">
1713
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1714
+ </div>
1715
+ <div id="records"></div>
1716
+ </div>
1717
+ </div>
1718
+ </section>
1719
+ <section class="view" id="view-clock" hidden>
1720
+ <h2>Clock</h2>
1721
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1722
+ <div class="card" id="clock-readout"></div>
1723
+ <div class="row-actions">
1724
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1725
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1726
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1727
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1728
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1729
+ <button class="btn" id="freeze" type="button">Freeze</button>
1730
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1731
+ </div>
1732
+ <form id="clock-set" class="row-actions">
1733
+ <label class="field">Set instant
1734
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1735
+ </label>
1736
+ <button class="btn-primary" type="submit">Set</button>
1737
+ </form>
1738
+ </section>
1739
+ <section class="view" id="view-faults" hidden>
1740
+ <h2>Faults</h2>
1741
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1742
+ <form id="fault-form" class="card stack">
1743
+ <label class="field">Preset
1744
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1745
+ </label>
1746
+ <label class="field">Status
1747
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1748
+ </label>
1749
+ <label class="field">Path prefix
1750
+ <input id="fault-path" placeholder="/v1">
1751
+ </label>
1752
+ <label class="field">Method
1753
+ <input id="fault-method" placeholder="GET">
1754
+ </label>
1755
+ <div class="dialog-actions">
1756
+ <button class="btn-primary" type="submit">Add fault</button>
1757
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1758
+ </div>
1759
+ </form>
1760
+ <div id="fault-list"></div>
1761
+ </section>
1762
+ <section class="view" id="view-journal" hidden>
1763
+ <h2>Journal</h2>
1764
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1765
+ <div class="row-actions">
1766
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1767
+ </div>
1768
+ <div id="journal"></div>
1769
+ </section>
1770
+ <section class="view" id="view-routes" hidden>
1771
+ <h2>Routes</h2>
1772
+ <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>
1773
+ <div id="route-list"></div>
1774
+ <form id="route-form" class="card stack">
1775
+ <strong id="route-title">Select a route</strong>
1776
+ <label class="field">JSON body
1777
+ <textarea id="route-body" placeholder="{ }"></textarea>
1778
+ </label>
1779
+ <div class="dialog-actions">
1780
+ <button class="btn-primary" type="submit">Send</button>
1781
+ </div>
1782
+ <pre id="route-result">Response will show here.</pre>
1783
+ </form>
1784
+ </section>
1785
+ </main>
1786
+ </div>
1787
+ </div>
1788
+ <dialog id="editor">
1789
+ <form method="dialog" id="editor-form">
1790
+ <strong id="editor-title">Record</strong>
1791
+ <label class="field">Id
1792
+ <input id="editor-id" required>
1793
+ </label>
1794
+ <label class="field">JSON value
1795
+ <textarea id="editor-value"></textarea>
1796
+ </label>
1797
+ <div class="dialog-actions">
1798
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1799
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1800
+ <button class="btn-primary" type="submit" value="save">Save</button>
1801
+ </div>
1802
+ </form>
1803
+ </dialog>
1804
+ <script>
1805
+ (() => {
1806
+ const STANDARD = new Set(${standard})
1807
+ const state = {
1808
+ namespace: "default",
1809
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1810
+ view: "overview",
1811
+ collection: "",
1812
+ shape: null,
1813
+ route: null,
1814
+ editing: null
1815
+ }
1816
+ const $ = (id) => document.getElementById(id)
1817
+ const banner = $("banner")
1818
+ const keyInput = $("admin-key")
1819
+ keyInput.value = state.key
1820
+ const params = new URLSearchParams(location.search)
1821
+ if (params.get("key")) {
1822
+ state.key = params.get("key")
1823
+ keyInput.value = state.key
1824
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1825
+ params.delete("key")
1826
+ const next = params.toString()
1827
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1828
+ }
1829
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1830
+
1831
+ const showError = (error) => {
1832
+ banner.textContent = error instanceof Error ? error.message : String(error)
1833
+ banner.classList.add("show")
1834
+ }
1835
+ const clearError = () => banner.classList.remove("show")
1836
+
1837
+ async function originGet(path) {
1838
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1839
+ if (!response.ok) throw new Error(response.status + " " + path)
1840
+ return response.json()
1841
+ }
1842
+ async function api(method, path, body) {
1843
+ const headers = { accept: "application/json" }
1844
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1845
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1846
+ if (body !== undefined) headers["content-type"] = "application/json"
1847
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1848
+ method,
1849
+ headers,
1850
+ body: body === undefined ? undefined : JSON.stringify(body)
1851
+ })
1852
+ const text = await response.text()
1853
+ let data = null
1854
+ if (text) {
1855
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1856
+ }
1857
+ if (response.status === 401) {
1858
+ keyInput.focus()
1859
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1860
+ }
1861
+ if (!response.ok) {
1862
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1863
+ }
1864
+ return data
1865
+ }
1866
+ const panelApi = {
1867
+ get: (path) => api("GET", path),
1868
+ send: (method, path, body) => api(method, path, body),
1869
+ namespace: () => state.namespace
1870
+ }
1871
+
1872
+ function setTheme(theme) {
1873
+ if (theme) document.documentElement.dataset.theme = theme
1874
+ else delete document.documentElement.dataset.theme
1875
+ }
1876
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1877
+ if (storedTheme) setTheme(storedTheme)
1878
+ $("theme").addEventListener("click", () => {
1879
+ const current = document.documentElement.dataset.theme
1880
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1881
+ const next = dark ? "light" : "dark"
1882
+ localStorage.setItem("mockingbird-admin-theme", next)
1883
+ setTheme(next)
1884
+ })
1885
+
1886
+ function show(view) {
1887
+ state.view = view
1888
+ for (const button of document.querySelectorAll("#nav button")) {
1889
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1890
+ }
1891
+ for (const section of document.querySelectorAll("main .view")) {
1892
+ section.hidden = section.id !== "view-" + view
1893
+ }
1894
+ }
1895
+ document.getElementById("nav").addEventListener("click", (event) => {
1896
+ const button = event.target.closest("button[data-view]")
1897
+ if (!button) return
1898
+ show(button.dataset.view)
1899
+ refresh().catch(showError)
1900
+ })
1901
+
1902
+ function cards(items) {
1903
+ return '<div class="grid">' + items.map((item) =>
1904
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1905
+ ).join("") + "</div>"
1906
+ }
1907
+ function table(columns, rows) {
1908
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1909
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1910
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1911
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1912
+ ).join("") + "</tr>").join("")
1913
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1914
+ }
1915
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1916
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1917
+ }[char]))
1918
+ const preview = (value) => {
1919
+ const text = JSON.stringify(value)
1920
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1921
+ }
1922
+ const when = (epoch) => {
1923
+ const date = new Date(epoch)
1924
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1925
+ }
1926
+ const clockCard = (epoch) => {
1927
+ const date = new Date(epoch)
1928
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1929
+ const iso = date.toISOString()
1930
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1931
+ }
1932
+
1933
+ async function loadNamespaces() {
1934
+ const data = await api("GET", "/namespaces")
1935
+ const select = $("namespace")
1936
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1937
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1938
+ select.innerHTML = names.map((name) =>
1939
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1940
+ ).join("")
1941
+ select.value = state.namespace
1942
+ }
1943
+
1944
+ async function renderOverview() {
1945
+ const [health, shape, clock, journal] = await Promise.all([
1946
+ originGet("/health"),
1947
+ api("GET", "/state"),
1948
+ api("GET", "/clock"),
1949
+ api("GET", "/requests?limit=8")
1950
+ ])
1951
+ state.shape = shape
1952
+ $("overview-cards").innerHTML = cards([
1953
+ { k: "Service", v: esc(health.service || "${name}") },
1954
+ { k: "Status", v: esc(health.status || "ok") },
1955
+ { k: "Namespace", v: esc(state.namespace) },
1956
+ { k: "Collections", v: String(shape.collections.length) },
1957
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1958
+ { k: "Clock", v: clockCard(clock.now) }
1959
+ ])
1960
+ const requests = (journal && journal.requests) || []
1961
+ $("overview-requests").innerHTML = table(
1962
+ [
1963
+ { label: "Method", cell: (row) => esc(row.method) },
1964
+ { label: "Path", cell: (row) => esc(row.path) },
1965
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1966
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1967
+ ],
1968
+ requests
1969
+ )
1970
+ }
1971
+
1972
+ function schemaChips(collection) {
1973
+ if (!collection || collection.fields.length === 0) {
1974
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
1975
+ }
1976
+ return '<div class="chips">' + collection.fields.map((field) =>
1977
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
1978
+ ).join("") + "</div>"
1979
+ }
1980
+
1981
+ async function renderState() {
1982
+ const shape = await api("GET", "/state")
1983
+ state.shape = shape
1984
+ const host = $("collections")
1985
+ if (shape.collections.length === 0) {
1986
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
1987
+ $("schema").innerHTML = ""
1988
+ $("records").innerHTML = ""
1989
+ return
1990
+ }
1991
+ if (!shape.collections.some((item) => item.name === state.collection)) {
1992
+ state.collection = shape.collections[0].name
1993
+ }
1994
+ host.innerHTML = shape.collections.map((item) =>
1995
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
1996
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
1997
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
1998
+ ).join("")
1999
+ const selected = shape.collections.find((item) => item.name === state.collection)
2000
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
2001
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
2002
+ schemaChips(selected)
2003
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
2004
+ const rows = page.records.map((record) => ({
2005
+ ...record,
2006
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
2007
+ }))
2008
+ $("records").innerHTML = table(
2009
+ [
2010
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
2011
+ { label: "Seq", cell: (row) => esc(row.seq) },
2012
+ { label: "Value", cell: (row) => preview(row.value) }
2013
+ ],
2014
+ rows
2015
+ )
2016
+ }
2017
+
2018
+ async function renderClock() {
2019
+ const clock = await api("GET", "/clock")
2020
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
2021
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
2022
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
2023
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
2024
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
2025
+ }
2026
+
2027
+ async function renderFaults() {
2028
+ const [faults, presets] = await Promise.all([
2029
+ api("GET", "/faults"),
2030
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2031
+ ])
2032
+ const select = $("fault-preset")
2033
+ const current = select.value
2034
+ const list = presets.presets || []
2035
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
2036
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
2037
+ ).join("")
2038
+ select.value = current
2039
+ const rules = faults.faults || []
2040
+ $("fault-list").innerHTML = table(
2041
+ [
2042
+ { label: "Id", cell: (row) => esc(row.id) },
2043
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
2044
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
2045
+ ],
2046
+ rules
2047
+ )
2048
+ }
2049
+
2050
+ async function renderJournal() {
2051
+ const journal = await api("GET", "/requests?limit=100")
2052
+ $("journal").innerHTML = table(
2053
+ [
2054
+ { label: "When", cell: (row) => esc(row.at || "") },
2055
+ { label: "Method", cell: (row) => esc(row.method) },
2056
+ { label: "Path", cell: (row) => esc(row.path) },
2057
+ { label: "Status", cell: (row) => esc(row.status) },
2058
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2059
+ ],
2060
+ journal.requests || []
2061
+ )
2062
+ }
2063
+
2064
+ async function renderRoutes() {
2065
+ const data = await api("GET", "/")
2066
+ const routes = data.routes || []
2067
+ $("route-list").innerHTML = routes.map((route) => {
2068
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
2069
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
2070
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
2071
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
2072
+ }).join("")
2073
+ }
2074
+
2075
+ const renderers = {
2076
+ overview: renderOverview,
2077
+ state: renderState,
2078
+ clock: renderClock,
2079
+ faults: renderFaults,
2080
+ journal: renderJournal,
2081
+ routes: renderRoutes
2082
+ }
2083
+
2084
+ async function refresh() {
2085
+ clearError()
2086
+ if (state.view in renderers) await renderers[state.view]()
2087
+ }
2088
+
2089
+ $("namespace").addEventListener("change", () => {
2090
+ state.namespace = $("namespace").value
2091
+ refresh().catch(showError)
2092
+ })
2093
+ keyInput.addEventListener("change", () => {
2094
+ state.key = keyInput.value.trim()
2095
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
2096
+ refresh().catch(showError)
2097
+ })
2098
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
2099
+
2100
+ $("collections").addEventListener("click", (event) => {
2101
+ const button = event.target.closest("[data-collection]")
2102
+ if (!button) return
2103
+ state.collection = button.dataset.collection
2104
+ renderState().catch(showError)
2105
+ })
2106
+ $("records").addEventListener("click", (event) => {
2107
+ const row = event.target.closest("[data-id]")
2108
+ if (!row) return
2109
+ openEditor(row.dataset.id).catch(showError)
2110
+ })
2111
+
2112
+ const editor = $("editor")
2113
+ async function openEditor(id) {
2114
+ state.editing = id || null
2115
+ $("editor-title").textContent = id ? "Edit record" : "New record"
2116
+ $("editor-id").value = id || ""
2117
+ $("editor-id").readOnly = Boolean(id)
2118
+ $("editor-delete").hidden = !id
2119
+ if (id) {
2120
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2121
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
2122
+ } else {
2123
+ $("editor-value").value = "{\\n \\n}"
2124
+ }
2125
+ editor.showModal()
2126
+ }
2127
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
2128
+ $("editor-form").addEventListener("submit", (event) => {
2129
+ const submitter = event.submitter
2130
+ if (!submitter || submitter.value !== "save") return
2131
+ event.preventDefault()
2132
+ let value
2133
+ try { value = JSON.parse($("editor-value").value) }
2134
+ catch { showError(new Error("Value is not JSON")); return }
2135
+ const id = $("editor-id").value.trim()
2136
+ const path = "/state/" + encodeURIComponent(state.collection)
2137
+ const request = state.editing
2138
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
2139
+ : api("POST", path, { id: id || undefined, value })
2140
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
2141
+ })
2142
+ $("editor-delete").addEventListener("click", () => {
2143
+ const id = state.editing
2144
+ if (!id) return
2145
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2146
+ .then(() => { editor.close(); return renderState() })
2147
+ .catch(showError)
2148
+ })
2149
+
2150
+ document.querySelectorAll("[data-advance]").forEach((button) => {
2151
+ button.addEventListener("click", () => {
2152
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
2153
+ })
2154
+ })
2155
+ $("freeze").addEventListener("click", () => {
2156
+ const frozen = $("freeze").dataset.frozen === "1"
2157
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
2158
+ })
2159
+ $("clock-reset").addEventListener("click", () => {
2160
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
2161
+ })
2162
+ $("clock-set").addEventListener("submit", (event) => {
2163
+ event.preventDefault()
2164
+ const raw = $("clock-instant").value.trim()
2165
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
2166
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
2167
+ })
2168
+
2169
+ $("fault-form").addEventListener("submit", (event) => {
2170
+ event.preventDefault()
2171
+ const preset = $("fault-preset").value
2172
+ const body = preset
2173
+ ? { preset }
2174
+ : {
2175
+ status: Number($("fault-status").value),
2176
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
2177
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
2178
+ }
2179
+ if (!preset && !Number.isFinite(body.status)) {
2180
+ showError(new Error("Status must be a number, or choose a preset"))
2181
+ return
2182
+ }
2183
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
2184
+ })
2185
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
2186
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
2187
+
2188
+ $("route-list").addEventListener("click", (event) => {
2189
+ const button = event.target.closest("[data-route]")
2190
+ if (!button) return
2191
+ state.route = button.dataset.route
2192
+ $("route-title").textContent = state.route
2193
+ const method = state.route.split(" ")[0]
2194
+ $("route-body").disabled = method === "GET" || method === "DELETE"
2195
+ })
2196
+ $("route-form").addEventListener("submit", async (event) => {
2197
+ event.preventDefault()
2198
+ if (!state.route) return showError(new Error("Choose a route first"))
2199
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
2200
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
2201
+ let body
2202
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
2203
+ try { body = JSON.parse($("route-body").value) }
2204
+ catch { return showError(new Error("Body is not JSON")) }
2205
+ }
2206
+ try {
2207
+ const data = await api(method, concrete, body)
2208
+ $("route-result").textContent = JSON.stringify(data, null, 2)
2209
+ } catch (error) {
2210
+ showError(error)
2211
+ }
2212
+ })
2213
+
2214
+ function mountPanels(panels) {
2215
+ const nav = $("nav")
2216
+ const views = $("views")
2217
+ for (const panel of panels) {
2218
+ const button = document.createElement("button")
2219
+ button.type = "button"
2220
+ button.dataset.view = panel.id
2221
+ button.textContent = panel.title
2222
+ nav.append(button)
2223
+ const section = document.createElement("section")
2224
+ section.className = "view"
2225
+ section.id = "view-" + panel.id
2226
+ section.hidden = true
2227
+ const title = document.createElement("h2")
2228
+ title.textContent = panel.title
2229
+ const lede = document.createElement("p")
2230
+ lede.className = "lede"
2231
+ lede.textContent = panel.description || ""
2232
+ const body = document.createElement("div")
2233
+ body.className = "panel-body"
2234
+ body.id = "panel-" + panel.id
2235
+ body.innerHTML = panel.html || ""
2236
+ section.append(title, lede, body)
2237
+ views.append(section)
2238
+ if (panel.script) {
2239
+ try {
2240
+ const run = new Function("root", "api", panel.script)
2241
+ run(body, panelApi)
2242
+ } catch (error) {
2243
+ const note = document.createElement("p")
2244
+ note.className = "banner show"
2245
+ note.textContent = error instanceof Error ? error.message : String(error)
2246
+ body.append(note)
2247
+ }
2248
+ }
2249
+ }
2250
+ }
2251
+
2252
+ loadNamespaces()
2253
+ .then(() => api("GET", "/ui/manifest"))
2254
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2255
+ .catch(showError)
2256
+ })()
2257
+ </script>
2258
+ </body>
2259
+ </html>`;
2260
+ };
2261
+ var htmlResponse = (body) => new Response(body, {
2262
+ status: 200,
2263
+ headers: {
2264
+ "content-type": "text/html; charset=utf-8",
2265
+ "cache-control": "no-store"
2266
+ }
2267
+ });
2268
+ var json2 = (body) => new Response(JSON.stringify(body), {
2269
+ status: 200,
2270
+ headers: { "content-type": "application/json; charset=utf-8" }
2271
+ });
2272
+ var adminUiRoutes = (service, ui) => {
2273
+ const shell = () => renderAdminDocument(service);
2274
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2275
+ return {
2276
+ "GET /ui": () => htmlResponse(document2()),
2277
+ "GET /ui/": () => htmlResponse(document2()),
2278
+ "GET /ui/manifest": () => json2({
2279
+ service,
2280
+ panels: (ui?.panels ?? []).map((panel) => ({
2281
+ id: panel.id,
2282
+ title: panel.title,
2283
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2284
+ html: panel.html,
2285
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2286
+ }))
2287
+ })
2288
+ };
2289
+ };
2290
+
1359
2291
  // ../../openapi/metadata/dist/types.js
1360
2292
  var EXTENSION_KEYS = {
1361
2293
  operation: "x-mockingbird",
@@ -1593,8 +2525,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1593
2525
  });
1594
2526
  };
1595
2527
 
2528
+ // ../core/dist/state-view.js
2529
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2530
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2531
+ var SAMPLE = 25;
2532
+ var WALK_LIMIT = 1e4;
2533
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2534
+ var fail2 = (status, message) => ({ ok: false, status, message });
2535
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2536
+ var kindOf = (value) => {
2537
+ if (value === null)
2538
+ return "null";
2539
+ if (Array.isArray(value))
2540
+ return "array";
2541
+ switch (typeof value) {
2542
+ case "string":
2543
+ return "string";
2544
+ case "number":
2545
+ return Number.isFinite(value) ? "number" : "unknown";
2546
+ case "boolean":
2547
+ return "boolean";
2548
+ case "object":
2549
+ return "object";
2550
+ default:
2551
+ return "unknown";
2552
+ }
2553
+ };
2554
+ var humanize = (name) => {
2555
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2556
+ if (words === "")
2557
+ return name;
2558
+ return words.charAt(0).toUpperCase() + words.slice(1);
2559
+ };
2560
+ var jsonValue = (value) => {
2561
+ if (value === void 0)
2562
+ return fail2(400, "value is required");
2563
+ try {
2564
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2565
+ } catch {
2566
+ return fail2(400, "value must be JSON");
2567
+ }
2568
+ };
2569
+ var ctorName = (value) => {
2570
+ const ctor = value.constructor;
2571
+ return typeof ctor?.name === "string" ? ctor.name : "";
2572
+ };
2573
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2574
+ var discoverCollections = (root) => {
2575
+ const found = [];
2576
+ const seen = /* @__PURE__ */ new Set();
2577
+ const visit = (value, depth) => {
2578
+ if (found.length + seen.size > WALK_LIMIT)
2579
+ return;
2580
+ if (value === null || typeof value !== "object")
2581
+ return;
2582
+ if (seen.has(value))
2583
+ return;
2584
+ seen.add(value);
2585
+ if (value instanceof Collection) {
2586
+ found.push(value);
2587
+ return;
2588
+ }
2589
+ if (value instanceof Map) {
2590
+ for (const child of value.values())
2591
+ visit(child, depth + 1);
2592
+ return;
2593
+ }
2594
+ if (value instanceof Set) {
2595
+ for (const child of value.values())
2596
+ visit(child, depth + 1);
2597
+ return;
2598
+ }
2599
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2600
+ return;
2601
+ if (Array.isArray(value)) {
2602
+ const cap = Math.min(value.length, 32);
2603
+ for (let i = 0; i < cap; i++)
2604
+ visit(value[i], depth + 1);
2605
+ return;
2606
+ }
2607
+ let children;
2608
+ try {
2609
+ children = Object.values(value);
2610
+ } catch {
2611
+ return;
2612
+ }
2613
+ for (const child of children)
2614
+ visit(child, depth + 1);
2615
+ };
2616
+ visit(root, 0);
2617
+ return found;
2618
+ };
2619
+ var storedNames = (sqlite, namespace) => {
2620
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2621
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2622
+ return [...records, ...sequences].map((row) => row.name);
2623
+ };
2624
+ var blankAccum = (name) => ({
2625
+ name,
2626
+ kinds: /* @__PURE__ */ new Set(),
2627
+ present: 0,
2628
+ nested: /* @__PURE__ */ new Map()
2629
+ });
2630
+ var absorb = (accum, value) => {
2631
+ const kind = kindOf(value);
2632
+ accum.kinds.add(kind);
2633
+ accum.present++;
2634
+ if (!isRecord3(value))
2635
+ return;
2636
+ for (const [key, child] of Object.entries(value)) {
2637
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2638
+ absorb(nested, child);
2639
+ accum.nested.set(key, nested);
2640
+ }
2641
+ };
2642
+ var finishField = (accum, samples) => {
2643
+ const kinds = [...accum.kinds];
2644
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2645
+ const field = {
2646
+ name: accum.name,
2647
+ kind,
2648
+ optional: accum.present < samples || kinds.includes("null")
2649
+ };
2650
+ if (accum.nested.size > 0) {
2651
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2652
+ }
2653
+ return field;
2654
+ };
2655
+ var inferFields = (records) => {
2656
+ if (records.length === 0)
2657
+ return [];
2658
+ const sample = records.slice(0, SAMPLE);
2659
+ const objects = sample.filter((record) => isRecord3(record.value));
2660
+ if (objects.length === 0) {
2661
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2662
+ const list = [...kinds];
2663
+ return [
2664
+ {
2665
+ name: "(value)",
2666
+ kind: list.length === 1 ? list[0] : "unknown",
2667
+ optional: false
2668
+ }
2669
+ ];
2670
+ }
2671
+ const root = /* @__PURE__ */ new Map();
2672
+ for (const record of objects) {
2673
+ for (const [key, value] of Object.entries(record.value)) {
2674
+ const accum = root.get(key) ?? blankAccum(key);
2675
+ absorb(accum, value);
2676
+ root.set(key, accum);
2677
+ }
2678
+ }
2679
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2680
+ };
2681
+ var mergeFields = (declared, inferred) => {
2682
+ const byName = /* @__PURE__ */ new Map();
2683
+ for (const field of inferred)
2684
+ byName.set(field.name, field);
2685
+ const ordered = [];
2686
+ const seen = /* @__PURE__ */ new Set();
2687
+ for (const field of declared ?? []) {
2688
+ const found = byName.get(field.name);
2689
+ seen.add(field.name);
2690
+ if (!found) {
2691
+ ordered.push({ ...field, optional: field.optional });
2692
+ continue;
2693
+ }
2694
+ ordered.push({
2695
+ ...found,
2696
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2697
+ optional: field.optional || found.optional,
2698
+ ...field.description !== void 0 ? { description: field.description } : {},
2699
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2700
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2701
+ });
2702
+ }
2703
+ for (const field of inferred) {
2704
+ if (!seen.has(field.name))
2705
+ ordered.push(field);
2706
+ }
2707
+ return ordered;
2708
+ };
2709
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2710
+ var readRecord = (collection, id) => {
2711
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2712
+ const row = rows.find((entry) => entry.id === id);
2713
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2714
+ };
2715
+ var inspectState = (scope) => {
2716
+ const declared = /* @__PURE__ */ new Map();
2717
+ for (const declaration of scope.declarations ?? []) {
2718
+ if (COLLECTION_NAME.test(declaration.name))
2719
+ declared.set(declaration.name, declaration);
2720
+ }
2721
+ const names = new Set(declared.keys());
2722
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2723
+ names.add(name);
2724
+ for (const collection of discoverCollections(scope.root)) {
2725
+ if (collection.namespace === scope.storageNamespace)
2726
+ names.add(collection.collectionName);
2727
+ }
2728
+ const collections = [];
2729
+ for (const name of names) {
2730
+ if (!COLLECTION_NAME.test(name))
2731
+ continue;
2732
+ const declaration = declared.get(name);
2733
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2734
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2735
+ const inferred = inferFields(records);
2736
+ const fields = mergeFields(declaration?.fields, inferred);
2737
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2738
+ collections.push({
2739
+ name,
2740
+ label: declaration?.label ?? humanize(name),
2741
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2742
+ count: collection.count(),
2743
+ source,
2744
+ fields,
2745
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2746
+ });
2747
+ }
2748
+ const order = /* @__PURE__ */ new Map();
2749
+ for (const [index, item] of (scope.declarations ?? []).entries())
2750
+ order.set(item.name, index);
2751
+ collections.sort((a, b) => {
2752
+ const left = order.get(a.name);
2753
+ const right = order.get(b.name);
2754
+ if (left !== void 0 && right !== void 0)
2755
+ return left - right;
2756
+ if (left !== void 0)
2757
+ return -1;
2758
+ if (right !== void 0)
2759
+ return 1;
2760
+ return a.name.localeCompare(b.name);
2761
+ });
2762
+ return {
2763
+ namespace: scope.namespace,
2764
+ storageNamespace: scope.storageNamespace,
2765
+ collections
2766
+ };
2767
+ };
2768
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2769
+ if (!COLLECTION_NAME.test(name))
2770
+ return fail2(400, "collection name is not allowed");
2771
+ const limit = query.limit ?? 50;
2772
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2773
+ return fail2(400, "limit must be an integer from 1 to 200");
2774
+ }
2775
+ const order = query.order ?? "newest";
2776
+ if (order !== "newest" && order !== "oldest")
2777
+ return fail2(400, 'order must be "newest" or "oldest"');
2778
+ const collection = collectionOf(sqlite, storageNamespace, name);
2779
+ const rows = collection.list({ order }).filter((row) => {
2780
+ if (query.after === void 0)
2781
+ return true;
2782
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2783
+ });
2784
+ const slice = rows.slice(0, limit);
2785
+ const last = slice.at(-1);
2786
+ return {
2787
+ ok: true,
2788
+ value: {
2789
+ collection: name,
2790
+ count: collection.count(),
2791
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2792
+ next: rows.length > limit && last ? last.seq : null
2793
+ }
2794
+ };
2795
+ };
2796
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2797
+ var readStateRecord = (scope, name, id) => {
2798
+ if (!COLLECTION_NAME.test(name))
2799
+ return fail2(400, "collection name is not allowed");
2800
+ if (!RECORD_ID.test(id))
2801
+ return fail2(400, "record id is not allowed");
2802
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2803
+ return record ? { ok: true, value: record } : fail2(404, `no record ${id} in ${name}`);
2804
+ };
2805
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail2(400, "id must be a single path segment");
2806
+ var createStateRecord = (scope, name, input) => {
2807
+ if (!COLLECTION_NAME.test(name))
2808
+ return fail2(400, "collection name is not allowed");
2809
+ const parsed = jsonValue(input.value);
2810
+ if (!parsed.ok)
2811
+ return parsed;
2812
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2813
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2814
+ const checked = requireId(id);
2815
+ if (!checked.ok)
2816
+ return checked;
2817
+ if (collection.has(checked.value))
2818
+ return fail2(409, `record ${checked.value} already exists`);
2819
+ const stored = collection.insert(checked.value, parsed.value);
2820
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2821
+ };
2822
+ var replaceStateRecord = (scope, name, id, value) => {
2823
+ if (!COLLECTION_NAME.test(name))
2824
+ return fail2(400, "collection name is not allowed");
2825
+ const checked = requireId(id);
2826
+ if (!checked.ok)
2827
+ return checked;
2828
+ const parsed = jsonValue(value);
2829
+ if (!parsed.ok)
2830
+ return parsed;
2831
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2832
+ if (!collection.has(checked.value))
2833
+ return fail2(404, `no record ${checked.value} in ${name}`);
2834
+ const stored = collection.update(checked.value, parsed.value);
2835
+ if (!stored)
2836
+ return fail2(404, `no record ${checked.value} in ${name}`);
2837
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2838
+ };
2839
+ var patchStateRecord = (scope, name, id, value) => {
2840
+ const current = readStateRecord(scope, name, id);
2841
+ if (!current.ok)
2842
+ return current;
2843
+ const parsed = jsonValue(value);
2844
+ if (!parsed.ok)
2845
+ return parsed;
2846
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2847
+ return replaceStateRecord(scope, name, id, next);
2848
+ };
2849
+ var deleteStateRecord = (scope, name, id) => {
2850
+ if (!COLLECTION_NAME.test(name))
2851
+ return fail2(400, "collection name is not allowed");
2852
+ const checked = requireId(id);
2853
+ if (!checked.ok)
2854
+ return checked;
2855
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2856
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail2(404, `no record ${checked.value} in ${name}`);
2857
+ };
2858
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2859
+ status,
2860
+ headers: { "content-type": "application/json; charset=utf-8" }
2861
+ });
2862
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2863
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2864
+ var integerParam = (value) => {
2865
+ if (value === null)
2866
+ return void 0;
2867
+ if (!/^-?\d+$/.test(value))
2868
+ return "bad";
2869
+ return Number(value);
2870
+ };
2871
+ var stateAdminRoutes = (routes) => {
2872
+ const open = (namespace) => {
2873
+ try {
2874
+ return { ok: true, value: routes.open(namespace) };
2875
+ } catch (error) {
2876
+ return fail2(400, error instanceof Error ? error.message : String(error));
2877
+ }
2878
+ };
2879
+ const wrote = (namespace) => {
2880
+ routes.afterWrite?.(namespace);
2881
+ };
2882
+ return {
2883
+ "GET /state": ({ namespace }) => {
2884
+ const scope = open(namespace);
2885
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2886
+ },
2887
+ "GET /state/:collection": ({ namespace, params, url }) => {
2888
+ const scope = open(namespace);
2889
+ if (!scope.ok)
2890
+ return fromResult(scope, 200);
2891
+ const limit = integerParam(url.searchParams.get("limit"));
2892
+ const after = integerParam(url.searchParams.get("after"));
2893
+ if (limit === "bad")
2894
+ return adminError2(400, "limit: expected an integer");
2895
+ if (after === "bad")
2896
+ return adminError2(400, "after: expected a sequence number");
2897
+ const order = url.searchParams.get("order");
2898
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2899
+ ...limit !== void 0 ? { limit } : {},
2900
+ ...after !== void 0 ? { after } : {},
2901
+ ...order === "newest" || order === "oldest" ? { order } : {}
2902
+ }), 200);
2903
+ },
2904
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2905
+ const scope = open(namespace);
2906
+ if (!scope.ok)
2907
+ return fromResult(scope, 200);
2908
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2909
+ },
2910
+ "POST /state/:collection": ({ namespace, params, body }) => {
2911
+ const scope = open(namespace);
2912
+ if (!scope.ok)
2913
+ return fromResult(scope, 201);
2914
+ if (!isRecord3(body) || !("value" in body)) {
2915
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2916
+ }
2917
+ const id = body.id;
2918
+ if (id !== void 0 && typeof id !== "string")
2919
+ return adminError2(400, "id must be a string");
2920
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2921
+ ...typeof id === "string" ? { id } : {},
2922
+ value: body.value
2923
+ });
2924
+ if (created.ok)
2925
+ wrote(namespace);
2926
+ return fromResult(created, 201);
2927
+ },
2928
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2929
+ const scope = open(namespace);
2930
+ if (!scope.ok)
2931
+ return fromResult(scope, 200);
2932
+ if (!isRecord3(body) || !("value" in body))
2933
+ return adminError2(400, 'expected {"value": <json>}');
2934
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2935
+ if (replaced.ok)
2936
+ wrote(namespace);
2937
+ return fromResult(replaced, 200);
2938
+ },
2939
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2940
+ const scope = open(namespace);
2941
+ if (!scope.ok)
2942
+ return fromResult(scope, 200);
2943
+ if (!isRecord3(body) || !("value" in body))
2944
+ return adminError2(400, 'expected {"value": <json>}');
2945
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2946
+ if (patched.ok)
2947
+ wrote(namespace);
2948
+ return fromResult(patched, 200);
2949
+ },
2950
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2951
+ const scope = open(namespace);
2952
+ if (!scope.ok)
2953
+ return fromResult(scope, 200);
2954
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2955
+ if (removed.ok)
2956
+ wrote(namespace);
2957
+ return fromResult(removed, 200);
2958
+ }
2959
+ };
2960
+ };
2961
+
1596
2962
  // ../core/dist/version.js
1597
- var PACKAGE_VERSION = true ? "1.2.0" : UNRELEASED_VERSION;
2963
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1598
2964
 
1599
2965
  // ../core/dist/signing.js
1600
2966
  var encoder = new TextEncoder();
@@ -1929,11 +3295,11 @@ var createWebhookHub = (options) => {
1929
3295
  };
1930
3296
  return hub;
1931
3297
  };
1932
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1933
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1934
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3298
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
3299
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
3300
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1935
3301
  var parseEndpoint = (value) => {
1936
- if (!isRecord3(value) || typeof value.url !== "string")
3302
+ if (!isRecord4(value) || typeof value.url !== "string")
1937
3303
  return "each endpoint needs a url";
1938
3304
  try {
1939
3305
  new URL(value.url);
@@ -1950,18 +3316,18 @@ var parseEndpoint = (value) => {
1950
3316
  const events = value.events ?? value.enabledEvents;
1951
3317
  if (Array.isArray(events))
1952
3318
  endpoint.events = events.map(String);
1953
- if (isRecord3(value.tags)) {
3319
+ if (isRecord4(value.tags)) {
1954
3320
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1955
3321
  }
1956
3322
  if (typeof value.account === "string")
1957
3323
  endpoint.tags = { ...endpoint.tags, account: value.account };
1958
- if (isRecord3(value.headers)) {
3324
+ if (isRecord4(value.headers)) {
1959
3325
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1960
3326
  }
1961
3327
  return endpoint;
1962
3328
  };
1963
3329
  var webhookAdminRoutes = (hub) => ({
1964
- "GET /webhooks": ({ url, namespace }) => json2(200, {
3330
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
1965
3331
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1966
3332
  const type = url.searchParams.get("type");
1967
3333
  return type === null || d.type === type;
@@ -1969,51 +3335,51 @@ var webhookAdminRoutes = (hub) => ({
1969
3335
  }),
1970
3336
  "GET /webhooks/events": ({ url, namespace }) => {
1971
3337
  const type = url.searchParams.get("type");
1972
- return json2(200, {
3338
+ return json4(200, {
1973
3339
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1974
3340
  });
1975
3341
  },
1976
3342
  "POST /webhooks/:id/replay": async ({ params }) => {
1977
3343
  const replayed = await hub.replay(params.id);
1978
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
3344
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1979
3345
  },
1980
3346
  "POST /webhooks/flush": async () => {
1981
3347
  await hub.flush();
1982
- return json2(200, { status: "ok" });
3348
+ return json4(200, { status: "ok" });
1983
3349
  },
1984
3350
  "POST /webhooks/faults": ({ body, namespace }) => {
1985
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1986
- return adminError2(400, "mode must be duplicate, reorder or drop");
3351
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3352
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1987
3353
  }
1988
3354
  const fault = { mode: body.mode };
1989
3355
  if (typeof body.count === "number")
1990
3356
  fault.count = body.count;
1991
3357
  hub.fault(namespace, fault);
1992
- return json2(201, { namespace, ...fault });
3358
+ return json4(201, { namespace, ...fault });
1993
3359
  },
1994
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
3360
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
1995
3361
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1996
3362
  ...rest,
1997
3363
  secret: secret ? "(set)" : null
1998
3364
  }))
1999
3365
  }),
2000
3366
  "PUT /webhook-endpoints": ({ body, namespace }) => {
2001
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
3367
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
2002
3368
  if (!Array.isArray(list))
2003
- return adminError2(400, "expected [{url, secret?, events?}]");
3369
+ return adminError3(400, "expected [{url, secret?, events?}]");
2004
3370
  const parsed = [];
2005
3371
  for (const each of list) {
2006
3372
  const endpoint = parseEndpoint(each);
2007
3373
  if (typeof endpoint === "string")
2008
- return adminError2(400, endpoint);
3374
+ return adminError3(400, endpoint);
2009
3375
  parsed.push(endpoint);
2010
3376
  }
2011
3377
  const set = hub.setEndpoints(namespace, parsed);
2012
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3378
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2013
3379
  },
2014
3380
  "DELETE /webhook-endpoints": ({ namespace }) => {
2015
3381
  hub.setEndpoints(namespace, []);
2016
- return json2(200, { status: "ok" });
3382
+ return json4(200, { status: "ok" });
2017
3383
  }
2018
3384
  });
2019
3385
  var parsePayload = (message) => {
@@ -2078,6 +3444,7 @@ var operationMatcher = (document2) => {
2078
3444
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
2079
3445
  };
2080
3446
  var createRuntime = (options) => {
3447
+ assertAdminUi(options.adminUi);
2081
3448
  const sqlite = bootSqlite(options.sqlite);
2082
3449
  const clock = options.clock ?? createClock();
2083
3450
  const rng = createRng(options.seed ?? 0);
@@ -2284,6 +3651,19 @@ var createRuntime = (options) => {
2284
3651
  else
2285
3652
  timeline(name);
2286
3653
  };
3654
+ const declarationsFor = (namespace) => {
3655
+ const declared = options.state;
3656
+ if (!declared)
3657
+ return [];
3658
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3659
+ };
3660
+ const stateScope = (namespace) => ({
3661
+ sqlite,
3662
+ namespace,
3663
+ storageNamespace: storageNamespace(namespace),
3664
+ root: instance(namespace),
3665
+ declarations: declarationsFor(namespace)
3666
+ });
2287
3667
  const runtime = {
2288
3668
  name: options.name,
2289
3669
  sqlite,
@@ -2322,6 +3702,7 @@ var createRuntime = (options) => {
2322
3702
  branch,
2323
3703
  checkout,
2324
3704
  timeline,
3705
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
2325
3706
  fetch: async (incoming) => {
2326
3707
  let request = incoming;
2327
3708
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2515,11 +3896,20 @@ var createRuntime = (options) => {
2515
3896
  ...credentialRoutes(credentials),
2516
3897
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2517
3898
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2518
- ...options.admin?.(runtime) ?? {}
3899
+ ...options.admin?.(runtime) ?? {},
3900
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3901
+ // beside these; it does not replace `/state` or `/ui`.
3902
+ ...stateAdminRoutes({
3903
+ open: stateScope,
3904
+ afterWrite: (namespace) => {
3905
+ checkpoint(namespace, "main");
3906
+ }
3907
+ }),
3908
+ ...adminUiRoutes(options.name, options.adminUi)
2519
3909
  },
2520
3910
  adminKey: options.adminKey
2521
3911
  });
2522
- return runtime;
3912
+ return defineMock(runtime);
2523
3913
  };
2524
3914
  var mutableResponse = (response) => {
2525
3915
  try {
@@ -2781,9 +4171,9 @@ var FULLSCRIPT_PRESETS = {
2781
4171
  },
2782
4172
  webhook_drop: { description: "The next webhook is never delivered", webhook: { mode: "drop" } }
2783
4173
  };
2784
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2785
- var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2786
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4174
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4175
+ var adminError4 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
4176
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2787
4177
  var echoes = async (response, challenge) => {
2788
4178
  try {
2789
4179
  const body = await response.clone().json();
@@ -2794,21 +4184,21 @@ var echoes = async (response, challenge) => {
2794
4184
  };
2795
4185
  var adminRoutes = (send, challenge) => (runtime) => ({
2796
4186
  "POST /oauth/codes": ({ body, namespace }) => {
2797
- const input = isRecord4(body) ? body : {};
4187
+ const input = isRecord5(body) ? body : {};
2798
4188
  const api = runtime.instance(namespace);
2799
4189
  const practitionerId = typeof input.practitionerId === "string" ? input.practitionerId : "prac_mock_1";
2800
4190
  if (!api.state.practitioners.get(practitionerId))
2801
- return adminError3(404, `no practitioner ${practitionerId}`);
4191
+ return adminError4(404, `no practitioner ${practitionerId}`);
2802
4192
  const code = api.issueCode(
2803
4193
  practitionerId,
2804
4194
  typeof input.clientId === "string" ? input.clientId : "any",
2805
4195
  typeof input.redirectUri === "string" ? input.redirectUri : null
2806
4196
  );
2807
- return json3(201, { code });
4197
+ return json5(201, { code });
2808
4198
  },
2809
4199
  "POST /practitioners": ({ body, namespace }) => {
2810
- if (!isRecord4(body) || typeof body.id !== "string" || typeof body.clinicId !== "string") {
2811
- return adminError3(
4200
+ if (!isRecord5(body) || typeof body.id !== "string" || typeof body.clinicId !== "string") {
4201
+ return adminError4(
2812
4202
  400,
2813
4203
  'expected {"id", "clinicId", "type"?: "Practitioner"|"Staff", "clinicName"?}'
2814
4204
  );
@@ -2827,12 +4217,12 @@ var adminRoutes = (send, challenge) => (runtime) => ({
2827
4217
  type: body.type === "Staff" ? "Staff" : "Practitioner"
2828
4218
  };
2829
4219
  api.state.practitioners.insert(practitioner.id, practitioner);
2830
- return json3(201, practitioner);
4220
+ return json5(201, practitioner);
2831
4221
  },
2832
- "GET /lab-orders": ({ namespace }) => json3(200, { orders: runtime.instance(namespace).labOrders() }),
4222
+ "GET /lab-orders": ({ namespace }) => json5(200, { orders: runtime.instance(namespace).labOrders() }),
2833
4223
  "POST /lab-orders": ({ body, namespace }) => {
2834
- if (!isRecord4(body) || typeof body.patientId !== "string") {
2835
- return adminError3(
4224
+ if (!isRecord5(body) || typeof body.patientId !== "string") {
4225
+ return adminError4(
2836
4226
  400,
2837
4227
  'expected {"patientId", "id"?, "clinicId"?, "treatmentPlanId"?, "name"?, "collectionMethod"?, "tests"?: [names]}'
2838
4228
  );
@@ -2847,23 +4237,23 @@ var adminRoutes = (send, challenge) => (runtime) => ({
2847
4237
  ...text("collectionMethod"),
2848
4238
  ...Array.isArray(body.tests) ? { tests: body.tests.map(String) } : {}
2849
4239
  });
2850
- return json3(201, order);
4240
+ return json5(201, order);
2851
4241
  },
2852
4242
  "POST /lab-orders/:id/transition": ({ params, body, namespace }) => {
2853
- if (!isRecord4(body) || !isLabOrderState(body.to)) {
2854
- return adminError3(
4243
+ if (!isRecord5(body) || !isLabOrderState(body.to)) {
4244
+ return adminError4(
2855
4245
  400,
2856
4246
  'expected {"to": "<purchased|schedule_appointment|upcoming_appointment|processing|partial_results|results_ready|interpretation_shared|results_amended>"}'
2857
4247
  );
2858
4248
  }
2859
4249
  try {
2860
- return json3(200, runtime.instance(namespace).transition(params.id, body.to));
4250
+ return json5(200, runtime.instance(namespace).transition(params.id, body.to));
2861
4251
  } catch (error) {
2862
4252
  if (error instanceof HttpError) return error.toResponse();
2863
4253
  throw error;
2864
4254
  }
2865
4255
  },
2866
- "GET /events": ({ namespace }) => json3(200, { events: runtime.instance(namespace).eventsList() }),
4256
+ "GET /events": ({ namespace }) => json5(200, { events: runtime.instance(namespace).eventsList() }),
2867
4257
  "POST /webhooks/verify": async ({ namespace }) => {
2868
4258
  const endpoints = runtime.webhooks?.endpoints(namespace) ?? [];
2869
4259
  const results = await Promise.all(
@@ -2889,29 +4279,29 @@ var adminRoutes = (send, challenge) => (runtime) => ({
2889
4279
  }
2890
4280
  })
2891
4281
  );
2892
- return json3(200, { endpoints: results });
4282
+ return json5(200, { endpoints: results });
2893
4283
  },
2894
- "GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
4284
+ "GET /settings": ({ namespace }) => json5(200, runtime.instance(namespace).state.current()),
2895
4285
  "PUT /settings": ({ body, namespace }) => {
2896
- if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
4286
+ if (!isRecord5(body)) return adminError4(400, "expected a JSON object");
2897
4287
  const patch = {};
2898
4288
  for (const key of ["accessTokenTtlSeconds", "codeTtlSeconds", "pdfUrlTtlSeconds"]) {
2899
4289
  if (body[key] !== void 0) {
2900
- if (typeof body[key] !== "number") return adminError3(400, `${key}: number`);
4290
+ if (typeof body[key] !== "number") return adminError4(400, `${key}: number`);
2901
4291
  patch[key] = body[key];
2902
4292
  }
2903
4293
  }
2904
4294
  if (body.resultsBaseUrl !== void 0) {
2905
4295
  if (body.resultsBaseUrl !== null && typeof body.resultsBaseUrl !== "string")
2906
- return adminError3(400, "resultsBaseUrl: string | null");
4296
+ return adminError4(400, "resultsBaseUrl: string | null");
2907
4297
  patch.resultsBaseUrl = body.resultsBaseUrl;
2908
4298
  }
2909
4299
  if (body.clients !== void 0) {
2910
4300
  if (!Array.isArray(body.clients))
2911
- return adminError3(400, "clients: [{clientId, clientSecret}]");
2912
- patch.clients = body.clients.filter(isRecord4).map((c) => ({ clientId: String(c.clientId), clientSecret: String(c.clientSecret) }));
4301
+ return adminError4(400, "clients: [{clientId, clientSecret}]");
4302
+ patch.clients = body.clients.filter(isRecord5).map((c) => ({ clientId: String(c.clientId), clientSecret: String(c.clientSecret) }));
2913
4303
  }
2914
- return json3(200, runtime.instance(namespace).state.update(patch));
4304
+ return json5(200, runtime.instance(namespace).state.update(patch));
2915
4305
  }
2916
4306
  });
2917
4307
  var createRuntime2 = (options = {}) => {
@@ -3493,4 +4883,4 @@ export {
3493
4883
  envelope,
3494
4884
  FullscriptAPI
3495
4885
  };
3496
- //# sourceMappingURL=chunk-7353U527.js.map
4886
+ //# sourceMappingURL=chunk-FLCK7ECX.js.map