@crvouga/mockingbird-service-bedrock 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;
@@ -700,64 +702,64 @@ var graphemeLength = (value) => [...value].length;
700
702
  var validateValue = (document2, schema, value, path = []) => {
701
703
  const errors = [];
702
704
  const s = resolveSchema(document2, schema);
703
- const fail2 = (message) => errors.push({ path, message });
705
+ const fail3 = (message) => errors.push({ path, message });
704
706
  const actual = jsonTypeOf(value);
705
707
  if (actual === "undefined") {
706
- fail2("value is undefined");
708
+ fail3("value is undefined");
707
709
  return errors;
708
710
  }
709
711
  const types = schemaTypes(s);
710
712
  if (types.length > 0) {
711
713
  const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
712
714
  if (!ok) {
713
- fail2(`expected type ${types.join("|")}, got ${actual}`);
715
+ fail3(`expected type ${types.join("|")}, got ${actual}`);
714
716
  return errors;
715
717
  }
716
718
  }
717
719
  if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
718
- fail2("value not in enum");
720
+ fail3("value not in enum");
719
721
  }
720
722
  if (s.const !== void 0 && !deepEqual(s.const, value))
721
- fail2("value does not equal const");
723
+ fail3("value does not equal const");
722
724
  if (typeof value === "string") {
723
725
  const length = graphemeLength(value);
724
726
  if (s.minLength !== void 0 && length < s.minLength)
725
- fail2(`length ${length} < minLength ${s.minLength}`);
727
+ fail3(`length ${length} < minLength ${s.minLength}`);
726
728
  if (s.maxLength !== void 0 && length > s.maxLength)
727
- fail2(`length ${length} > maxLength ${s.maxLength}`);
729
+ fail3(`length ${length} > maxLength ${s.maxLength}`);
728
730
  if (s.pattern !== void 0) {
729
731
  try {
730
732
  if (!new RegExp(s.pattern, "u").test(value))
731
- fail2(`does not match pattern ${s.pattern}`);
733
+ fail3(`does not match pattern ${s.pattern}`);
732
734
  } catch {
733
735
  }
734
736
  }
735
737
  if (s.format !== void 0) {
736
738
  const pattern = FORMAT_PATTERNS[s.format];
737
739
  if (pattern && !pattern.test(value))
738
- fail2(`does not match format ${s.format}`);
740
+ fail3(`does not match format ${s.format}`);
739
741
  }
740
742
  }
741
743
  if (typeof value === "number") {
742
744
  if (s.minimum !== void 0 && value < s.minimum)
743
- fail2(`${value} < minimum ${s.minimum}`);
745
+ fail3(`${value} < minimum ${s.minimum}`);
744
746
  if (s.maximum !== void 0 && value > s.maximum)
745
- fail2(`${value} > maximum ${s.maximum}`);
747
+ fail3(`${value} > maximum ${s.maximum}`);
746
748
  if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
747
- fail2(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
749
+ fail3(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
748
750
  if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
749
- fail2(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
751
+ fail3(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
750
752
  if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
751
- fail2(`${value} is not a multiple of ${s.multipleOf}`);
753
+ fail3(`${value} is not a multiple of ${s.multipleOf}`);
752
754
  }
753
755
  }
754
756
  if (Array.isArray(value)) {
755
757
  if (s.minItems !== void 0 && value.length < s.minItems)
756
- fail2(`${value.length} items < minItems ${s.minItems}`);
758
+ fail3(`${value.length} items < minItems ${s.minItems}`);
757
759
  if (s.maxItems !== void 0 && value.length > s.maxItems)
758
- fail2(`${value.length} items > maxItems ${s.maxItems}`);
760
+ fail3(`${value.length} items > maxItems ${s.maxItems}`);
759
761
  if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
760
- fail2("items are not unique");
762
+ fail3("items are not unique");
761
763
  value.forEach((item, i) => {
762
764
  const itemSchema = s.prefixItems?.[i] ?? s.items;
763
765
  if (itemSchema)
@@ -769,11 +771,11 @@ var validateValue = (document2, schema, value, path = []) => {
769
771
  const keys = Object.keys(record);
770
772
  for (const name of s.required ?? [])
771
773
  if (!(name in record))
772
- fail2(`missing required property ${name}`);
774
+ fail3(`missing required property ${name}`);
773
775
  if (s.minProperties !== void 0 && keys.length < s.minProperties)
774
- fail2(`${keys.length} properties < minProperties ${s.minProperties}`);
776
+ fail3(`${keys.length} properties < minProperties ${s.minProperties}`);
775
777
  if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
776
- fail2(`${keys.length} properties > maxProperties ${s.maxProperties}`);
778
+ fail3(`${keys.length} properties > maxProperties ${s.maxProperties}`);
777
779
  for (const key of keys) {
778
780
  const property = s.properties?.[key];
779
781
  if (property) {
@@ -781,14 +783,14 @@ var validateValue = (document2, schema, value, path = []) => {
781
783
  continue;
782
784
  }
783
785
  if (s.additionalProperties === false)
784
- fail2(`unexpected property ${key}`);
786
+ fail3(`unexpected property ${key}`);
785
787
  else if (typeof s.additionalProperties === "object") {
786
788
  errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
787
789
  }
788
790
  if (s.propertyNames) {
789
791
  const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
790
792
  if (nameErrors.length > 0)
791
- fail2(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
793
+ fail3(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
792
794
  }
793
795
  }
794
796
  }
@@ -796,14 +798,14 @@ var validateValue = (document2, schema, value, path = []) => {
796
798
  for (const branch of s.allOf)
797
799
  errors.push(...validateValue(document2, branch, value, path));
798
800
  if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
799
- fail2("matches no anyOf branch");
801
+ fail3("matches no anyOf branch");
800
802
  if (s.oneOf) {
801
803
  const matches3 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
802
804
  if (matches3 !== 1)
803
- fail2(`matches ${matches3} oneOf branches, expected exactly 1`);
805
+ fail3(`matches ${matches3} oneOf branches, expected exactly 1`);
804
806
  }
805
807
  if (s.not && validateValue(document2, s.not, value).length === 0)
806
- fail2("matches forbidden `not` schema");
808
+ fail3("matches forbidden `not` schema");
807
809
  return errors;
808
810
  };
809
811
 
@@ -1335,6 +1337,936 @@ var clearNamespace = (sqlite, namespace) => {
1335
1337
  });
1336
1338
  };
1337
1339
 
1340
+ // ../core/dist/surface.js
1341
+ var defineMock = (runtime) => runtime;
1342
+ var STANDARD_ADMIN_ROUTES = [
1343
+ "GET /",
1344
+ "POST /reset",
1345
+ "GET /namespaces",
1346
+ "GET /clock",
1347
+ "POST /clock",
1348
+ "GET /faults",
1349
+ "POST /faults",
1350
+ "DELETE /faults",
1351
+ "POST /snapshots",
1352
+ "POST /snapshots/:id/restore",
1353
+ "DELETE /snapshots/:id",
1354
+ "GET /timeline",
1355
+ "POST /checkpoints",
1356
+ "POST /branches/:name",
1357
+ "POST /branches/:name/checkout",
1358
+ "GET /requests",
1359
+ "DELETE /requests",
1360
+ "GET /metrics",
1361
+ "DELETE /metrics",
1362
+ "GET /credentials",
1363
+ "PUT /credentials",
1364
+ "DELETE /credentials",
1365
+ "GET /state",
1366
+ "GET /state/:collection",
1367
+ "GET /state/:collection/:id",
1368
+ "POST /state/:collection",
1369
+ "PUT /state/:collection/:id",
1370
+ "PATCH /state/:collection/:id",
1371
+ "DELETE /state/:collection/:id",
1372
+ "GET /ui",
1373
+ "GET /ui/",
1374
+ "GET /ui/manifest"
1375
+ ];
1376
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1377
+ var assertAdminUi = (ui) => {
1378
+ if (!ui?.panels)
1379
+ return;
1380
+ const seen = /* @__PURE__ */ new Set();
1381
+ for (const panel of ui.panels) {
1382
+ if (!PANEL_ID.test(panel.id)) {
1383
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1384
+ }
1385
+ if (seen.has(panel.id))
1386
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1387
+ seen.add(panel.id);
1388
+ if (panel.title.trim() === "")
1389
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1390
+ }
1391
+ };
1392
+
1393
+ // ../core/dist/admin-ui.js
1394
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1395
+ switch (char) {
1396
+ case "&":
1397
+ return "&amp;";
1398
+ case "<":
1399
+ return "&lt;";
1400
+ case ">":
1401
+ return "&gt;";
1402
+ case '"':
1403
+ return "&quot;";
1404
+ default:
1405
+ return "&#39;";
1406
+ }
1407
+ });
1408
+ var renderAdminDocument = (service) => {
1409
+ const name = escapeHtml(service);
1410
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1411
+ return `<!DOCTYPE html>
1412
+ <html lang="en">
1413
+ <head>
1414
+ <meta charset="utf-8">
1415
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1416
+ <meta name="color-scheme" content="light dark">
1417
+ <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">
1418
+ <title>${name} admin</title>
1419
+ <style>
1420
+ :root {
1421
+ color-scheme: light;
1422
+ --bg: #f6f5f2;
1423
+ --bg-elev: #ffffff;
1424
+ --bg-muted: #eeece6;
1425
+ --bg-inset: #f3f1eb;
1426
+ --line: #e2dfd6;
1427
+ --line-strong: #d0ccc1;
1428
+ --ink: #1c1915;
1429
+ --muted: #5e584f;
1430
+ --faint: #8a8378;
1431
+ --accent: #3d4f3a;
1432
+ --accent-ink: #f7f6f2;
1433
+ --accent-soft: #e5ece2;
1434
+ --ok: #1f7a45;
1435
+ --ok-soft: #e5f4eb;
1436
+ --warn: #9a6700;
1437
+ --warn-soft: #fbf3df;
1438
+ --err: #a33b32;
1439
+ --err-soft: #fdecea;
1440
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1441
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1442
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1443
+ --radius: 14px;
1444
+ --header: 60px;
1445
+ --nav: 220px;
1446
+ }
1447
+ :root[data-theme="dark"] {
1448
+ color-scheme: dark;
1449
+ --bg: #141311;
1450
+ --bg-elev: #1e1c19;
1451
+ --bg-muted: #26231f;
1452
+ --bg-inset: #181715;
1453
+ --line: #34302b;
1454
+ --line-strong: #4a453d;
1455
+ --ink: #f4f1ea;
1456
+ --muted: #c4bdb1;
1457
+ --faint: #8f877c;
1458
+ --accent: #c5d5b8;
1459
+ --accent-ink: #1a2118;
1460
+ --accent-soft: #2a3328;
1461
+ --ok: #8fd6a8;
1462
+ --ok-soft: #1a2e22;
1463
+ --warn: #f0cc78;
1464
+ --warn-soft: #332911;
1465
+ --err: #f0a8a2;
1466
+ --err-soft: #3a201e;
1467
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1468
+ }
1469
+ @media (prefers-color-scheme: dark) {
1470
+ :root:not([data-theme="light"]) {
1471
+ color-scheme: dark;
1472
+ --bg: #141311;
1473
+ --bg-elev: #1e1c19;
1474
+ --bg-muted: #26231f;
1475
+ --bg-inset: #181715;
1476
+ --line: #34302b;
1477
+ --line-strong: #4a453d;
1478
+ --ink: #f4f1ea;
1479
+ --muted: #c4bdb1;
1480
+ --faint: #8f877c;
1481
+ --accent: #c5d5b8;
1482
+ --accent-ink: #1a2118;
1483
+ --accent-soft: #2a3328;
1484
+ --ok: #8fd6a8;
1485
+ --ok-soft: #1a2e22;
1486
+ --warn: #f0cc78;
1487
+ --warn-soft: #332911;
1488
+ --err: #f0a8a2;
1489
+ --err-soft: #3a201e;
1490
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1491
+ }
1492
+ }
1493
+ * { box-sizing: border-box; }
1494
+ html, body { margin: 0; height: 100%; }
1495
+ body {
1496
+ font-family: var(--sans);
1497
+ background: var(--bg);
1498
+ color: var(--ink);
1499
+ line-height: 1.45;
1500
+ padding-left: env(safe-area-inset-left);
1501
+ padding-right: env(safe-area-inset-right);
1502
+ -webkit-text-size-adjust: 100%;
1503
+ }
1504
+ button, input, select, textarea { font: inherit; color: inherit; }
1505
+ button { cursor: pointer; }
1506
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1507
+ @media (prefers-reduced-motion: reduce) {
1508
+ * { scroll-behavior: auto !important; transition: none !important; }
1509
+ }
1510
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1511
+ header.top {
1512
+ position: sticky; top: 0; z-index: 5;
1513
+ display: flex; align-items: center; gap: 12px;
1514
+ min-height: var(--header); padding: 10px 16px;
1515
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1516
+ border-bottom: 1px solid var(--line);
1517
+ backdrop-filter: blur(10px);
1518
+ }
1519
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1520
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1521
+ .brand span { color: var(--faint); font-size: 12px; }
1522
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1523
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1524
+ label.field input, label.field select, .controls input[type="password"] {
1525
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1526
+ padding: 7px 8px; min-height: 36px;
1527
+ }
1528
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1529
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1530
+ background: var(--bg-elev);
1531
+ }
1532
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1533
+ .btn-quiet { background: transparent; }
1534
+ .btn-danger { color: var(--err); }
1535
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1536
+ record or the full nav row would widen the page past the viewport. */
1537
+ .layout {
1538
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1539
+ flex: 1; min-height: 0; min-width: 0;
1540
+ }
1541
+ nav.side {
1542
+ border-right: 1px solid var(--line); padding: 12px;
1543
+ display: flex; flex-direction: column; gap: 4px;
1544
+ background: var(--bg-elev);
1545
+ }
1546
+ nav.side button {
1547
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1548
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1549
+ }
1550
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1551
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1552
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1553
+ .lede { margin: 0 0 16px; color: var(--muted); }
1554
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1555
+ .card {
1556
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1557
+ padding: 14px 16px; box-shadow: var(--shadow);
1558
+ }
1559
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1560
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1561
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1562
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1563
+ .collection {
1564
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1565
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1566
+ }
1567
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1568
+ .collection small { display: block; color: var(--faint); }
1569
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1570
+ .chip {
1571
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1572
+ border-radius: 999px; padding: 4px 8px;
1573
+ }
1574
+ .chip i { color: var(--faint); font-style: normal; }
1575
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1576
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1577
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1578
+ tr.clickable { cursor: pointer; }
1579
+ tr.clickable:hover { background: var(--bg-muted); }
1580
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1581
+ pre {
1582
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1583
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1584
+ }
1585
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1586
+ .banner {
1587
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1588
+ background: var(--err-soft); color: var(--err);
1589
+ }
1590
+ .banner.show { display: block; }
1591
+ .empty { color: var(--muted); padding: 24px 8px; }
1592
+ dialog {
1593
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1594
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1595
+ }
1596
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1597
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1598
+ textarea {
1599
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1600
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1601
+ font-family: var(--mono); font-size: 12px;
1602
+ }
1603
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1604
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1605
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1606
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1607
+ .status-2 { color: var(--ok); }
1608
+ .status-4, .status-5, .status-0 { color: var(--err); }
1609
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1610
+ .route {
1611
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1612
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1613
+ }
1614
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1615
+ @media (max-width: 800px) {
1616
+ header.top {
1617
+ align-items: stretch; flex-direction: column;
1618
+ padding-top: max(10px, env(safe-area-inset-top));
1619
+ }
1620
+ input, select, textarea { font-size: 16px; }
1621
+ .controls { width: 100%; }
1622
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1623
+ .layout { grid-template-columns: minmax(0, 1fr); }
1624
+ nav.side {
1625
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1626
+ border-right: 0; border-bottom: 1px solid var(--line);
1627
+ padding: 8px;
1628
+ }
1629
+ nav.side button { white-space: nowrap; flex: none; }
1630
+ .split { grid-template-columns: minmax(0, 1fr); }
1631
+ main { padding: 14px; }
1632
+ table, thead, tbody, tr, th, td { display: block; }
1633
+ thead { display: none; }
1634
+ tr {
1635
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1636
+ background: var(--bg-elev); min-width: 0;
1637
+ }
1638
+ td {
1639
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1640
+ min-width: 0; overflow-wrap: anywhere;
1641
+ }
1642
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1643
+ .route { grid-template-columns: 72px 1fr; }
1644
+ .route button { grid-column: 1 / -1; }
1645
+ }
1646
+ </style>
1647
+ </head>
1648
+ <body>
1649
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1650
+ <header class="top">
1651
+ <div class="brand">
1652
+ <strong>${name}</strong>
1653
+ <span>Mockingbird admin</span>
1654
+ </div>
1655
+ <div class="controls">
1656
+ <label class="field">Namespace
1657
+ <select id="namespace" aria-label="Namespace"></select>
1658
+ </label>
1659
+ <label class="field">Admin key
1660
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1661
+ </label>
1662
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1663
+ <button class="btn" id="refresh" type="button">Refresh</button>
1664
+ </div>
1665
+ </header>
1666
+ <div class="layout">
1667
+ <nav class="side" id="nav" aria-label="Admin sections">
1668
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1669
+ <button type="button" data-view="state">State</button>
1670
+ <button type="button" data-view="clock">Clock</button>
1671
+ <button type="button" data-view="faults">Faults</button>
1672
+ <button type="button" data-view="journal">Journal</button>
1673
+ <button type="button" data-view="routes">Routes</button>
1674
+ </nav>
1675
+ <main id="views">
1676
+ <p class="banner" id="banner" role="alert"></p>
1677
+ <section class="view" id="view-overview">
1678
+ <h2>Overview</h2>
1679
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1680
+ <div class="grid" id="overview-cards"></div>
1681
+ <h3>Recent requests</h3>
1682
+ <div id="overview-requests"></div>
1683
+ </section>
1684
+ <section class="view" id="view-state" hidden>
1685
+ <h2>State</h2>
1686
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1687
+ <div class="split">
1688
+ <div id="collections"></div>
1689
+ <div>
1690
+ <div id="schema"></div>
1691
+ <div class="row-actions">
1692
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1693
+ </div>
1694
+ <div id="records"></div>
1695
+ </div>
1696
+ </div>
1697
+ </section>
1698
+ <section class="view" id="view-clock" hidden>
1699
+ <h2>Clock</h2>
1700
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1701
+ <div class="card" id="clock-readout"></div>
1702
+ <div class="row-actions">
1703
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1704
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1705
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1706
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1707
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1708
+ <button class="btn" id="freeze" type="button">Freeze</button>
1709
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1710
+ </div>
1711
+ <form id="clock-set" class="row-actions">
1712
+ <label class="field">Set instant
1713
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1714
+ </label>
1715
+ <button class="btn-primary" type="submit">Set</button>
1716
+ </form>
1717
+ </section>
1718
+ <section class="view" id="view-faults" hidden>
1719
+ <h2>Faults</h2>
1720
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1721
+ <form id="fault-form" class="card stack">
1722
+ <label class="field">Preset
1723
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1724
+ </label>
1725
+ <label class="field">Status
1726
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1727
+ </label>
1728
+ <label class="field">Path prefix
1729
+ <input id="fault-path" placeholder="/v1">
1730
+ </label>
1731
+ <label class="field">Method
1732
+ <input id="fault-method" placeholder="GET">
1733
+ </label>
1734
+ <div class="dialog-actions">
1735
+ <button class="btn-primary" type="submit">Add fault</button>
1736
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1737
+ </div>
1738
+ </form>
1739
+ <div id="fault-list"></div>
1740
+ </section>
1741
+ <section class="view" id="view-journal" hidden>
1742
+ <h2>Journal</h2>
1743
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1744
+ <div class="row-actions">
1745
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1746
+ </div>
1747
+ <div id="journal"></div>
1748
+ </section>
1749
+ <section class="view" id="view-routes" hidden>
1750
+ <h2>Routes</h2>
1751
+ <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>
1752
+ <div id="route-list"></div>
1753
+ <form id="route-form" class="card stack">
1754
+ <strong id="route-title">Select a route</strong>
1755
+ <label class="field">JSON body
1756
+ <textarea id="route-body" placeholder="{ }"></textarea>
1757
+ </label>
1758
+ <div class="dialog-actions">
1759
+ <button class="btn-primary" type="submit">Send</button>
1760
+ </div>
1761
+ <pre id="route-result">Response will show here.</pre>
1762
+ </form>
1763
+ </section>
1764
+ </main>
1765
+ </div>
1766
+ </div>
1767
+ <dialog id="editor">
1768
+ <form method="dialog" id="editor-form">
1769
+ <strong id="editor-title">Record</strong>
1770
+ <label class="field">Id
1771
+ <input id="editor-id" required>
1772
+ </label>
1773
+ <label class="field">JSON value
1774
+ <textarea id="editor-value"></textarea>
1775
+ </label>
1776
+ <div class="dialog-actions">
1777
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1778
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1779
+ <button class="btn-primary" type="submit" value="save">Save</button>
1780
+ </div>
1781
+ </form>
1782
+ </dialog>
1783
+ <script>
1784
+ (() => {
1785
+ const STANDARD = new Set(${standard})
1786
+ const state = {
1787
+ namespace: "default",
1788
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1789
+ view: "overview",
1790
+ collection: "",
1791
+ shape: null,
1792
+ route: null,
1793
+ editing: null
1794
+ }
1795
+ const $ = (id) => document.getElementById(id)
1796
+ const banner = $("banner")
1797
+ const keyInput = $("admin-key")
1798
+ keyInput.value = state.key
1799
+ const params = new URLSearchParams(location.search)
1800
+ if (params.get("key")) {
1801
+ state.key = params.get("key")
1802
+ keyInput.value = state.key
1803
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1804
+ params.delete("key")
1805
+ const next = params.toString()
1806
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1807
+ }
1808
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1809
+
1810
+ const showError = (error) => {
1811
+ banner.textContent = error instanceof Error ? error.message : String(error)
1812
+ banner.classList.add("show")
1813
+ }
1814
+ const clearError = () => banner.classList.remove("show")
1815
+
1816
+ async function originGet(path) {
1817
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1818
+ if (!response.ok) throw new Error(response.status + " " + path)
1819
+ return response.json()
1820
+ }
1821
+ async function api(method, path, body) {
1822
+ const headers = { accept: "application/json" }
1823
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1824
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1825
+ if (body !== undefined) headers["content-type"] = "application/json"
1826
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1827
+ method,
1828
+ headers,
1829
+ body: body === undefined ? undefined : JSON.stringify(body)
1830
+ })
1831
+ const text = await response.text()
1832
+ let data = null
1833
+ if (text) {
1834
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1835
+ }
1836
+ if (response.status === 401) {
1837
+ keyInput.focus()
1838
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1839
+ }
1840
+ if (!response.ok) {
1841
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1842
+ }
1843
+ return data
1844
+ }
1845
+ const panelApi = {
1846
+ get: (path) => api("GET", path),
1847
+ send: (method, path, body) => api(method, path, body),
1848
+ namespace: () => state.namespace
1849
+ }
1850
+
1851
+ function setTheme(theme) {
1852
+ if (theme) document.documentElement.dataset.theme = theme
1853
+ else delete document.documentElement.dataset.theme
1854
+ }
1855
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1856
+ if (storedTheme) setTheme(storedTheme)
1857
+ $("theme").addEventListener("click", () => {
1858
+ const current = document.documentElement.dataset.theme
1859
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1860
+ const next = dark ? "light" : "dark"
1861
+ localStorage.setItem("mockingbird-admin-theme", next)
1862
+ setTheme(next)
1863
+ })
1864
+
1865
+ function show(view) {
1866
+ state.view = view
1867
+ for (const button of document.querySelectorAll("#nav button")) {
1868
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1869
+ }
1870
+ for (const section of document.querySelectorAll("main .view")) {
1871
+ section.hidden = section.id !== "view-" + view
1872
+ }
1873
+ }
1874
+ document.getElementById("nav").addEventListener("click", (event) => {
1875
+ const button = event.target.closest("button[data-view]")
1876
+ if (!button) return
1877
+ show(button.dataset.view)
1878
+ refresh().catch(showError)
1879
+ })
1880
+
1881
+ function cards(items) {
1882
+ return '<div class="grid">' + items.map((item) =>
1883
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1884
+ ).join("") + "</div>"
1885
+ }
1886
+ function table(columns, rows) {
1887
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1888
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1889
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1890
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1891
+ ).join("") + "</tr>").join("")
1892
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1893
+ }
1894
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1895
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1896
+ }[char]))
1897
+ const preview = (value) => {
1898
+ const text = JSON.stringify(value)
1899
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1900
+ }
1901
+ const when = (epoch) => {
1902
+ const date = new Date(epoch)
1903
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1904
+ }
1905
+ const clockCard = (epoch) => {
1906
+ const date = new Date(epoch)
1907
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1908
+ const iso = date.toISOString()
1909
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1910
+ }
1911
+
1912
+ async function loadNamespaces() {
1913
+ const data = await api("GET", "/namespaces")
1914
+ const select = $("namespace")
1915
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1916
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1917
+ select.innerHTML = names.map((name) =>
1918
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1919
+ ).join("")
1920
+ select.value = state.namespace
1921
+ }
1922
+
1923
+ async function renderOverview() {
1924
+ const [health, shape, clock, journal] = await Promise.all([
1925
+ originGet("/health"),
1926
+ api("GET", "/state"),
1927
+ api("GET", "/clock"),
1928
+ api("GET", "/requests?limit=8")
1929
+ ])
1930
+ state.shape = shape
1931
+ $("overview-cards").innerHTML = cards([
1932
+ { k: "Service", v: esc(health.service || "${name}") },
1933
+ { k: "Status", v: esc(health.status || "ok") },
1934
+ { k: "Namespace", v: esc(state.namespace) },
1935
+ { k: "Collections", v: String(shape.collections.length) },
1936
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1937
+ { k: "Clock", v: clockCard(clock.now) }
1938
+ ])
1939
+ const requests = (journal && journal.requests) || []
1940
+ $("overview-requests").innerHTML = table(
1941
+ [
1942
+ { label: "Method", cell: (row) => esc(row.method) },
1943
+ { label: "Path", cell: (row) => esc(row.path) },
1944
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1945
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1946
+ ],
1947
+ requests
1948
+ )
1949
+ }
1950
+
1951
+ function schemaChips(collection) {
1952
+ if (!collection || collection.fields.length === 0) {
1953
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
1954
+ }
1955
+ return '<div class="chips">' + collection.fields.map((field) =>
1956
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
1957
+ ).join("") + "</div>"
1958
+ }
1959
+
1960
+ async function renderState() {
1961
+ const shape = await api("GET", "/state")
1962
+ state.shape = shape
1963
+ const host = $("collections")
1964
+ if (shape.collections.length === 0) {
1965
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
1966
+ $("schema").innerHTML = ""
1967
+ $("records").innerHTML = ""
1968
+ return
1969
+ }
1970
+ if (!shape.collections.some((item) => item.name === state.collection)) {
1971
+ state.collection = shape.collections[0].name
1972
+ }
1973
+ host.innerHTML = shape.collections.map((item) =>
1974
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
1975
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
1976
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
1977
+ ).join("")
1978
+ const selected = shape.collections.find((item) => item.name === state.collection)
1979
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
1980
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
1981
+ schemaChips(selected)
1982
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
1983
+ const rows = page.records.map((record) => ({
1984
+ ...record,
1985
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
1986
+ }))
1987
+ $("records").innerHTML = table(
1988
+ [
1989
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
1990
+ { label: "Seq", cell: (row) => esc(row.seq) },
1991
+ { label: "Value", cell: (row) => preview(row.value) }
1992
+ ],
1993
+ rows
1994
+ )
1995
+ }
1996
+
1997
+ async function renderClock() {
1998
+ const clock = await api("GET", "/clock")
1999
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
2000
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
2001
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
2002
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
2003
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
2004
+ }
2005
+
2006
+ async function renderFaults() {
2007
+ const [faults, presets] = await Promise.all([
2008
+ api("GET", "/faults"),
2009
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
2010
+ ])
2011
+ const select = $("fault-preset")
2012
+ const current = select.value
2013
+ const list = presets.presets || []
2014
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
2015
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
2016
+ ).join("")
2017
+ select.value = current
2018
+ const rules = faults.faults || []
2019
+ $("fault-list").innerHTML = table(
2020
+ [
2021
+ { label: "Id", cell: (row) => esc(row.id) },
2022
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
2023
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
2024
+ ],
2025
+ rules
2026
+ )
2027
+ }
2028
+
2029
+ async function renderJournal() {
2030
+ const journal = await api("GET", "/requests?limit=100")
2031
+ $("journal").innerHTML = table(
2032
+ [
2033
+ { label: "When", cell: (row) => esc(row.at || "") },
2034
+ { label: "Method", cell: (row) => esc(row.method) },
2035
+ { label: "Path", cell: (row) => esc(row.path) },
2036
+ { label: "Status", cell: (row) => esc(row.status) },
2037
+ { label: "ms", cell: (row) => esc(row.durationMs) }
2038
+ ],
2039
+ journal.requests || []
2040
+ )
2041
+ }
2042
+
2043
+ async function renderRoutes() {
2044
+ const data = await api("GET", "/")
2045
+ const routes = data.routes || []
2046
+ $("route-list").innerHTML = routes.map((route) => {
2047
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
2048
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
2049
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
2050
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
2051
+ }).join("")
2052
+ }
2053
+
2054
+ const renderers = {
2055
+ overview: renderOverview,
2056
+ state: renderState,
2057
+ clock: renderClock,
2058
+ faults: renderFaults,
2059
+ journal: renderJournal,
2060
+ routes: renderRoutes
2061
+ }
2062
+
2063
+ async function refresh() {
2064
+ clearError()
2065
+ if (state.view in renderers) await renderers[state.view]()
2066
+ }
2067
+
2068
+ $("namespace").addEventListener("change", () => {
2069
+ state.namespace = $("namespace").value
2070
+ refresh().catch(showError)
2071
+ })
2072
+ keyInput.addEventListener("change", () => {
2073
+ state.key = keyInput.value.trim()
2074
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
2075
+ refresh().catch(showError)
2076
+ })
2077
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
2078
+
2079
+ $("collections").addEventListener("click", (event) => {
2080
+ const button = event.target.closest("[data-collection]")
2081
+ if (!button) return
2082
+ state.collection = button.dataset.collection
2083
+ renderState().catch(showError)
2084
+ })
2085
+ $("records").addEventListener("click", (event) => {
2086
+ const row = event.target.closest("[data-id]")
2087
+ if (!row) return
2088
+ openEditor(row.dataset.id).catch(showError)
2089
+ })
2090
+
2091
+ const editor = $("editor")
2092
+ async function openEditor(id) {
2093
+ state.editing = id || null
2094
+ $("editor-title").textContent = id ? "Edit record" : "New record"
2095
+ $("editor-id").value = id || ""
2096
+ $("editor-id").readOnly = Boolean(id)
2097
+ $("editor-delete").hidden = !id
2098
+ if (id) {
2099
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2100
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
2101
+ } else {
2102
+ $("editor-value").value = "{\\n \\n}"
2103
+ }
2104
+ editor.showModal()
2105
+ }
2106
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
2107
+ $("editor-form").addEventListener("submit", (event) => {
2108
+ const submitter = event.submitter
2109
+ if (!submitter || submitter.value !== "save") return
2110
+ event.preventDefault()
2111
+ let value
2112
+ try { value = JSON.parse($("editor-value").value) }
2113
+ catch { showError(new Error("Value is not JSON")); return }
2114
+ const id = $("editor-id").value.trim()
2115
+ const path = "/state/" + encodeURIComponent(state.collection)
2116
+ const request = state.editing
2117
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
2118
+ : api("POST", path, { id: id || undefined, value })
2119
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
2120
+ })
2121
+ $("editor-delete").addEventListener("click", () => {
2122
+ const id = state.editing
2123
+ if (!id) return
2124
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
2125
+ .then(() => { editor.close(); return renderState() })
2126
+ .catch(showError)
2127
+ })
2128
+
2129
+ document.querySelectorAll("[data-advance]").forEach((button) => {
2130
+ button.addEventListener("click", () => {
2131
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
2132
+ })
2133
+ })
2134
+ $("freeze").addEventListener("click", () => {
2135
+ const frozen = $("freeze").dataset.frozen === "1"
2136
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
2137
+ })
2138
+ $("clock-reset").addEventListener("click", () => {
2139
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
2140
+ })
2141
+ $("clock-set").addEventListener("submit", (event) => {
2142
+ event.preventDefault()
2143
+ const raw = $("clock-instant").value.trim()
2144
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
2145
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
2146
+ })
2147
+
2148
+ $("fault-form").addEventListener("submit", (event) => {
2149
+ event.preventDefault()
2150
+ const preset = $("fault-preset").value
2151
+ const body = preset
2152
+ ? { preset }
2153
+ : {
2154
+ status: Number($("fault-status").value),
2155
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
2156
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
2157
+ }
2158
+ if (!preset && !Number.isFinite(body.status)) {
2159
+ showError(new Error("Status must be a number, or choose a preset"))
2160
+ return
2161
+ }
2162
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
2163
+ })
2164
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
2165
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
2166
+
2167
+ $("route-list").addEventListener("click", (event) => {
2168
+ const button = event.target.closest("[data-route]")
2169
+ if (!button) return
2170
+ state.route = button.dataset.route
2171
+ $("route-title").textContent = state.route
2172
+ const method = state.route.split(" ")[0]
2173
+ $("route-body").disabled = method === "GET" || method === "DELETE"
2174
+ })
2175
+ $("route-form").addEventListener("submit", async (event) => {
2176
+ event.preventDefault()
2177
+ if (!state.route) return showError(new Error("Choose a route first"))
2178
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
2179
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
2180
+ let body
2181
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
2182
+ try { body = JSON.parse($("route-body").value) }
2183
+ catch { return showError(new Error("Body is not JSON")) }
2184
+ }
2185
+ try {
2186
+ const data = await api(method, concrete, body)
2187
+ $("route-result").textContent = JSON.stringify(data, null, 2)
2188
+ } catch (error) {
2189
+ showError(error)
2190
+ }
2191
+ })
2192
+
2193
+ function mountPanels(panels) {
2194
+ const nav = $("nav")
2195
+ const views = $("views")
2196
+ for (const panel of panels) {
2197
+ const button = document.createElement("button")
2198
+ button.type = "button"
2199
+ button.dataset.view = panel.id
2200
+ button.textContent = panel.title
2201
+ nav.append(button)
2202
+ const section = document.createElement("section")
2203
+ section.className = "view"
2204
+ section.id = "view-" + panel.id
2205
+ section.hidden = true
2206
+ const title = document.createElement("h2")
2207
+ title.textContent = panel.title
2208
+ const lede = document.createElement("p")
2209
+ lede.className = "lede"
2210
+ lede.textContent = panel.description || ""
2211
+ const body = document.createElement("div")
2212
+ body.className = "panel-body"
2213
+ body.id = "panel-" + panel.id
2214
+ body.innerHTML = panel.html || ""
2215
+ section.append(title, lede, body)
2216
+ views.append(section)
2217
+ if (panel.script) {
2218
+ try {
2219
+ const run = new Function("root", "api", panel.script)
2220
+ run(body, panelApi)
2221
+ } catch (error) {
2222
+ const note = document.createElement("p")
2223
+ note.className = "banner show"
2224
+ note.textContent = error instanceof Error ? error.message : String(error)
2225
+ body.append(note)
2226
+ }
2227
+ }
2228
+ }
2229
+ }
2230
+
2231
+ loadNamespaces()
2232
+ .then(() => api("GET", "/ui/manifest"))
2233
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
2234
+ .catch(showError)
2235
+ })()
2236
+ </script>
2237
+ </body>
2238
+ </html>`;
2239
+ };
2240
+ var htmlResponse = (body) => new Response(body, {
2241
+ status: 200,
2242
+ headers: {
2243
+ "content-type": "text/html; charset=utf-8",
2244
+ "cache-control": "no-store"
2245
+ }
2246
+ });
2247
+ var json2 = (body) => new Response(JSON.stringify(body), {
2248
+ status: 200,
2249
+ headers: { "content-type": "application/json; charset=utf-8" }
2250
+ });
2251
+ var adminUiRoutes = (service, ui) => {
2252
+ const shell = () => renderAdminDocument(service);
2253
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
2254
+ return {
2255
+ "GET /ui": () => htmlResponse(document2()),
2256
+ "GET /ui/": () => htmlResponse(document2()),
2257
+ "GET /ui/manifest": () => json2({
2258
+ service,
2259
+ panels: (ui?.panels ?? []).map((panel) => ({
2260
+ id: panel.id,
2261
+ title: panel.title,
2262
+ ...panel.description !== void 0 ? { description: panel.description } : {},
2263
+ html: panel.html,
2264
+ ...panel.script !== void 0 ? { script: panel.script } : {}
2265
+ }))
2266
+ })
2267
+ };
2268
+ };
2269
+
1338
2270
  // ../../openapi/metadata/dist/types.js
1339
2271
  var EXTENSION_KEYS = {
1340
2272
  operation: "x-mockingbird",
@@ -1572,8 +2504,442 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1572
2504
  });
1573
2505
  };
1574
2506
 
2507
+ // ../core/dist/state-view.js
2508
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2509
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2510
+ var SAMPLE = 25;
2511
+ var WALK_LIMIT = 1e4;
2512
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2513
+ var fail = (status, message) => ({ ok: false, status, message });
2514
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2515
+ var kindOf = (value) => {
2516
+ if (value === null)
2517
+ return "null";
2518
+ if (Array.isArray(value))
2519
+ return "array";
2520
+ switch (typeof value) {
2521
+ case "string":
2522
+ return "string";
2523
+ case "number":
2524
+ return Number.isFinite(value) ? "number" : "unknown";
2525
+ case "boolean":
2526
+ return "boolean";
2527
+ case "object":
2528
+ return "object";
2529
+ default:
2530
+ return "unknown";
2531
+ }
2532
+ };
2533
+ var humanize = (name) => {
2534
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2535
+ if (words === "")
2536
+ return name;
2537
+ return words.charAt(0).toUpperCase() + words.slice(1);
2538
+ };
2539
+ var jsonValue = (value) => {
2540
+ if (value === void 0)
2541
+ return fail(400, "value is required");
2542
+ try {
2543
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2544
+ } catch {
2545
+ return fail(400, "value must be JSON");
2546
+ }
2547
+ };
2548
+ var ctorName = (value) => {
2549
+ const ctor = value.constructor;
2550
+ return typeof ctor?.name === "string" ? ctor.name : "";
2551
+ };
2552
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2553
+ var discoverCollections = (root) => {
2554
+ const found = [];
2555
+ const seen = /* @__PURE__ */ new Set();
2556
+ const visit = (value, depth) => {
2557
+ if (found.length + seen.size > WALK_LIMIT)
2558
+ return;
2559
+ if (value === null || typeof value !== "object")
2560
+ return;
2561
+ if (seen.has(value))
2562
+ return;
2563
+ seen.add(value);
2564
+ if (value instanceof Collection) {
2565
+ found.push(value);
2566
+ return;
2567
+ }
2568
+ if (value instanceof Map) {
2569
+ for (const child of value.values())
2570
+ visit(child, depth + 1);
2571
+ return;
2572
+ }
2573
+ if (value instanceof Set) {
2574
+ for (const child of value.values())
2575
+ visit(child, depth + 1);
2576
+ return;
2577
+ }
2578
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2579
+ return;
2580
+ if (Array.isArray(value)) {
2581
+ const cap = Math.min(value.length, 32);
2582
+ for (let i = 0; i < cap; i++)
2583
+ visit(value[i], depth + 1);
2584
+ return;
2585
+ }
2586
+ let children;
2587
+ try {
2588
+ children = Object.values(value);
2589
+ } catch {
2590
+ return;
2591
+ }
2592
+ for (const child of children)
2593
+ visit(child, depth + 1);
2594
+ };
2595
+ visit(root, 0);
2596
+ return found;
2597
+ };
2598
+ var storedNames = (sqlite, namespace) => {
2599
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2600
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2601
+ return [...records, ...sequences].map((row) => row.name);
2602
+ };
2603
+ var blankAccum = (name) => ({
2604
+ name,
2605
+ kinds: /* @__PURE__ */ new Set(),
2606
+ present: 0,
2607
+ nested: /* @__PURE__ */ new Map()
2608
+ });
2609
+ var absorb = (accum, value) => {
2610
+ const kind = kindOf(value);
2611
+ accum.kinds.add(kind);
2612
+ accum.present++;
2613
+ if (!isRecord3(value))
2614
+ return;
2615
+ for (const [key, child] of Object.entries(value)) {
2616
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2617
+ absorb(nested, child);
2618
+ accum.nested.set(key, nested);
2619
+ }
2620
+ };
2621
+ var finishField = (accum, samples) => {
2622
+ const kinds = [...accum.kinds];
2623
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2624
+ const field = {
2625
+ name: accum.name,
2626
+ kind,
2627
+ optional: accum.present < samples || kinds.includes("null")
2628
+ };
2629
+ if (accum.nested.size > 0) {
2630
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2631
+ }
2632
+ return field;
2633
+ };
2634
+ var inferFields = (records) => {
2635
+ if (records.length === 0)
2636
+ return [];
2637
+ const sample = records.slice(0, SAMPLE);
2638
+ const objects = sample.filter((record) => isRecord3(record.value));
2639
+ if (objects.length === 0) {
2640
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2641
+ const list = [...kinds];
2642
+ return [
2643
+ {
2644
+ name: "(value)",
2645
+ kind: list.length === 1 ? list[0] : "unknown",
2646
+ optional: false
2647
+ }
2648
+ ];
2649
+ }
2650
+ const root = /* @__PURE__ */ new Map();
2651
+ for (const record of objects) {
2652
+ for (const [key, value] of Object.entries(record.value)) {
2653
+ const accum = root.get(key) ?? blankAccum(key);
2654
+ absorb(accum, value);
2655
+ root.set(key, accum);
2656
+ }
2657
+ }
2658
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2659
+ };
2660
+ var mergeFields = (declared, inferred) => {
2661
+ const byName = /* @__PURE__ */ new Map();
2662
+ for (const field of inferred)
2663
+ byName.set(field.name, field);
2664
+ const ordered = [];
2665
+ const seen = /* @__PURE__ */ new Set();
2666
+ for (const field of declared ?? []) {
2667
+ const found = byName.get(field.name);
2668
+ seen.add(field.name);
2669
+ if (!found) {
2670
+ ordered.push({ ...field, optional: field.optional });
2671
+ continue;
2672
+ }
2673
+ ordered.push({
2674
+ ...found,
2675
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2676
+ optional: field.optional || found.optional,
2677
+ ...field.description !== void 0 ? { description: field.description } : {},
2678
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2679
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2680
+ });
2681
+ }
2682
+ for (const field of inferred) {
2683
+ if (!seen.has(field.name))
2684
+ ordered.push(field);
2685
+ }
2686
+ return ordered;
2687
+ };
2688
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2689
+ var readRecord = (collection, id) => {
2690
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2691
+ const row = rows.find((entry) => entry.id === id);
2692
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2693
+ };
2694
+ var inspectState = (scope) => {
2695
+ const declared = /* @__PURE__ */ new Map();
2696
+ for (const declaration of scope.declarations ?? []) {
2697
+ if (COLLECTION_NAME.test(declaration.name))
2698
+ declared.set(declaration.name, declaration);
2699
+ }
2700
+ const names = new Set(declared.keys());
2701
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2702
+ names.add(name);
2703
+ for (const collection of discoverCollections(scope.root)) {
2704
+ if (collection.namespace === scope.storageNamespace)
2705
+ names.add(collection.collectionName);
2706
+ }
2707
+ const collections = [];
2708
+ for (const name of names) {
2709
+ if (!COLLECTION_NAME.test(name))
2710
+ continue;
2711
+ const declaration = declared.get(name);
2712
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2713
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2714
+ const inferred = inferFields(records);
2715
+ const fields = mergeFields(declaration?.fields, inferred);
2716
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2717
+ collections.push({
2718
+ name,
2719
+ label: declaration?.label ?? humanize(name),
2720
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2721
+ count: collection.count(),
2722
+ source,
2723
+ fields,
2724
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2725
+ });
2726
+ }
2727
+ const order = /* @__PURE__ */ new Map();
2728
+ for (const [index, item] of (scope.declarations ?? []).entries())
2729
+ order.set(item.name, index);
2730
+ collections.sort((a, b) => {
2731
+ const left = order.get(a.name);
2732
+ const right = order.get(b.name);
2733
+ if (left !== void 0 && right !== void 0)
2734
+ return left - right;
2735
+ if (left !== void 0)
2736
+ return -1;
2737
+ if (right !== void 0)
2738
+ return 1;
2739
+ return a.name.localeCompare(b.name);
2740
+ });
2741
+ return {
2742
+ namespace: scope.namespace,
2743
+ storageNamespace: scope.storageNamespace,
2744
+ collections
2745
+ };
2746
+ };
2747
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2748
+ if (!COLLECTION_NAME.test(name))
2749
+ return fail(400, "collection name is not allowed");
2750
+ const limit = query.limit ?? 50;
2751
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2752
+ return fail(400, "limit must be an integer from 1 to 200");
2753
+ }
2754
+ const order = query.order ?? "newest";
2755
+ if (order !== "newest" && order !== "oldest")
2756
+ return fail(400, 'order must be "newest" or "oldest"');
2757
+ const collection = collectionOf(sqlite, storageNamespace, name);
2758
+ const rows = collection.list({ order }).filter((row) => {
2759
+ if (query.after === void 0)
2760
+ return true;
2761
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2762
+ });
2763
+ const slice = rows.slice(0, limit);
2764
+ const last = slice.at(-1);
2765
+ return {
2766
+ ok: true,
2767
+ value: {
2768
+ collection: name,
2769
+ count: collection.count(),
2770
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2771
+ next: rows.length > limit && last ? last.seq : null
2772
+ }
2773
+ };
2774
+ };
2775
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2776
+ var readStateRecord = (scope, name, id) => {
2777
+ if (!COLLECTION_NAME.test(name))
2778
+ return fail(400, "collection name is not allowed");
2779
+ if (!RECORD_ID.test(id))
2780
+ return fail(400, "record id is not allowed");
2781
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2782
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
2783
+ };
2784
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2785
+ var createStateRecord = (scope, name, input) => {
2786
+ if (!COLLECTION_NAME.test(name))
2787
+ return fail(400, "collection name is not allowed");
2788
+ const parsed = jsonValue(input.value);
2789
+ if (!parsed.ok)
2790
+ return parsed;
2791
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2792
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2793
+ const checked = requireId(id);
2794
+ if (!checked.ok)
2795
+ return checked;
2796
+ if (collection.has(checked.value))
2797
+ return fail(409, `record ${checked.value} already exists`);
2798
+ const stored = collection.insert(checked.value, parsed.value);
2799
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2800
+ };
2801
+ var replaceStateRecord = (scope, name, id, value) => {
2802
+ if (!COLLECTION_NAME.test(name))
2803
+ return fail(400, "collection name is not allowed");
2804
+ const checked = requireId(id);
2805
+ if (!checked.ok)
2806
+ return checked;
2807
+ const parsed = jsonValue(value);
2808
+ if (!parsed.ok)
2809
+ return parsed;
2810
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2811
+ if (!collection.has(checked.value))
2812
+ return fail(404, `no record ${checked.value} in ${name}`);
2813
+ const stored = collection.update(checked.value, parsed.value);
2814
+ if (!stored)
2815
+ return fail(404, `no record ${checked.value} in ${name}`);
2816
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2817
+ };
2818
+ var patchStateRecord = (scope, name, id, value) => {
2819
+ const current = readStateRecord(scope, name, id);
2820
+ if (!current.ok)
2821
+ return current;
2822
+ const parsed = jsonValue(value);
2823
+ if (!parsed.ok)
2824
+ return parsed;
2825
+ const next = isRecord3(current.value.value) && isRecord3(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2826
+ return replaceStateRecord(scope, name, id, next);
2827
+ };
2828
+ var deleteStateRecord = (scope, name, id) => {
2829
+ if (!COLLECTION_NAME.test(name))
2830
+ return fail(400, "collection name is not allowed");
2831
+ const checked = requireId(id);
2832
+ if (!checked.ok)
2833
+ return checked;
2834
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2835
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2836
+ };
2837
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2838
+ status,
2839
+ headers: { "content-type": "application/json; charset=utf-8" }
2840
+ });
2841
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2842
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2843
+ var integerParam = (value) => {
2844
+ if (value === null)
2845
+ return void 0;
2846
+ if (!/^-?\d+$/.test(value))
2847
+ return "bad";
2848
+ return Number(value);
2849
+ };
2850
+ var stateAdminRoutes = (routes) => {
2851
+ const open = (namespace) => {
2852
+ try {
2853
+ return { ok: true, value: routes.open(namespace) };
2854
+ } catch (error) {
2855
+ return fail(400, error instanceof Error ? error.message : String(error));
2856
+ }
2857
+ };
2858
+ const wrote = (namespace) => {
2859
+ routes.afterWrite?.(namespace);
2860
+ };
2861
+ return {
2862
+ "GET /state": ({ namespace }) => {
2863
+ const scope = open(namespace);
2864
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2865
+ },
2866
+ "GET /state/:collection": ({ namespace, params, url }) => {
2867
+ const scope = open(namespace);
2868
+ if (!scope.ok)
2869
+ return fromResult(scope, 200);
2870
+ const limit = integerParam(url.searchParams.get("limit"));
2871
+ const after = integerParam(url.searchParams.get("after"));
2872
+ if (limit === "bad")
2873
+ return adminError2(400, "limit: expected an integer");
2874
+ if (after === "bad")
2875
+ return adminError2(400, "after: expected a sequence number");
2876
+ const order = url.searchParams.get("order");
2877
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2878
+ ...limit !== void 0 ? { limit } : {},
2879
+ ...after !== void 0 ? { after } : {},
2880
+ ...order === "newest" || order === "oldest" ? { order } : {}
2881
+ }), 200);
2882
+ },
2883
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2884
+ const scope = open(namespace);
2885
+ if (!scope.ok)
2886
+ return fromResult(scope, 200);
2887
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2888
+ },
2889
+ "POST /state/:collection": ({ namespace, params, body }) => {
2890
+ const scope = open(namespace);
2891
+ if (!scope.ok)
2892
+ return fromResult(scope, 201);
2893
+ if (!isRecord3(body) || !("value" in body)) {
2894
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2895
+ }
2896
+ const id = body.id;
2897
+ if (id !== void 0 && typeof id !== "string")
2898
+ return adminError2(400, "id must be a string");
2899
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2900
+ ...typeof id === "string" ? { id } : {},
2901
+ value: body.value
2902
+ });
2903
+ if (created.ok)
2904
+ wrote(namespace);
2905
+ return fromResult(created, 201);
2906
+ },
2907
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2908
+ const scope = open(namespace);
2909
+ if (!scope.ok)
2910
+ return fromResult(scope, 200);
2911
+ if (!isRecord3(body) || !("value" in body))
2912
+ return adminError2(400, 'expected {"value": <json>}');
2913
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2914
+ if (replaced.ok)
2915
+ wrote(namespace);
2916
+ return fromResult(replaced, 200);
2917
+ },
2918
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2919
+ const scope = open(namespace);
2920
+ if (!scope.ok)
2921
+ return fromResult(scope, 200);
2922
+ if (!isRecord3(body) || !("value" in body))
2923
+ return adminError2(400, 'expected {"value": <json>}');
2924
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2925
+ if (patched.ok)
2926
+ wrote(namespace);
2927
+ return fromResult(patched, 200);
2928
+ },
2929
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2930
+ const scope = open(namespace);
2931
+ if (!scope.ok)
2932
+ return fromResult(scope, 200);
2933
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2934
+ if (removed.ok)
2935
+ wrote(namespace);
2936
+ return fromResult(removed, 200);
2937
+ }
2938
+ };
2939
+ };
2940
+
1575
2941
  // ../core/dist/version.js
1576
- var PACKAGE_VERSION = true ? "1.2.0" : UNRELEASED_VERSION;
2942
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1577
2943
 
1578
2944
  // ../core/dist/signing.js
1579
2945
  var encoder = new TextEncoder();
@@ -1581,11 +2947,11 @@ var toHex = (bytes) => [...bytes instanceof Uint8Array ? bytes : new Uint8Array(
1581
2947
  var sha = async (algorithm, input) => toHex(await crypto.subtle.digest(algorithm, typeof input === "string" ? encoder.encode(input) : input));
1582
2948
 
1583
2949
  // ../core/dist/webhooks.js
1584
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1585
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1586
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2950
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2951
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2952
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1587
2953
  var parseEndpoint = (value) => {
1588
- if (!isRecord3(value) || typeof value.url !== "string")
2954
+ if (!isRecord4(value) || typeof value.url !== "string")
1589
2955
  return "each endpoint needs a url";
1590
2956
  try {
1591
2957
  new URL(value.url);
@@ -1602,18 +2968,18 @@ var parseEndpoint = (value) => {
1602
2968
  const events = value.events ?? value.enabledEvents;
1603
2969
  if (Array.isArray(events))
1604
2970
  endpoint.events = events.map(String);
1605
- if (isRecord3(value.tags)) {
2971
+ if (isRecord4(value.tags)) {
1606
2972
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1607
2973
  }
1608
2974
  if (typeof value.account === "string")
1609
2975
  endpoint.tags = { ...endpoint.tags, account: value.account };
1610
- if (isRecord3(value.headers)) {
2976
+ if (isRecord4(value.headers)) {
1611
2977
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1612
2978
  }
1613
2979
  return endpoint;
1614
2980
  };
1615
2981
  var webhookAdminRoutes = (hub) => ({
1616
- "GET /webhooks": ({ url, namespace }) => json2(200, {
2982
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
1617
2983
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1618
2984
  const type = url.searchParams.get("type");
1619
2985
  return type === null || d.type === type;
@@ -1621,51 +2987,51 @@ var webhookAdminRoutes = (hub) => ({
1621
2987
  }),
1622
2988
  "GET /webhooks/events": ({ url, namespace }) => {
1623
2989
  const type = url.searchParams.get("type");
1624
- return json2(200, {
2990
+ return json4(200, {
1625
2991
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1626
2992
  });
1627
2993
  },
1628
2994
  "POST /webhooks/:id/replay": async ({ params }) => {
1629
2995
  const replayed = await hub.replay(params.id);
1630
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
2996
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1631
2997
  },
1632
2998
  "POST /webhooks/flush": async () => {
1633
2999
  await hub.flush();
1634
- return json2(200, { status: "ok" });
3000
+ return json4(200, { status: "ok" });
1635
3001
  },
1636
3002
  "POST /webhooks/faults": ({ body, namespace }) => {
1637
- if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1638
- return adminError2(400, "mode must be duplicate, reorder or drop");
3003
+ if (!isRecord4(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
3004
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1639
3005
  }
1640
3006
  const fault = { mode: body.mode };
1641
3007
  if (typeof body.count === "number")
1642
3008
  fault.count = body.count;
1643
3009
  hub.fault(namespace, fault);
1644
- return json2(201, { namespace, ...fault });
3010
+ return json4(201, { namespace, ...fault });
1645
3011
  },
1646
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
3012
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
1647
3013
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1648
3014
  ...rest,
1649
3015
  secret: secret ? "(set)" : null
1650
3016
  }))
1651
3017
  }),
1652
3018
  "PUT /webhook-endpoints": ({ body, namespace }) => {
1653
- const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
3019
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
1654
3020
  if (!Array.isArray(list))
1655
- return adminError2(400, "expected [{url, secret?, events?}]");
3021
+ return adminError3(400, "expected [{url, secret?, events?}]");
1656
3022
  const parsed = [];
1657
3023
  for (const each of list) {
1658
3024
  const endpoint = parseEndpoint(each);
1659
3025
  if (typeof endpoint === "string")
1660
- return adminError2(400, endpoint);
3026
+ return adminError3(400, endpoint);
1661
3027
  parsed.push(endpoint);
1662
3028
  }
1663
3029
  const set = hub.setEndpoints(namespace, parsed);
1664
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
3030
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1665
3031
  },
1666
3032
  "DELETE /webhook-endpoints": ({ namespace }) => {
1667
3033
  hub.setEndpoints(namespace, []);
1668
- return json2(200, { status: "ok" });
3034
+ return json4(200, { status: "ok" });
1669
3035
  }
1670
3036
  });
1671
3037
  var parsePayload = (message) => {
@@ -1730,6 +3096,7 @@ var operationMatcher = (document2) => {
1730
3096
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1731
3097
  };
1732
3098
  var createRuntime = (options) => {
3099
+ assertAdminUi(options.adminUi);
1733
3100
  const sqlite = bootSqlite(options.sqlite);
1734
3101
  const clock = options.clock ?? createClock();
1735
3102
  const rng = createRng(options.seed ?? 0);
@@ -1936,6 +3303,19 @@ var createRuntime = (options) => {
1936
3303
  else
1937
3304
  timeline(name);
1938
3305
  };
3306
+ const declarationsFor = (namespace) => {
3307
+ const declared = options.state;
3308
+ if (!declared)
3309
+ return [];
3310
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3311
+ };
3312
+ const stateScope = (namespace) => ({
3313
+ sqlite,
3314
+ namespace,
3315
+ storageNamespace: storageNamespace(namespace),
3316
+ root: instance(namespace),
3317
+ declarations: declarationsFor(namespace)
3318
+ });
1939
3319
  const runtime = {
1940
3320
  name: options.name,
1941
3321
  sqlite,
@@ -1974,6 +3354,7 @@ var createRuntime = (options) => {
1974
3354
  branch,
1975
3355
  checkout,
1976
3356
  timeline,
3357
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
1977
3358
  fetch: async (incoming) => {
1978
3359
  let request = incoming;
1979
3360
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2167,11 +3548,20 @@ var createRuntime = (options) => {
2167
3548
  ...credentialRoutes(credentials),
2168
3549
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2169
3550
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2170
- ...options.admin?.(runtime) ?? {}
3551
+ ...options.admin?.(runtime) ?? {},
3552
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3553
+ // beside these; it does not replace `/state` or `/ui`.
3554
+ ...stateAdminRoutes({
3555
+ open: stateScope,
3556
+ afterWrite: (namespace) => {
3557
+ checkpoint(namespace, "main");
3558
+ }
3559
+ }),
3560
+ ...adminUiRoutes(options.name, options.adminUi)
2171
3561
  },
2172
3562
  adminKey: options.adminKey
2173
3563
  });
2174
- return runtime;
3564
+ return defineMock(runtime);
2175
3565
  };
2176
3566
  var mutableResponse = (response) => {
2177
3567
  try {
@@ -2248,7 +3638,7 @@ var presetRoutes = (presets, runtime) => ({
2248
3638
  });
2249
3639
 
2250
3640
  // src/analyze.ts
2251
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3641
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2252
3642
  var array = (value) => Array.isArray(value) ? value : [];
2253
3643
  var ValidationProblem = class extends Error {
2254
3644
  constructor(message) {
@@ -2266,7 +3656,7 @@ var parseSchema = (value) => {
2266
3656
  return {};
2267
3657
  }
2268
3658
  };
2269
- var textOf = (blocks) => blocks.map((block) => isRecord4(block) && typeof block.text === "string" ? block.text : "").filter((text2) => text2.length > 0).join("\n");
3659
+ var textOf = (blocks) => blocks.map((block) => isRecord5(block) && typeof block.text === "string" ? block.text : "").filter((text2) => text2.length > 0).join("\n");
2270
3660
  var conversationFacts = (messages) => {
2271
3661
  let lastSaid = -1;
2272
3662
  for (let i = messages.length - 1; i >= 0; i--) {
@@ -2343,7 +3733,7 @@ var checkConversation = (messages, modelId, hasToolConfig) => {
2343
3733
  }
2344
3734
  };
2345
3735
  var converseMessage = (value, index) => {
2346
- if (!isRecord4(value) || value.role !== "user" && value.role !== "assistant") {
3736
+ if (!isRecord5(value) || value.role !== "user" && value.role !== "assistant") {
2347
3737
  throw new ValidationProblem(`messages.${index}.role: must be one of [user, assistant]`);
2348
3738
  }
2349
3739
  const content = array(value.content);
@@ -2364,49 +3754,49 @@ var converseMessage = (value, index) => {
2364
3754
  chars: 0
2365
3755
  };
2366
3756
  for (const block of content) {
2367
- if (!isRecord4(block)) continue;
3757
+ if (!isRecord5(block)) continue;
2368
3758
  out.chars += JSON.stringify(block).length;
2369
3759
  if (typeof block.text === "string") out.hasContent = true;
2370
- if (isRecord4(block.document)) {
3760
+ if (isRecord5(block.document)) {
2371
3761
  out.hasDocument = true;
2372
3762
  out.hasContent = true;
2373
3763
  }
2374
- if (isRecord4(block.image)) {
3764
+ if (isRecord5(block.image)) {
2375
3765
  out.hasImage = true;
2376
3766
  out.hasContent = true;
2377
3767
  }
2378
- if (isRecord4(block.video)) out.hasContent = true;
2379
- if (isRecord4(block.cachePoint)) out.hasCachePoint = true;
2380
- if (isRecord4(block.toolUse)) {
3768
+ if (isRecord5(block.video)) out.hasContent = true;
3769
+ if (isRecord5(block.cachePoint)) out.hasCachePoint = true;
3770
+ if (isRecord5(block.toolUse)) {
2381
3771
  out.toolUses.push({
2382
3772
  id: String(block.toolUse.toolUseId ?? ""),
2383
3773
  name: String(block.toolUse.name ?? "")
2384
3774
  });
2385
3775
  }
2386
- if (isRecord4(block.toolResult)) out.toolResultIds.push(String(block.toolResult.toolUseId ?? ""));
3776
+ if (isRecord5(block.toolResult)) out.toolResultIds.push(String(block.toolResult.toolUseId ?? ""));
2387
3777
  }
2388
3778
  return out;
2389
3779
  };
2390
3780
  var analyzeConverse = (operation, modelId, body) => {
2391
- if (!isRecord4(body))
3781
+ if (!isRecord5(body))
2392
3782
  throw new ValidationProblem(
2393
3783
  "Malformed input request, please reformat your input and try again."
2394
3784
  );
2395
3785
  const messages = array(body.messages).map(converseMessage);
2396
3786
  const system = array(body.system);
2397
- const toolConfig = isRecord4(body.toolConfig) ? body.toolConfig : void 0;
3787
+ const toolConfig = isRecord5(body.toolConfig) ? body.toolConfig : void 0;
2398
3788
  const toolSchemas = {};
2399
3789
  for (const tool of array(toolConfig?.tools)) {
2400
- if (!isRecord4(tool) || !isRecord4(tool.toolSpec)) continue;
3790
+ if (!isRecord5(tool) || !isRecord5(tool.toolSpec)) continue;
2401
3791
  const spec = tool.toolSpec;
2402
- const schema = isRecord4(spec.inputSchema) ? spec.inputSchema.json : void 0;
3792
+ const schema = isRecord5(spec.inputSchema) ? spec.inputSchema.json : void 0;
2403
3793
  toolSchemas[String(spec.name)] = parseSchema(schema) ?? {};
2404
3794
  }
2405
3795
  const tools = Object.keys(toolSchemas);
2406
- const choice = isRecord4(toolConfig?.toolChoice) ? toolConfig.toolChoice : void 0;
3796
+ const choice = isRecord5(toolConfig?.toolChoice) ? toolConfig.toolChoice : void 0;
2407
3797
  let toolChoice;
2408
3798
  if (choice) {
2409
- if (isRecord4(choice.tool)) toolChoice = `tool:${String(choice.tool.name)}`;
3799
+ if (isRecord5(choice.tool)) toolChoice = `tool:${String(choice.tool.name)}`;
2410
3800
  else if (choice.any !== void 0) toolChoice = "any";
2411
3801
  else if (choice.auto !== void 0) toolChoice = "auto";
2412
3802
  }
@@ -2420,8 +3810,8 @@ var analyzeConverse = (operation, modelId, body) => {
2420
3810
  `The provided toolChoice ${toolChoice.slice(5)} is not a tool in toolConfig.tools.`
2421
3811
  );
2422
3812
  }
2423
- const inference = isRecord4(body.inferenceConfig) ? body.inferenceConfig : {};
2424
- const additional = isRecord4(body.additionalModelRequestFields) ? body.additionalModelRequestFields : {};
3813
+ const inference = isRecord5(body.inferenceConfig) ? body.inferenceConfig : {};
3814
+ const additional = isRecord5(body.additionalModelRequestFields) ? body.additionalModelRequestFields : {};
2425
3815
  const hasTemperature = inference.temperature !== void 0 || additional.temperature !== void 0;
2426
3816
  const hasTopP = inference.topP !== void 0 || additional.top_p !== void 0;
2427
3817
  if (hasTemperature && hasTopP && ONE_SAMPLING_PARAM.test(modelId)) {
@@ -2431,10 +3821,10 @@ var analyzeConverse = (operation, modelId, body) => {
2431
3821
  }
2432
3822
  checkConversation(messages, modelId, toolConfig !== void 0);
2433
3823
  let structured;
2434
- const outputConfig = isRecord4(body.outputConfig) ? body.outputConfig : void 0;
2435
- const textFormat = isRecord4(outputConfig?.textFormat) ? outputConfig.textFormat : void 0;
2436
- const jsonSchema = textFormat && isRecord4(textFormat.structure) && isRecord4(textFormat.structure.jsonSchema) ? textFormat.structure.jsonSchema : void 0;
2437
- const nativeFormat = isRecord4(additional.output_config) && isRecord4(additional.output_config.format) ? additional.output_config.format : void 0;
3824
+ const outputConfig = isRecord5(body.outputConfig) ? body.outputConfig : void 0;
3825
+ const textFormat = isRecord5(outputConfig?.textFormat) ? outputConfig.textFormat : void 0;
3826
+ const jsonSchema = textFormat && isRecord5(textFormat.structure) && isRecord5(textFormat.structure.jsonSchema) ? textFormat.structure.jsonSchema : void 0;
3827
+ const nativeFormat = isRecord5(additional.output_config) && isRecord5(additional.output_config.format) ? additional.output_config.format : void 0;
2438
3828
  if (jsonSchema) {
2439
3829
  structured = {
2440
3830
  form: "outputConfig",
@@ -2462,8 +3852,8 @@ var analyzeConverse = (operation, modelId, body) => {
2462
3852
  toolChoice,
2463
3853
  hasDocument: messages.some((m) => m.hasDocument),
2464
3854
  hasImage: messages.some((m) => m.hasImage),
2465
- hasCachePoint: messages.some((m) => m.hasCachePoint) || system.some((b) => isRecord4(b) && isRecord4(b.cachePoint)) || array(toolConfig?.tools).some((t) => isRecord4(t) && isRecord4(t.cachePoint)),
2466
- hasGuardrail: isRecord4(body.guardrailConfig),
3855
+ hasCachePoint: messages.some((m) => m.hasCachePoint) || system.some((b) => isRecord5(b) && isRecord5(b.cachePoint)) || array(toolConfig?.tools).some((t) => isRecord5(t) && isRecord5(t.cachePoint)),
3856
+ hasGuardrail: isRecord5(body.guardrailConfig),
2467
3857
  toolResults: facts.toolResults,
2468
3858
  turnIndex: facts.turnIndex,
2469
3859
  structured,
@@ -2471,7 +3861,7 @@ var analyzeConverse = (operation, modelId, body) => {
2471
3861
  };
2472
3862
  };
2473
3863
  var anthropicMessage = (value, index) => {
2474
- if (!isRecord4(value) || value.role !== "user" && value.role !== "assistant") {
3864
+ if (!isRecord5(value) || value.role !== "user" && value.role !== "assistant") {
2475
3865
  throw new ValidationProblem(`messages.${index}.role: Input should be 'user' or 'assistant'`);
2476
3866
  }
2477
3867
  const blocks = typeof value.content === "string" ? [{ type: "text", text: value.content }] : array(value.content);
@@ -2479,7 +3869,7 @@ var anthropicMessage = (value, index) => {
2479
3869
  throw new ValidationProblem(`messages.${index}: all messages must have non-empty content`);
2480
3870
  const out = {
2481
3871
  role: value.role,
2482
- text: textOf(blocks.filter((b) => isRecord4(b) && b.type === "text")),
3872
+ text: textOf(blocks.filter((b) => isRecord5(b) && b.type === "text")),
2483
3873
  toolUses: [],
2484
3874
  toolResultIds: [],
2485
3875
  hasContent: false,
@@ -2489,9 +3879,9 @@ var anthropicMessage = (value, index) => {
2489
3879
  chars: 0
2490
3880
  };
2491
3881
  for (const block of blocks) {
2492
- if (!isRecord4(block)) continue;
3882
+ if (!isRecord5(block)) continue;
2493
3883
  out.chars += JSON.stringify(block).length;
2494
- if (isRecord4(block.cache_control)) out.hasCachePoint = true;
3884
+ if (isRecord5(block.cache_control)) out.hasCachePoint = true;
2495
3885
  switch (block.type) {
2496
3886
  case "text":
2497
3887
  out.hasContent = true;
@@ -2515,7 +3905,7 @@ var anthropicMessage = (value, index) => {
2515
3905
  return out;
2516
3906
  };
2517
3907
  var analyzeAnthropic = (modelId, body) => {
2518
- if (!isRecord4(body))
3908
+ if (!isRecord5(body))
2519
3909
  throw new ValidationProblem(
2520
3910
  "Malformed input request, please reformat your input and try again."
2521
3911
  );
@@ -2537,16 +3927,16 @@ var analyzeAnthropic = (modelId, body) => {
2537
3927
  const messages = array(body.messages).map(anthropicMessage);
2538
3928
  const toolSchemas = {};
2539
3929
  for (const tool of array(body.tools)) {
2540
- if (isRecord4(tool) && typeof tool.name === "string")
3930
+ if (isRecord5(tool) && typeof tool.name === "string")
2541
3931
  toolSchemas[tool.name] = tool.input_schema ?? {};
2542
3932
  }
2543
3933
  checkConversation(messages, modelId, true);
2544
3934
  const system = typeof body.system === "string" ? body.system : textOf(array(body.system));
2545
- const choice = isRecord4(body.tool_choice) ? body.tool_choice : void 0;
3935
+ const choice = isRecord5(body.tool_choice) ? body.tool_choice : void 0;
2546
3936
  const toolChoice = choice?.type === "tool" ? `tool:${String(choice.name)}` : typeof choice?.type === "string" ? choice.type : void 0;
2547
3937
  const tools = Object.keys(toolSchemas);
2548
3938
  let structured;
2549
- const format = isRecord4(body.output_config) && isRecord4(body.output_config.format) ? body.output_config.format : void 0;
3939
+ const format = isRecord5(body.output_config) && isRecord5(body.output_config.format) ? body.output_config.format : void 0;
2550
3940
  if (format?.type === "json_schema") structured = { form: "outputFormat", schema: format.schema };
2551
3941
  else if (toolChoice?.startsWith("tool:")) {
2552
3942
  const tool = toolChoice.slice(5);
@@ -2572,7 +3962,7 @@ var analyzeAnthropic = (modelId, body) => {
2572
3962
  };
2573
3963
  };
2574
3964
  var analyzeHarness = (harnessArn, body) => {
2575
- if (!isRecord4(body) || !Array.isArray(body.messages) || body.messages.length === 0) {
3965
+ if (!isRecord5(body) || !Array.isArray(body.messages) || body.messages.length === 0) {
2576
3966
  throw new ValidationProblem(
2577
3967
  "1 validation error detected: Value null at 'messages' failed to satisfy constraint: Member must not be null"
2578
3968
  );
@@ -2585,7 +3975,7 @@ var analyzeHarness = (harnessArn, body) => {
2585
3975
  modelId: harnessArn,
2586
3976
  lastUserText: facts.lastUserText,
2587
3977
  systemText: system,
2588
- tools: array(body.tools).map((tool) => isRecord4(tool) && typeof tool.name === "string" ? tool.name : void 0).filter((name) => name !== void 0),
3978
+ tools: array(body.tools).map((tool) => isRecord5(tool) && typeof tool.name === "string" ? tool.name : void 0).filter((name) => name !== void 0),
2589
3979
  toolSchemas: {},
2590
3980
  toolChoice: void 0,
2591
3981
  hasDocument: false,
@@ -2769,7 +4159,7 @@ var TURN_FAULTS = [
2769
4159
  "truncated_frame",
2770
4160
  "latency"
2771
4161
  ];
2772
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4162
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2773
4163
  var escapeGlob = (value) => new RegExp(
2774
4164
  `^${value.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`,
2775
4165
  "i"
@@ -2815,9 +4205,9 @@ var selectTurn = (script, call) => {
2815
4205
  }
2816
4206
  return turn;
2817
4207
  };
2818
- var fail = (path, message) => `${path}: ${message}`;
4208
+ var fail2 = (path, message) => `${path}: ${message}`;
2819
4209
  var checkTurn = (turn, path) => {
2820
- if (!isRecord5(turn)) return fail(path, "a turn is an object");
4210
+ if (!isRecord6(turn)) return fail2(path, "a turn is an object");
2821
4211
  const known = /* @__PURE__ */ new Set([
2822
4212
  "text",
2823
4213
  "chunkSize",
@@ -2834,77 +4224,77 @@ var checkTurn = (turn, path) => {
2834
4224
  "toolResult"
2835
4225
  ]);
2836
4226
  for (const key of Object.keys(turn)) {
2837
- if (!known.has(key)) return fail(`${path}.${key}`, "unknown turn field");
4227
+ if (!known.has(key)) return fail2(`${path}.${key}`, "unknown turn field");
2838
4228
  }
2839
4229
  if (turn.text !== void 0 && typeof turn.text !== "string")
2840
- return fail(`${path}.text`, "string");
4230
+ return fail2(`${path}.text`, "string");
2841
4231
  for (const key of ["chunkSize", "delayMsPerChunk"]) {
2842
4232
  const value = turn[key];
2843
4233
  if (value !== void 0 && (typeof value !== "number" || value < (key === "chunkSize" ? 1 : 0))) {
2844
- return fail(`${path}.${key}`, key === "chunkSize" ? "a positive number" : "ms \u2265 0");
4234
+ return fail2(`${path}.${key}`, key === "chunkSize" ? "a positive number" : "ms \u2265 0");
2845
4235
  }
2846
4236
  }
2847
4237
  if (turn.toolUse !== void 0) {
2848
4238
  const uses = Array.isArray(turn.toolUse) ? turn.toolUse : [turn.toolUse];
2849
4239
  for (const [i, use] of uses.entries()) {
2850
- if (!isRecord5(use) || typeof use.name !== "string" || use.name === "") {
2851
- return fail(`${path}.toolUse[${i}]`, "needs a name");
4240
+ if (!isRecord6(use) || typeof use.name !== "string" || use.name === "") {
4241
+ return fail2(`${path}.toolUse[${i}]`, "needs a name");
2852
4242
  }
2853
4243
  }
2854
4244
  }
2855
4245
  if (turn.stopReason !== void 0 && !STOP_REASONS.includes(turn.stopReason)) {
2856
- return fail(`${path}.stopReason`, `one of ${STOP_REASONS.join(", ")}`);
4246
+ return fail2(`${path}.stopReason`, `one of ${STOP_REASONS.join(", ")}`);
2857
4247
  }
2858
4248
  if (turn.fault !== void 0) {
2859
- const type = isRecord5(turn.fault) ? turn.fault.type : turn.fault;
4249
+ const type = isRecord6(turn.fault) ? turn.fault.type : turn.fault;
2860
4250
  if (!TURN_FAULTS.includes(type)) {
2861
- return fail(`${path}.fault`, `one of ${TURN_FAULTS.join(", ")}`);
4251
+ return fail2(`${path}.fault`, `one of ${TURN_FAULTS.join(", ")}`);
2862
4252
  }
2863
4253
  }
2864
4254
  if (turn.toolResult !== void 0 && !Array.isArray(turn.toolResult)) {
2865
- return fail(`${path}.toolResult`, "an array of {text} | {json}");
4255
+ return fail2(`${path}.toolResult`, "an array of {text} | {json}");
2866
4256
  }
2867
- if (turn.expectToolResult !== void 0 && !(isRecord5(turn.expectToolResult) && typeof turn.expectToolResult.name === "string")) {
2868
- return fail(`${path}.expectToolResult`, "{name}");
4257
+ if (turn.expectToolResult !== void 0 && !(isRecord6(turn.expectToolResult) && typeof turn.expectToolResult.name === "string")) {
4258
+ return fail2(`${path}.expectToolResult`, "{name}");
2869
4259
  }
2870
4260
  return void 0;
2871
4261
  };
2872
4262
  var parseScript = (value, index) => {
2873
4263
  const path = `scripts[${index}]`;
2874
- if (!isRecord5(value)) return fail(path, "a script is an object");
4264
+ if (!isRecord6(value)) return fail2(path, "a script is an object");
2875
4265
  if (typeof value.id !== "string" || value.id === "")
2876
- return fail(`${path}.id`, "a non-empty string");
4266
+ return fail2(`${path}.id`, "a non-empty string");
2877
4267
  if (!Array.isArray(value.turns) || value.turns.length === 0) {
2878
- return fail(`${path}.turns`, "a non-empty array");
4268
+ return fail2(`${path}.turns`, "a non-empty array");
2879
4269
  }
2880
4270
  for (const [i, turn] of value.turns.entries()) {
2881
4271
  const problem = checkTurn(turn, `${path}.turns[${i}]`);
2882
4272
  if (problem) return problem;
2883
4273
  }
2884
4274
  if (value.match !== void 0) {
2885
- if (!isRecord5(value.match)) return fail(`${path}.match`, "an object");
4275
+ if (!isRecord6(value.match)) return fail2(`${path}.match`, "an object");
2886
4276
  const match = value.match;
2887
4277
  if (match.operation !== void 0) {
2888
4278
  const ops = Array.isArray(match.operation) ? match.operation : [match.operation];
2889
4279
  for (const op of ops) {
2890
4280
  if (!MODEL_OPERATIONS.includes(op)) {
2891
- return fail(`${path}.match.operation`, `one of ${MODEL_OPERATIONS.join(", ")}`);
4281
+ return fail2(`${path}.match.operation`, `one of ${MODEL_OPERATIONS.join(", ")}`);
2892
4282
  }
2893
4283
  }
2894
4284
  }
2895
- if (isRecord5(match.lastUserText) && typeof match.lastUserText.regex === "string") {
4285
+ if (isRecord6(match.lastUserText) && typeof match.lastUserText.regex === "string") {
2896
4286
  try {
2897
4287
  new RegExp(match.lastUserText.regex);
2898
4288
  } catch {
2899
- return fail(`${path}.match.lastUserText.regex`, "not a valid regular expression");
4289
+ return fail2(`${path}.match.lastUserText.regex`, "not a valid regular expression");
2900
4290
  }
2901
4291
  }
2902
4292
  if (match.toolsInclude !== void 0 && !Array.isArray(match.toolsInclude)) {
2903
- return fail(`${path}.match.toolsInclude`, "string[]");
4293
+ return fail2(`${path}.match.toolsInclude`, "string[]");
2904
4294
  }
2905
4295
  }
2906
4296
  if (value.times !== void 0 && (typeof value.times !== "number" || value.times < 1)) {
2907
- return fail(`${path}.times`, "a positive count");
4297
+ return fail2(`${path}.times`, "a positive count");
2908
4298
  }
2909
4299
  return value;
2910
4300
  };
@@ -3621,7 +5011,7 @@ var base64 = (bytes) => {
3621
5011
  };
3622
5012
 
3623
5013
  // src/sonic.ts
3624
- var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5014
+ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3625
5015
  var utf83 = new TextDecoder();
3626
5016
  var AUDIO_CHUNK_BYTES = 4800;
3627
5017
  var sonicSession = (request, modelId, host) => {
@@ -3836,15 +5226,15 @@ var sonicSession = (request, modelId, host) => {
3836
5226
  const handle = (event) => {
3837
5227
  const [kind] = Object.keys(event);
3838
5228
  const body = kind ? event[kind] : void 0;
3839
- if (!kind || !isRecord6(body)) return;
5229
+ if (!kind || !isRecord7(body)) return;
3840
5230
  switch (kind) {
3841
5231
  case "promptStart": {
3842
5232
  promptName = String(body.promptName ?? "");
3843
- const audio = isRecord6(body.audioOutputConfiguration) ? body.audioOutputConfiguration : void 0;
5233
+ const audio = isRecord7(body.audioOutputConfiguration) ? body.audioOutputConfiguration : void 0;
3844
5234
  if (typeof audio?.sampleRateHertz === "number") outputSampleRate = audio.sampleRateHertz;
3845
- const config = isRecord6(body.toolConfiguration) ? body.toolConfiguration : void 0;
5235
+ const config = isRecord7(body.toolConfiguration) ? body.toolConfiguration : void 0;
3846
5236
  for (const tool of Array.isArray(config?.tools) ? config.tools : []) {
3847
- if (isRecord6(tool) && isRecord6(tool.toolSpec) && typeof tool.toolSpec.name === "string") {
5237
+ if (isRecord7(tool) && isRecord7(tool.toolSpec) && typeof tool.toolSpec.name === "string") {
3848
5238
  tools.push(tool.toolSpec.name);
3849
5239
  }
3850
5240
  }
@@ -3859,7 +5249,7 @@ var sonicSession = (request, modelId, host) => {
3859
5249
  text: "",
3860
5250
  audioChunks: 0
3861
5251
  });
3862
- const config = isRecord6(body.toolResultInputConfiguration) ? body.toolResultInputConfiguration : void 0;
5252
+ const config = isRecord7(body.toolResultInputConfiguration) ? body.toolResultInputConfiguration : void 0;
3863
5253
  if (config && typeof config.toolUseId === "string") {
3864
5254
  const tool = toolNames.get(config.toolUseId);
3865
5255
  if (tool) pendingToolResults.push(tool);
@@ -3920,7 +5310,7 @@ var sonicSession = (request, modelId, host) => {
3920
5310
  if (frame === null) break;
3921
5311
  if (headerString(frame, ":event-type") !== "chunk") continue;
3922
5312
  const payload = payloadJson(frame);
3923
- if (!isRecord6(payload) || typeof payload.bytes !== "string") continue;
5313
+ if (!isRecord7(payload) || typeof payload.bytes !== "string") continue;
3924
5314
  let decoded;
3925
5315
  try {
3926
5316
  decoded = JSON.parse(
@@ -3929,8 +5319,8 @@ var sonicSession = (request, modelId, host) => {
3929
5319
  } catch {
3930
5320
  continue;
3931
5321
  }
3932
- const event = isRecord6(decoded) && isRecord6(decoded.event) ? decoded.event : decoded;
3933
- if (!isRecord6(event)) continue;
5322
+ const event = isRecord7(decoded) && isRecord7(decoded.event) ? decoded.event : decoded;
5323
+ if (!isRecord7(event)) continue;
3934
5324
  if ("sessionEnd" in event) {
3935
5325
  ended = true;
3936
5326
  break;
@@ -4086,11 +5476,11 @@ var BEDROCK_PRESETS = {
4086
5476
  access_denied: everyCall("403 AccessDeniedException", { type: "access_denied" }),
4087
5477
  internal_server: everyCall("500 InternalServerException", { type: "internal_server" })
4088
5478
  };
4089
- var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
4090
- var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
4091
- var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5479
+ var json5 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
5480
+ var adminError4 = (status, message) => json5(status, { error: { type: "mockingbird_admin", message } });
5481
+ var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4092
5482
  var parseScripts = (body) => {
4093
- const list = Array.isArray(body) ? body : isRecord7(body) ? body.scripts ?? (body.id ? [body] : void 0) : void 0;
5483
+ const list = Array.isArray(body) ? body : isRecord8(body) ? body.scripts ?? (body.id ? [body] : void 0) : void 0;
4094
5484
  if (!Array.isArray(list)) return 'expected {"scripts": [{id, match?, turns: [...]}]}';
4095
5485
  const out = [];
4096
5486
  for (const [index, each] of list.entries()) {
@@ -4111,31 +5501,31 @@ var SETTING_CHECKS = {
4111
5501
  var adminRoutes = (runtime) => {
4112
5502
  const store = (replace) => ({ body, namespace }) => {
4113
5503
  const scripts = parseScripts(body);
4114
- if (typeof scripts === "string") return adminError3(400, scripts);
4115
- return json3(200, { scripts: runtime.instance(namespace).putScripts(scripts, replace) });
5504
+ if (typeof scripts === "string") return adminError4(400, scripts);
5505
+ return json5(200, { scripts: runtime.instance(namespace).putScripts(scripts, replace) });
4116
5506
  };
4117
5507
  return {
4118
5508
  "GET /scripts": ({ namespace }) => {
4119
5509
  const api = runtime.instance(namespace);
4120
- return json3(200, { scripts: api.scripts(), stats: api.stats() });
5510
+ return json5(200, { scripts: api.scripts(), stats: api.stats() });
4121
5511
  },
4122
5512
  "PUT /scripts": store(true),
4123
5513
  "POST /scripts": store(false),
4124
- "DELETE /scripts": ({ url, namespace }) => json3(200, {
5514
+ "DELETE /scripts": ({ url, namespace }) => json5(200, {
4125
5515
  removed: runtime.instance(namespace).removeScripts(url.searchParams.get("id") ?? void 0)
4126
5516
  }),
4127
- "GET /model-metrics": ({ namespace }) => json3(200, runtime.instance(namespace).stats()),
4128
- "GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
5517
+ "GET /model-metrics": ({ namespace }) => json5(200, runtime.instance(namespace).stats()),
5518
+ "GET /settings": ({ namespace }) => json5(200, runtime.instance(namespace).state.current()),
4129
5519
  "PUT /settings": ({ body, namespace }) => {
4130
- if (!isRecord7(body)) return adminError3(400, "expected a JSON object");
5520
+ if (!isRecord8(body)) return adminError4(400, "expected a JSON object");
4131
5521
  const patch = {};
4132
5522
  for (const [key, value] of Object.entries(body)) {
4133
5523
  const check = SETTING_CHECKS[key];
4134
- if (!check) return adminError3(400, `unknown setting ${key}`);
4135
- if (!check(value)) return adminError3(400, `bad value for ${key}`);
5524
+ if (!check) return adminError4(400, `unknown setting ${key}`);
5525
+ if (!check(value)) return adminError4(400, `bad value for ${key}`);
4136
5526
  patch[key] = value;
4137
5527
  }
4138
- return json3(200, runtime.instance(namespace).state.update(patch));
5528
+ return json5(200, runtime.instance(namespace).state.update(patch));
4139
5529
  }
4140
5530
  };
4141
5531
  };
@@ -4239,7 +5629,7 @@ var clockSleep = (now) => (ms, signal) => {
4239
5629
  tick();
4240
5630
  });
4241
5631
  };
4242
- var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5632
+ var isRecord9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4243
5633
  var utf84 = new TextEncoder();
4244
5634
  var titanEmbedding = async (inputText, dims = 1024) => {
4245
5635
  const seed = new Uint8Array(await crypto.subtle.digest("SHA-256", utf84.encode(inputText)));
@@ -4333,7 +5723,7 @@ var BedrockAPI = class {
4333
5723
  }
4334
5724
  planContext(body, maxTokens) {
4335
5725
  const settings = this.state.current();
4336
- const guardrail = isRecord8(body.guardrailConfig) ? body.guardrailConfig : void 0;
5726
+ const guardrail = isRecord9(body.guardrailConfig) ? body.guardrailConfig : void 0;
4337
5727
  return {
4338
5728
  nextToolUseId: () => this.state.ids.next("tooluse_", 22),
4339
5729
  chunkSize: settings.chunkSize,
@@ -4430,7 +5820,7 @@ var BedrockAPI = class {
4430
5820
  const operation = streaming ? "ConverseStream" : "Converse";
4431
5821
  const modelId = context.params.modelId ?? "";
4432
5822
  const body = this.jsonBody(context);
4433
- if (!isRecord8(body)) {
5823
+ if (!isRecord9(body)) {
4434
5824
  return bedrockError(
4435
5825
  400,
4436
5826
  "ValidationException",
@@ -4458,7 +5848,7 @@ var BedrockAPI = class {
4458
5848
  return bedrockError(400, "ValidationException", error.message, requestId);
4459
5849
  throw error;
4460
5850
  }
4461
- const inference = isRecord8(body.inferenceConfig) ? body.inferenceConfig : {};
5851
+ const inference = isRecord9(body.inferenceConfig) ? body.inferenceConfig : {};
4462
5852
  const maxTokens = typeof inference.maxTokens === "number" ? inference.maxTokens : void 0;
4463
5853
  let plan = await this.resolve(call, this.planContext(body, maxTokens));
4464
5854
  const fault = presetFault(context.request) ?? plan.fault;
@@ -4485,7 +5875,7 @@ var BedrockAPI = class {
4485
5875
  const requestId = this.requestId();
4486
5876
  const modelId = context.params.modelId ?? "";
4487
5877
  const body = this.jsonBody(context);
4488
- if (!isRecord8(body)) {
5878
+ if (!isRecord9(body)) {
4489
5879
  return bedrockError(
4490
5880
  400,
4491
5881
  "ValidationException",
@@ -4710,4 +6100,4 @@ export {
4710
6100
  titanEmbedding,
4711
6101
  BedrockAPI
4712
6102
  };
4713
- //# sourceMappingURL=chunk-4UA5HZST.js.map
6103
+ //# sourceMappingURL=chunk-7GDNJRPB.js.map