@crvouga/mockingbird-service-step-functions 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;
@@ -969,6 +971,936 @@ var clearNamespace = (sqlite, namespace) => {
969
971
  });
970
972
  };
971
973
 
974
+ // ../core/dist/surface.js
975
+ var defineMock = (runtime) => runtime;
976
+ var STANDARD_ADMIN_ROUTES = [
977
+ "GET /",
978
+ "POST /reset",
979
+ "GET /namespaces",
980
+ "GET /clock",
981
+ "POST /clock",
982
+ "GET /faults",
983
+ "POST /faults",
984
+ "DELETE /faults",
985
+ "POST /snapshots",
986
+ "POST /snapshots/:id/restore",
987
+ "DELETE /snapshots/:id",
988
+ "GET /timeline",
989
+ "POST /checkpoints",
990
+ "POST /branches/:name",
991
+ "POST /branches/:name/checkout",
992
+ "GET /requests",
993
+ "DELETE /requests",
994
+ "GET /metrics",
995
+ "DELETE /metrics",
996
+ "GET /credentials",
997
+ "PUT /credentials",
998
+ "DELETE /credentials",
999
+ "GET /state",
1000
+ "GET /state/:collection",
1001
+ "GET /state/:collection/:id",
1002
+ "POST /state/:collection",
1003
+ "PUT /state/:collection/:id",
1004
+ "PATCH /state/:collection/:id",
1005
+ "DELETE /state/:collection/:id",
1006
+ "GET /ui",
1007
+ "GET /ui/",
1008
+ "GET /ui/manifest"
1009
+ ];
1010
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
1011
+ var assertAdminUi = (ui) => {
1012
+ if (!ui?.panels)
1013
+ return;
1014
+ const seen = /* @__PURE__ */ new Set();
1015
+ for (const panel of ui.panels) {
1016
+ if (!PANEL_ID.test(panel.id)) {
1017
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
1018
+ }
1019
+ if (seen.has(panel.id))
1020
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
1021
+ seen.add(panel.id);
1022
+ if (panel.title.trim() === "")
1023
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
1024
+ }
1025
+ };
1026
+
1027
+ // ../core/dist/admin-ui.js
1028
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
1029
+ switch (char) {
1030
+ case "&":
1031
+ return "&amp;";
1032
+ case "<":
1033
+ return "&lt;";
1034
+ case ">":
1035
+ return "&gt;";
1036
+ case '"':
1037
+ return "&quot;";
1038
+ default:
1039
+ return "&#39;";
1040
+ }
1041
+ });
1042
+ var renderAdminDocument = (service) => {
1043
+ const name = escapeHtml(service);
1044
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
1045
+ return `<!DOCTYPE html>
1046
+ <html lang="en">
1047
+ <head>
1048
+ <meta charset="utf-8">
1049
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1050
+ <meta name="color-scheme" content="light dark">
1051
+ <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">
1052
+ <title>${name} admin</title>
1053
+ <style>
1054
+ :root {
1055
+ color-scheme: light;
1056
+ --bg: #f6f5f2;
1057
+ --bg-elev: #ffffff;
1058
+ --bg-muted: #eeece6;
1059
+ --bg-inset: #f3f1eb;
1060
+ --line: #e2dfd6;
1061
+ --line-strong: #d0ccc1;
1062
+ --ink: #1c1915;
1063
+ --muted: #5e584f;
1064
+ --faint: #8a8378;
1065
+ --accent: #3d4f3a;
1066
+ --accent-ink: #f7f6f2;
1067
+ --accent-soft: #e5ece2;
1068
+ --ok: #1f7a45;
1069
+ --ok-soft: #e5f4eb;
1070
+ --warn: #9a6700;
1071
+ --warn-soft: #fbf3df;
1072
+ --err: #a33b32;
1073
+ --err-soft: #fdecea;
1074
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1075
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1076
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1077
+ --radius: 14px;
1078
+ --header: 60px;
1079
+ --nav: 220px;
1080
+ }
1081
+ :root[data-theme="dark"] {
1082
+ color-scheme: dark;
1083
+ --bg: #141311;
1084
+ --bg-elev: #1e1c19;
1085
+ --bg-muted: #26231f;
1086
+ --bg-inset: #181715;
1087
+ --line: #34302b;
1088
+ --line-strong: #4a453d;
1089
+ --ink: #f4f1ea;
1090
+ --muted: #c4bdb1;
1091
+ --faint: #8f877c;
1092
+ --accent: #c5d5b8;
1093
+ --accent-ink: #1a2118;
1094
+ --accent-soft: #2a3328;
1095
+ --ok: #8fd6a8;
1096
+ --ok-soft: #1a2e22;
1097
+ --warn: #f0cc78;
1098
+ --warn-soft: #332911;
1099
+ --err: #f0a8a2;
1100
+ --err-soft: #3a201e;
1101
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1102
+ }
1103
+ @media (prefers-color-scheme: dark) {
1104
+ :root:not([data-theme="light"]) {
1105
+ color-scheme: dark;
1106
+ --bg: #141311;
1107
+ --bg-elev: #1e1c19;
1108
+ --bg-muted: #26231f;
1109
+ --bg-inset: #181715;
1110
+ --line: #34302b;
1111
+ --line-strong: #4a453d;
1112
+ --ink: #f4f1ea;
1113
+ --muted: #c4bdb1;
1114
+ --faint: #8f877c;
1115
+ --accent: #c5d5b8;
1116
+ --accent-ink: #1a2118;
1117
+ --accent-soft: #2a3328;
1118
+ --ok: #8fd6a8;
1119
+ --ok-soft: #1a2e22;
1120
+ --warn: #f0cc78;
1121
+ --warn-soft: #332911;
1122
+ --err: #f0a8a2;
1123
+ --err-soft: #3a201e;
1124
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1125
+ }
1126
+ }
1127
+ * { box-sizing: border-box; }
1128
+ html, body { margin: 0; height: 100%; }
1129
+ body {
1130
+ font-family: var(--sans);
1131
+ background: var(--bg);
1132
+ color: var(--ink);
1133
+ line-height: 1.45;
1134
+ padding-left: env(safe-area-inset-left);
1135
+ padding-right: env(safe-area-inset-right);
1136
+ -webkit-text-size-adjust: 100%;
1137
+ }
1138
+ button, input, select, textarea { font: inherit; color: inherit; }
1139
+ button { cursor: pointer; }
1140
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1141
+ @media (prefers-reduced-motion: reduce) {
1142
+ * { scroll-behavior: auto !important; transition: none !important; }
1143
+ }
1144
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1145
+ header.top {
1146
+ position: sticky; top: 0; z-index: 5;
1147
+ display: flex; align-items: center; gap: 12px;
1148
+ min-height: var(--header); padding: 10px 16px;
1149
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1150
+ border-bottom: 1px solid var(--line);
1151
+ backdrop-filter: blur(10px);
1152
+ }
1153
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1154
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1155
+ .brand span { color: var(--faint); font-size: 12px; }
1156
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1157
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1158
+ label.field input, label.field select, .controls input[type="password"] {
1159
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1160
+ padding: 7px 8px; min-height: 36px;
1161
+ }
1162
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1163
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1164
+ background: var(--bg-elev);
1165
+ }
1166
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1167
+ .btn-quiet { background: transparent; }
1168
+ .btn-danger { color: var(--err); }
1169
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1170
+ record or the full nav row would widen the page past the viewport. */
1171
+ .layout {
1172
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1173
+ flex: 1; min-height: 0; min-width: 0;
1174
+ }
1175
+ nav.side {
1176
+ border-right: 1px solid var(--line); padding: 12px;
1177
+ display: flex; flex-direction: column; gap: 4px;
1178
+ background: var(--bg-elev);
1179
+ }
1180
+ nav.side button {
1181
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1182
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1183
+ }
1184
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1185
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1186
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1187
+ .lede { margin: 0 0 16px; color: var(--muted); }
1188
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1189
+ .card {
1190
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1191
+ padding: 14px 16px; box-shadow: var(--shadow);
1192
+ }
1193
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1194
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1195
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1196
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1197
+ .collection {
1198
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1199
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1200
+ }
1201
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1202
+ .collection small { display: block; color: var(--faint); }
1203
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1204
+ .chip {
1205
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1206
+ border-radius: 999px; padding: 4px 8px;
1207
+ }
1208
+ .chip i { color: var(--faint); font-style: normal; }
1209
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1210
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1211
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1212
+ tr.clickable { cursor: pointer; }
1213
+ tr.clickable:hover { background: var(--bg-muted); }
1214
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1215
+ pre {
1216
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1217
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1218
+ }
1219
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1220
+ .banner {
1221
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1222
+ background: var(--err-soft); color: var(--err);
1223
+ }
1224
+ .banner.show { display: block; }
1225
+ .empty { color: var(--muted); padding: 24px 8px; }
1226
+ dialog {
1227
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1228
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1229
+ }
1230
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1231
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1232
+ textarea {
1233
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1234
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1235
+ font-family: var(--mono); font-size: 12px;
1236
+ }
1237
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1238
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1239
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1240
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1241
+ .status-2 { color: var(--ok); }
1242
+ .status-4, .status-5, .status-0 { color: var(--err); }
1243
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1244
+ .route {
1245
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1246
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1247
+ }
1248
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1249
+ @media (max-width: 800px) {
1250
+ header.top {
1251
+ align-items: stretch; flex-direction: column;
1252
+ padding-top: max(10px, env(safe-area-inset-top));
1253
+ }
1254
+ input, select, textarea { font-size: 16px; }
1255
+ .controls { width: 100%; }
1256
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1257
+ .layout { grid-template-columns: minmax(0, 1fr); }
1258
+ nav.side {
1259
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1260
+ border-right: 0; border-bottom: 1px solid var(--line);
1261
+ padding: 8px;
1262
+ }
1263
+ nav.side button { white-space: nowrap; flex: none; }
1264
+ .split { grid-template-columns: minmax(0, 1fr); }
1265
+ main { padding: 14px; }
1266
+ table, thead, tbody, tr, th, td { display: block; }
1267
+ thead { display: none; }
1268
+ tr {
1269
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1270
+ background: var(--bg-elev); min-width: 0;
1271
+ }
1272
+ td {
1273
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1274
+ min-width: 0; overflow-wrap: anywhere;
1275
+ }
1276
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1277
+ .route { grid-template-columns: 72px 1fr; }
1278
+ .route button { grid-column: 1 / -1; }
1279
+ }
1280
+ </style>
1281
+ </head>
1282
+ <body>
1283
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1284
+ <header class="top">
1285
+ <div class="brand">
1286
+ <strong>${name}</strong>
1287
+ <span>Mockingbird admin</span>
1288
+ </div>
1289
+ <div class="controls">
1290
+ <label class="field">Namespace
1291
+ <select id="namespace" aria-label="Namespace"></select>
1292
+ </label>
1293
+ <label class="field">Admin key
1294
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1295
+ </label>
1296
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1297
+ <button class="btn" id="refresh" type="button">Refresh</button>
1298
+ </div>
1299
+ </header>
1300
+ <div class="layout">
1301
+ <nav class="side" id="nav" aria-label="Admin sections">
1302
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1303
+ <button type="button" data-view="state">State</button>
1304
+ <button type="button" data-view="clock">Clock</button>
1305
+ <button type="button" data-view="faults">Faults</button>
1306
+ <button type="button" data-view="journal">Journal</button>
1307
+ <button type="button" data-view="routes">Routes</button>
1308
+ </nav>
1309
+ <main id="views">
1310
+ <p class="banner" id="banner" role="alert"></p>
1311
+ <section class="view" id="view-overview">
1312
+ <h2>Overview</h2>
1313
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1314
+ <div class="grid" id="overview-cards"></div>
1315
+ <h3>Recent requests</h3>
1316
+ <div id="overview-requests"></div>
1317
+ </section>
1318
+ <section class="view" id="view-state" hidden>
1319
+ <h2>State</h2>
1320
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1321
+ <div class="split">
1322
+ <div id="collections"></div>
1323
+ <div>
1324
+ <div id="schema"></div>
1325
+ <div class="row-actions">
1326
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1327
+ </div>
1328
+ <div id="records"></div>
1329
+ </div>
1330
+ </div>
1331
+ </section>
1332
+ <section class="view" id="view-clock" hidden>
1333
+ <h2>Clock</h2>
1334
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1335
+ <div class="card" id="clock-readout"></div>
1336
+ <div class="row-actions">
1337
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1338
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1339
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1340
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1341
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1342
+ <button class="btn" id="freeze" type="button">Freeze</button>
1343
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1344
+ </div>
1345
+ <form id="clock-set" class="row-actions">
1346
+ <label class="field">Set instant
1347
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1348
+ </label>
1349
+ <button class="btn-primary" type="submit">Set</button>
1350
+ </form>
1351
+ </section>
1352
+ <section class="view" id="view-faults" hidden>
1353
+ <h2>Faults</h2>
1354
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1355
+ <form id="fault-form" class="card stack">
1356
+ <label class="field">Preset
1357
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1358
+ </label>
1359
+ <label class="field">Status
1360
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1361
+ </label>
1362
+ <label class="field">Path prefix
1363
+ <input id="fault-path" placeholder="/v1">
1364
+ </label>
1365
+ <label class="field">Method
1366
+ <input id="fault-method" placeholder="GET">
1367
+ </label>
1368
+ <div class="dialog-actions">
1369
+ <button class="btn-primary" type="submit">Add fault</button>
1370
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1371
+ </div>
1372
+ </form>
1373
+ <div id="fault-list"></div>
1374
+ </section>
1375
+ <section class="view" id="view-journal" hidden>
1376
+ <h2>Journal</h2>
1377
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1378
+ <div class="row-actions">
1379
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1380
+ </div>
1381
+ <div id="journal"></div>
1382
+ </section>
1383
+ <section class="view" id="view-routes" hidden>
1384
+ <h2>Routes</h2>
1385
+ <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>
1386
+ <div id="route-list"></div>
1387
+ <form id="route-form" class="card stack">
1388
+ <strong id="route-title">Select a route</strong>
1389
+ <label class="field">JSON body
1390
+ <textarea id="route-body" placeholder="{ }"></textarea>
1391
+ </label>
1392
+ <div class="dialog-actions">
1393
+ <button class="btn-primary" type="submit">Send</button>
1394
+ </div>
1395
+ <pre id="route-result">Response will show here.</pre>
1396
+ </form>
1397
+ </section>
1398
+ </main>
1399
+ </div>
1400
+ </div>
1401
+ <dialog id="editor">
1402
+ <form method="dialog" id="editor-form">
1403
+ <strong id="editor-title">Record</strong>
1404
+ <label class="field">Id
1405
+ <input id="editor-id" required>
1406
+ </label>
1407
+ <label class="field">JSON value
1408
+ <textarea id="editor-value"></textarea>
1409
+ </label>
1410
+ <div class="dialog-actions">
1411
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1412
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1413
+ <button class="btn-primary" type="submit" value="save">Save</button>
1414
+ </div>
1415
+ </form>
1416
+ </dialog>
1417
+ <script>
1418
+ (() => {
1419
+ const STANDARD = new Set(${standard})
1420
+ const state = {
1421
+ namespace: "default",
1422
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1423
+ view: "overview",
1424
+ collection: "",
1425
+ shape: null,
1426
+ route: null,
1427
+ editing: null
1428
+ }
1429
+ const $ = (id) => document.getElementById(id)
1430
+ const banner = $("banner")
1431
+ const keyInput = $("admin-key")
1432
+ keyInput.value = state.key
1433
+ const params = new URLSearchParams(location.search)
1434
+ if (params.get("key")) {
1435
+ state.key = params.get("key")
1436
+ keyInput.value = state.key
1437
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1438
+ params.delete("key")
1439
+ const next = params.toString()
1440
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1441
+ }
1442
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1443
+
1444
+ const showError = (error) => {
1445
+ banner.textContent = error instanceof Error ? error.message : String(error)
1446
+ banner.classList.add("show")
1447
+ }
1448
+ const clearError = () => banner.classList.remove("show")
1449
+
1450
+ async function originGet(path) {
1451
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1452
+ if (!response.ok) throw new Error(response.status + " " + path)
1453
+ return response.json()
1454
+ }
1455
+ async function api(method, path, body) {
1456
+ const headers = { accept: "application/json" }
1457
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1458
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1459
+ if (body !== undefined) headers["content-type"] = "application/json"
1460
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1461
+ method,
1462
+ headers,
1463
+ body: body === undefined ? undefined : JSON.stringify(body)
1464
+ })
1465
+ const text = await response.text()
1466
+ let data = null
1467
+ if (text) {
1468
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1469
+ }
1470
+ if (response.status === 401) {
1471
+ keyInput.focus()
1472
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1473
+ }
1474
+ if (!response.ok) {
1475
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1476
+ }
1477
+ return data
1478
+ }
1479
+ const panelApi = {
1480
+ get: (path) => api("GET", path),
1481
+ send: (method, path, body) => api(method, path, body),
1482
+ namespace: () => state.namespace
1483
+ }
1484
+
1485
+ function setTheme(theme) {
1486
+ if (theme) document.documentElement.dataset.theme = theme
1487
+ else delete document.documentElement.dataset.theme
1488
+ }
1489
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1490
+ if (storedTheme) setTheme(storedTheme)
1491
+ $("theme").addEventListener("click", () => {
1492
+ const current = document.documentElement.dataset.theme
1493
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1494
+ const next = dark ? "light" : "dark"
1495
+ localStorage.setItem("mockingbird-admin-theme", next)
1496
+ setTheme(next)
1497
+ })
1498
+
1499
+ function show(view) {
1500
+ state.view = view
1501
+ for (const button of document.querySelectorAll("#nav button")) {
1502
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1503
+ }
1504
+ for (const section of document.querySelectorAll("main .view")) {
1505
+ section.hidden = section.id !== "view-" + view
1506
+ }
1507
+ }
1508
+ document.getElementById("nav").addEventListener("click", (event) => {
1509
+ const button = event.target.closest("button[data-view]")
1510
+ if (!button) return
1511
+ show(button.dataset.view)
1512
+ refresh().catch(showError)
1513
+ })
1514
+
1515
+ function cards(items) {
1516
+ return '<div class="grid">' + items.map((item) =>
1517
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1518
+ ).join("") + "</div>"
1519
+ }
1520
+ function table(columns, rows) {
1521
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1522
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1523
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1524
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1525
+ ).join("") + "</tr>").join("")
1526
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1527
+ }
1528
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1529
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1530
+ }[char]))
1531
+ const preview = (value) => {
1532
+ const text = JSON.stringify(value)
1533
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1534
+ }
1535
+ const when = (epoch) => {
1536
+ const date = new Date(epoch)
1537
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1538
+ }
1539
+ const clockCard = (epoch) => {
1540
+ const date = new Date(epoch)
1541
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1542
+ const iso = date.toISOString()
1543
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1544
+ }
1545
+
1546
+ async function loadNamespaces() {
1547
+ const data = await api("GET", "/namespaces")
1548
+ const select = $("namespace")
1549
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1550
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1551
+ select.innerHTML = names.map((name) =>
1552
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1553
+ ).join("")
1554
+ select.value = state.namespace
1555
+ }
1556
+
1557
+ async function renderOverview() {
1558
+ const [health, shape, clock, journal] = await Promise.all([
1559
+ originGet("/health"),
1560
+ api("GET", "/state"),
1561
+ api("GET", "/clock"),
1562
+ api("GET", "/requests?limit=8")
1563
+ ])
1564
+ state.shape = shape
1565
+ $("overview-cards").innerHTML = cards([
1566
+ { k: "Service", v: esc(health.service || "${name}") },
1567
+ { k: "Status", v: esc(health.status || "ok") },
1568
+ { k: "Namespace", v: esc(state.namespace) },
1569
+ { k: "Collections", v: String(shape.collections.length) },
1570
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1571
+ { k: "Clock", v: clockCard(clock.now) }
1572
+ ])
1573
+ const requests = (journal && journal.requests) || []
1574
+ $("overview-requests").innerHTML = table(
1575
+ [
1576
+ { label: "Method", cell: (row) => esc(row.method) },
1577
+ { label: "Path", cell: (row) => esc(row.path) },
1578
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1579
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1580
+ ],
1581
+ requests
1582
+ )
1583
+ }
1584
+
1585
+ function schemaChips(collection) {
1586
+ if (!collection || collection.fields.length === 0) {
1587
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
1588
+ }
1589
+ return '<div class="chips">' + collection.fields.map((field) =>
1590
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
1591
+ ).join("") + "</div>"
1592
+ }
1593
+
1594
+ async function renderState() {
1595
+ const shape = await api("GET", "/state")
1596
+ state.shape = shape
1597
+ const host = $("collections")
1598
+ if (shape.collections.length === 0) {
1599
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
1600
+ $("schema").innerHTML = ""
1601
+ $("records").innerHTML = ""
1602
+ return
1603
+ }
1604
+ if (!shape.collections.some((item) => item.name === state.collection)) {
1605
+ state.collection = shape.collections[0].name
1606
+ }
1607
+ host.innerHTML = shape.collections.map((item) =>
1608
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
1609
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
1610
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
1611
+ ).join("")
1612
+ const selected = shape.collections.find((item) => item.name === state.collection)
1613
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
1614
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
1615
+ schemaChips(selected)
1616
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
1617
+ const rows = page.records.map((record) => ({
1618
+ ...record,
1619
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
1620
+ }))
1621
+ $("records").innerHTML = table(
1622
+ [
1623
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
1624
+ { label: "Seq", cell: (row) => esc(row.seq) },
1625
+ { label: "Value", cell: (row) => preview(row.value) }
1626
+ ],
1627
+ rows
1628
+ )
1629
+ }
1630
+
1631
+ async function renderClock() {
1632
+ const clock = await api("GET", "/clock")
1633
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
1634
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
1635
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
1636
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
1637
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
1638
+ }
1639
+
1640
+ async function renderFaults() {
1641
+ const [faults, presets] = await Promise.all([
1642
+ api("GET", "/faults"),
1643
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
1644
+ ])
1645
+ const select = $("fault-preset")
1646
+ const current = select.value
1647
+ const list = presets.presets || []
1648
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
1649
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
1650
+ ).join("")
1651
+ select.value = current
1652
+ const rules = faults.faults || []
1653
+ $("fault-list").innerHTML = table(
1654
+ [
1655
+ { label: "Id", cell: (row) => esc(row.id) },
1656
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
1657
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
1658
+ ],
1659
+ rules
1660
+ )
1661
+ }
1662
+
1663
+ async function renderJournal() {
1664
+ const journal = await api("GET", "/requests?limit=100")
1665
+ $("journal").innerHTML = table(
1666
+ [
1667
+ { label: "When", cell: (row) => esc(row.at || "") },
1668
+ { label: "Method", cell: (row) => esc(row.method) },
1669
+ { label: "Path", cell: (row) => esc(row.path) },
1670
+ { label: "Status", cell: (row) => esc(row.status) },
1671
+ { label: "ms", cell: (row) => esc(row.durationMs) }
1672
+ ],
1673
+ journal.requests || []
1674
+ )
1675
+ }
1676
+
1677
+ async function renderRoutes() {
1678
+ const data = await api("GET", "/")
1679
+ const routes = data.routes || []
1680
+ $("route-list").innerHTML = routes.map((route) => {
1681
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
1682
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
1683
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
1684
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
1685
+ }).join("")
1686
+ }
1687
+
1688
+ const renderers = {
1689
+ overview: renderOverview,
1690
+ state: renderState,
1691
+ clock: renderClock,
1692
+ faults: renderFaults,
1693
+ journal: renderJournal,
1694
+ routes: renderRoutes
1695
+ }
1696
+
1697
+ async function refresh() {
1698
+ clearError()
1699
+ if (state.view in renderers) await renderers[state.view]()
1700
+ }
1701
+
1702
+ $("namespace").addEventListener("change", () => {
1703
+ state.namespace = $("namespace").value
1704
+ refresh().catch(showError)
1705
+ })
1706
+ keyInput.addEventListener("change", () => {
1707
+ state.key = keyInput.value.trim()
1708
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1709
+ refresh().catch(showError)
1710
+ })
1711
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
1712
+
1713
+ $("collections").addEventListener("click", (event) => {
1714
+ const button = event.target.closest("[data-collection]")
1715
+ if (!button) return
1716
+ state.collection = button.dataset.collection
1717
+ renderState().catch(showError)
1718
+ })
1719
+ $("records").addEventListener("click", (event) => {
1720
+ const row = event.target.closest("[data-id]")
1721
+ if (!row) return
1722
+ openEditor(row.dataset.id).catch(showError)
1723
+ })
1724
+
1725
+ const editor = $("editor")
1726
+ async function openEditor(id) {
1727
+ state.editing = id || null
1728
+ $("editor-title").textContent = id ? "Edit record" : "New record"
1729
+ $("editor-id").value = id || ""
1730
+ $("editor-id").readOnly = Boolean(id)
1731
+ $("editor-delete").hidden = !id
1732
+ if (id) {
1733
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1734
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
1735
+ } else {
1736
+ $("editor-value").value = "{\\n \\n}"
1737
+ }
1738
+ editor.showModal()
1739
+ }
1740
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
1741
+ $("editor-form").addEventListener("submit", (event) => {
1742
+ const submitter = event.submitter
1743
+ if (!submitter || submitter.value !== "save") return
1744
+ event.preventDefault()
1745
+ let value
1746
+ try { value = JSON.parse($("editor-value").value) }
1747
+ catch { showError(new Error("Value is not JSON")); return }
1748
+ const id = $("editor-id").value.trim()
1749
+ const path = "/state/" + encodeURIComponent(state.collection)
1750
+ const request = state.editing
1751
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
1752
+ : api("POST", path, { id: id || undefined, value })
1753
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
1754
+ })
1755
+ $("editor-delete").addEventListener("click", () => {
1756
+ const id = state.editing
1757
+ if (!id) return
1758
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1759
+ .then(() => { editor.close(); return renderState() })
1760
+ .catch(showError)
1761
+ })
1762
+
1763
+ document.querySelectorAll("[data-advance]").forEach((button) => {
1764
+ button.addEventListener("click", () => {
1765
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
1766
+ })
1767
+ })
1768
+ $("freeze").addEventListener("click", () => {
1769
+ const frozen = $("freeze").dataset.frozen === "1"
1770
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
1771
+ })
1772
+ $("clock-reset").addEventListener("click", () => {
1773
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
1774
+ })
1775
+ $("clock-set").addEventListener("submit", (event) => {
1776
+ event.preventDefault()
1777
+ const raw = $("clock-instant").value.trim()
1778
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
1779
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
1780
+ })
1781
+
1782
+ $("fault-form").addEventListener("submit", (event) => {
1783
+ event.preventDefault()
1784
+ const preset = $("fault-preset").value
1785
+ const body = preset
1786
+ ? { preset }
1787
+ : {
1788
+ status: Number($("fault-status").value),
1789
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
1790
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
1791
+ }
1792
+ if (!preset && !Number.isFinite(body.status)) {
1793
+ showError(new Error("Status must be a number, or choose a preset"))
1794
+ return
1795
+ }
1796
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
1797
+ })
1798
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
1799
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
1800
+
1801
+ $("route-list").addEventListener("click", (event) => {
1802
+ const button = event.target.closest("[data-route]")
1803
+ if (!button) return
1804
+ state.route = button.dataset.route
1805
+ $("route-title").textContent = state.route
1806
+ const method = state.route.split(" ")[0]
1807
+ $("route-body").disabled = method === "GET" || method === "DELETE"
1808
+ })
1809
+ $("route-form").addEventListener("submit", async (event) => {
1810
+ event.preventDefault()
1811
+ if (!state.route) return showError(new Error("Choose a route first"))
1812
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
1813
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
1814
+ let body
1815
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
1816
+ try { body = JSON.parse($("route-body").value) }
1817
+ catch { return showError(new Error("Body is not JSON")) }
1818
+ }
1819
+ try {
1820
+ const data = await api(method, concrete, body)
1821
+ $("route-result").textContent = JSON.stringify(data, null, 2)
1822
+ } catch (error) {
1823
+ showError(error)
1824
+ }
1825
+ })
1826
+
1827
+ function mountPanels(panels) {
1828
+ const nav = $("nav")
1829
+ const views = $("views")
1830
+ for (const panel of panels) {
1831
+ const button = document.createElement("button")
1832
+ button.type = "button"
1833
+ button.dataset.view = panel.id
1834
+ button.textContent = panel.title
1835
+ nav.append(button)
1836
+ const section = document.createElement("section")
1837
+ section.className = "view"
1838
+ section.id = "view-" + panel.id
1839
+ section.hidden = true
1840
+ const title = document.createElement("h2")
1841
+ title.textContent = panel.title
1842
+ const lede = document.createElement("p")
1843
+ lede.className = "lede"
1844
+ lede.textContent = panel.description || ""
1845
+ const body = document.createElement("div")
1846
+ body.className = "panel-body"
1847
+ body.id = "panel-" + panel.id
1848
+ body.innerHTML = panel.html || ""
1849
+ section.append(title, lede, body)
1850
+ views.append(section)
1851
+ if (panel.script) {
1852
+ try {
1853
+ const run = new Function("root", "api", panel.script)
1854
+ run(body, panelApi)
1855
+ } catch (error) {
1856
+ const note = document.createElement("p")
1857
+ note.className = "banner show"
1858
+ note.textContent = error instanceof Error ? error.message : String(error)
1859
+ body.append(note)
1860
+ }
1861
+ }
1862
+ }
1863
+ }
1864
+
1865
+ loadNamespaces()
1866
+ .then(() => api("GET", "/ui/manifest"))
1867
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
1868
+ .catch(showError)
1869
+ })()
1870
+ </script>
1871
+ </body>
1872
+ </html>`;
1873
+ };
1874
+ var htmlResponse = (body) => new Response(body, {
1875
+ status: 200,
1876
+ headers: {
1877
+ "content-type": "text/html; charset=utf-8",
1878
+ "cache-control": "no-store"
1879
+ }
1880
+ });
1881
+ var json2 = (body) => new Response(JSON.stringify(body), {
1882
+ status: 200,
1883
+ headers: { "content-type": "application/json; charset=utf-8" }
1884
+ });
1885
+ var adminUiRoutes = (service, ui) => {
1886
+ const shell = () => renderAdminDocument(service);
1887
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
1888
+ return {
1889
+ "GET /ui": () => htmlResponse(document2()),
1890
+ "GET /ui/": () => htmlResponse(document2()),
1891
+ "GET /ui/manifest": () => json2({
1892
+ service,
1893
+ panels: (ui?.panels ?? []).map((panel) => ({
1894
+ id: panel.id,
1895
+ title: panel.title,
1896
+ ...panel.description !== void 0 ? { description: panel.description } : {},
1897
+ html: panel.html,
1898
+ ...panel.script !== void 0 ? { script: panel.script } : {}
1899
+ }))
1900
+ })
1901
+ };
1902
+ };
1903
+
972
1904
  // ../../../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/request/constants.js
973
1905
  var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
974
1906
 
@@ -1436,15 +2368,449 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1436
2368
  });
1437
2369
  };
1438
2370
 
2371
+ // ../core/dist/state-view.js
2372
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2373
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2374
+ var SAMPLE = 25;
2375
+ var WALK_LIMIT = 1e4;
2376
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2377
+ var fail = (status, message) => ({ ok: false, status, message });
2378
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2379
+ var kindOf = (value) => {
2380
+ if (value === null)
2381
+ return "null";
2382
+ if (Array.isArray(value))
2383
+ return "array";
2384
+ switch (typeof value) {
2385
+ case "string":
2386
+ return "string";
2387
+ case "number":
2388
+ return Number.isFinite(value) ? "number" : "unknown";
2389
+ case "boolean":
2390
+ return "boolean";
2391
+ case "object":
2392
+ return "object";
2393
+ default:
2394
+ return "unknown";
2395
+ }
2396
+ };
2397
+ var humanize = (name) => {
2398
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2399
+ if (words === "")
2400
+ return name;
2401
+ return words.charAt(0).toUpperCase() + words.slice(1);
2402
+ };
2403
+ var jsonValue = (value) => {
2404
+ if (value === void 0)
2405
+ return fail(400, "value is required");
2406
+ try {
2407
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2408
+ } catch {
2409
+ return fail(400, "value must be JSON");
2410
+ }
2411
+ };
2412
+ var ctorName = (value) => {
2413
+ const ctor = value.constructor;
2414
+ return typeof ctor?.name === "string" ? ctor.name : "";
2415
+ };
2416
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2417
+ var discoverCollections = (root) => {
2418
+ const found = [];
2419
+ const seen = /* @__PURE__ */ new Set();
2420
+ const visit = (value, depth) => {
2421
+ if (found.length + seen.size > WALK_LIMIT)
2422
+ return;
2423
+ if (value === null || typeof value !== "object")
2424
+ return;
2425
+ if (seen.has(value))
2426
+ return;
2427
+ seen.add(value);
2428
+ if (value instanceof Collection) {
2429
+ found.push(value);
2430
+ return;
2431
+ }
2432
+ if (value instanceof Map) {
2433
+ for (const child of value.values())
2434
+ visit(child, depth + 1);
2435
+ return;
2436
+ }
2437
+ if (value instanceof Set) {
2438
+ for (const child of value.values())
2439
+ visit(child, depth + 1);
2440
+ return;
2441
+ }
2442
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2443
+ return;
2444
+ if (Array.isArray(value)) {
2445
+ const cap = Math.min(value.length, 32);
2446
+ for (let i = 0; i < cap; i++)
2447
+ visit(value[i], depth + 1);
2448
+ return;
2449
+ }
2450
+ let children;
2451
+ try {
2452
+ children = Object.values(value);
2453
+ } catch {
2454
+ return;
2455
+ }
2456
+ for (const child of children)
2457
+ visit(child, depth + 1);
2458
+ };
2459
+ visit(root, 0);
2460
+ return found;
2461
+ };
2462
+ var storedNames = (sqlite, namespace) => {
2463
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2464
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2465
+ return [...records, ...sequences].map((row) => row.name);
2466
+ };
2467
+ var blankAccum = (name) => ({
2468
+ name,
2469
+ kinds: /* @__PURE__ */ new Set(),
2470
+ present: 0,
2471
+ nested: /* @__PURE__ */ new Map()
2472
+ });
2473
+ var absorb = (accum, value) => {
2474
+ const kind = kindOf(value);
2475
+ accum.kinds.add(kind);
2476
+ accum.present++;
2477
+ if (!isRecord2(value))
2478
+ return;
2479
+ for (const [key, child] of Object.entries(value)) {
2480
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2481
+ absorb(nested, child);
2482
+ accum.nested.set(key, nested);
2483
+ }
2484
+ };
2485
+ var finishField = (accum, samples) => {
2486
+ const kinds = [...accum.kinds];
2487
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2488
+ const field = {
2489
+ name: accum.name,
2490
+ kind,
2491
+ optional: accum.present < samples || kinds.includes("null")
2492
+ };
2493
+ if (accum.nested.size > 0) {
2494
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2495
+ }
2496
+ return field;
2497
+ };
2498
+ var inferFields = (records) => {
2499
+ if (records.length === 0)
2500
+ return [];
2501
+ const sample = records.slice(0, SAMPLE);
2502
+ const objects = sample.filter((record) => isRecord2(record.value));
2503
+ if (objects.length === 0) {
2504
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2505
+ const list = [...kinds];
2506
+ return [
2507
+ {
2508
+ name: "(value)",
2509
+ kind: list.length === 1 ? list[0] : "unknown",
2510
+ optional: false
2511
+ }
2512
+ ];
2513
+ }
2514
+ const root = /* @__PURE__ */ new Map();
2515
+ for (const record of objects) {
2516
+ for (const [key, value] of Object.entries(record.value)) {
2517
+ const accum = root.get(key) ?? blankAccum(key);
2518
+ absorb(accum, value);
2519
+ root.set(key, accum);
2520
+ }
2521
+ }
2522
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2523
+ };
2524
+ var mergeFields = (declared, inferred) => {
2525
+ const byName = /* @__PURE__ */ new Map();
2526
+ for (const field of inferred)
2527
+ byName.set(field.name, field);
2528
+ const ordered = [];
2529
+ const seen = /* @__PURE__ */ new Set();
2530
+ for (const field of declared ?? []) {
2531
+ const found = byName.get(field.name);
2532
+ seen.add(field.name);
2533
+ if (!found) {
2534
+ ordered.push({ ...field, optional: field.optional });
2535
+ continue;
2536
+ }
2537
+ ordered.push({
2538
+ ...found,
2539
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2540
+ optional: field.optional || found.optional,
2541
+ ...field.description !== void 0 ? { description: field.description } : {},
2542
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2543
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2544
+ });
2545
+ }
2546
+ for (const field of inferred) {
2547
+ if (!seen.has(field.name))
2548
+ ordered.push(field);
2549
+ }
2550
+ return ordered;
2551
+ };
2552
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2553
+ var readRecord = (collection, id) => {
2554
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2555
+ const row = rows.find((entry) => entry.id === id);
2556
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2557
+ };
2558
+ var inspectState = (scope) => {
2559
+ const declared = /* @__PURE__ */ new Map();
2560
+ for (const declaration of scope.declarations ?? []) {
2561
+ if (COLLECTION_NAME.test(declaration.name))
2562
+ declared.set(declaration.name, declaration);
2563
+ }
2564
+ const names = new Set(declared.keys());
2565
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2566
+ names.add(name);
2567
+ for (const collection of discoverCollections(scope.root)) {
2568
+ if (collection.namespace === scope.storageNamespace)
2569
+ names.add(collection.collectionName);
2570
+ }
2571
+ const collections = [];
2572
+ for (const name of names) {
2573
+ if (!COLLECTION_NAME.test(name))
2574
+ continue;
2575
+ const declaration = declared.get(name);
2576
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2577
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2578
+ const inferred = inferFields(records);
2579
+ const fields = mergeFields(declaration?.fields, inferred);
2580
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2581
+ collections.push({
2582
+ name,
2583
+ label: declaration?.label ?? humanize(name),
2584
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2585
+ count: collection.count(),
2586
+ source,
2587
+ fields,
2588
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2589
+ });
2590
+ }
2591
+ const order = /* @__PURE__ */ new Map();
2592
+ for (const [index, item] of (scope.declarations ?? []).entries())
2593
+ order.set(item.name, index);
2594
+ collections.sort((a, b) => {
2595
+ const left = order.get(a.name);
2596
+ const right = order.get(b.name);
2597
+ if (left !== void 0 && right !== void 0)
2598
+ return left - right;
2599
+ if (left !== void 0)
2600
+ return -1;
2601
+ if (right !== void 0)
2602
+ return 1;
2603
+ return a.name.localeCompare(b.name);
2604
+ });
2605
+ return {
2606
+ namespace: scope.namespace,
2607
+ storageNamespace: scope.storageNamespace,
2608
+ collections
2609
+ };
2610
+ };
2611
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2612
+ if (!COLLECTION_NAME.test(name))
2613
+ return fail(400, "collection name is not allowed");
2614
+ const limit = query.limit ?? 50;
2615
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2616
+ return fail(400, "limit must be an integer from 1 to 200");
2617
+ }
2618
+ const order = query.order ?? "newest";
2619
+ if (order !== "newest" && order !== "oldest")
2620
+ return fail(400, 'order must be "newest" or "oldest"');
2621
+ const collection = collectionOf(sqlite, storageNamespace, name);
2622
+ const rows = collection.list({ order }).filter((row) => {
2623
+ if (query.after === void 0)
2624
+ return true;
2625
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2626
+ });
2627
+ const slice = rows.slice(0, limit);
2628
+ const last = slice.at(-1);
2629
+ return {
2630
+ ok: true,
2631
+ value: {
2632
+ collection: name,
2633
+ count: collection.count(),
2634
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2635
+ next: rows.length > limit && last ? last.seq : null
2636
+ }
2637
+ };
2638
+ };
2639
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2640
+ var readStateRecord = (scope, name, id) => {
2641
+ if (!COLLECTION_NAME.test(name))
2642
+ return fail(400, "collection name is not allowed");
2643
+ if (!RECORD_ID.test(id))
2644
+ return fail(400, "record id is not allowed");
2645
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2646
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
2647
+ };
2648
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2649
+ var createStateRecord = (scope, name, input) => {
2650
+ if (!COLLECTION_NAME.test(name))
2651
+ return fail(400, "collection name is not allowed");
2652
+ const parsed = jsonValue(input.value);
2653
+ if (!parsed.ok)
2654
+ return parsed;
2655
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2656
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2657
+ const checked = requireId(id);
2658
+ if (!checked.ok)
2659
+ return checked;
2660
+ if (collection.has(checked.value))
2661
+ return fail(409, `record ${checked.value} already exists`);
2662
+ const stored = collection.insert(checked.value, parsed.value);
2663
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2664
+ };
2665
+ var replaceStateRecord = (scope, name, id, value) => {
2666
+ if (!COLLECTION_NAME.test(name))
2667
+ return fail(400, "collection name is not allowed");
2668
+ const checked = requireId(id);
2669
+ if (!checked.ok)
2670
+ return checked;
2671
+ const parsed = jsonValue(value);
2672
+ if (!parsed.ok)
2673
+ return parsed;
2674
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2675
+ if (!collection.has(checked.value))
2676
+ return fail(404, `no record ${checked.value} in ${name}`);
2677
+ const stored = collection.update(checked.value, parsed.value);
2678
+ if (!stored)
2679
+ return fail(404, `no record ${checked.value} in ${name}`);
2680
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2681
+ };
2682
+ var patchStateRecord = (scope, name, id, value) => {
2683
+ const current = readStateRecord(scope, name, id);
2684
+ if (!current.ok)
2685
+ return current;
2686
+ const parsed = jsonValue(value);
2687
+ if (!parsed.ok)
2688
+ return parsed;
2689
+ const next = isRecord2(current.value.value) && isRecord2(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2690
+ return replaceStateRecord(scope, name, id, next);
2691
+ };
2692
+ var deleteStateRecord = (scope, name, id) => {
2693
+ if (!COLLECTION_NAME.test(name))
2694
+ return fail(400, "collection name is not allowed");
2695
+ const checked = requireId(id);
2696
+ if (!checked.ok)
2697
+ return checked;
2698
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2699
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2700
+ };
2701
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2702
+ status,
2703
+ headers: { "content-type": "application/json; charset=utf-8" }
2704
+ });
2705
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2706
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2707
+ var integerParam = (value) => {
2708
+ if (value === null)
2709
+ return void 0;
2710
+ if (!/^-?\d+$/.test(value))
2711
+ return "bad";
2712
+ return Number(value);
2713
+ };
2714
+ var stateAdminRoutes = (routes) => {
2715
+ const open = (namespace) => {
2716
+ try {
2717
+ return { ok: true, value: routes.open(namespace) };
2718
+ } catch (error) {
2719
+ return fail(400, error instanceof Error ? error.message : String(error));
2720
+ }
2721
+ };
2722
+ const wrote = (namespace) => {
2723
+ routes.afterWrite?.(namespace);
2724
+ };
2725
+ return {
2726
+ "GET /state": ({ namespace }) => {
2727
+ const scope = open(namespace);
2728
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2729
+ },
2730
+ "GET /state/:collection": ({ namespace, params, url }) => {
2731
+ const scope = open(namespace);
2732
+ if (!scope.ok)
2733
+ return fromResult(scope, 200);
2734
+ const limit = integerParam(url.searchParams.get("limit"));
2735
+ const after = integerParam(url.searchParams.get("after"));
2736
+ if (limit === "bad")
2737
+ return adminError2(400, "limit: expected an integer");
2738
+ if (after === "bad")
2739
+ return adminError2(400, "after: expected a sequence number");
2740
+ const order = url.searchParams.get("order");
2741
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2742
+ ...limit !== void 0 ? { limit } : {},
2743
+ ...after !== void 0 ? { after } : {},
2744
+ ...order === "newest" || order === "oldest" ? { order } : {}
2745
+ }), 200);
2746
+ },
2747
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2748
+ const scope = open(namespace);
2749
+ if (!scope.ok)
2750
+ return fromResult(scope, 200);
2751
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2752
+ },
2753
+ "POST /state/:collection": ({ namespace, params, body }) => {
2754
+ const scope = open(namespace);
2755
+ if (!scope.ok)
2756
+ return fromResult(scope, 201);
2757
+ if (!isRecord2(body) || !("value" in body)) {
2758
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2759
+ }
2760
+ const id = body.id;
2761
+ if (id !== void 0 && typeof id !== "string")
2762
+ return adminError2(400, "id must be a string");
2763
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2764
+ ...typeof id === "string" ? { id } : {},
2765
+ value: body.value
2766
+ });
2767
+ if (created.ok)
2768
+ wrote(namespace);
2769
+ return fromResult(created, 201);
2770
+ },
2771
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2772
+ const scope = open(namespace);
2773
+ if (!scope.ok)
2774
+ return fromResult(scope, 200);
2775
+ if (!isRecord2(body) || !("value" in body))
2776
+ return adminError2(400, 'expected {"value": <json>}');
2777
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2778
+ if (replaced.ok)
2779
+ wrote(namespace);
2780
+ return fromResult(replaced, 200);
2781
+ },
2782
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2783
+ const scope = open(namespace);
2784
+ if (!scope.ok)
2785
+ return fromResult(scope, 200);
2786
+ if (!isRecord2(body) || !("value" in body))
2787
+ return adminError2(400, 'expected {"value": <json>}');
2788
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2789
+ if (patched.ok)
2790
+ wrote(namespace);
2791
+ return fromResult(patched, 200);
2792
+ },
2793
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2794
+ const scope = open(namespace);
2795
+ if (!scope.ok)
2796
+ return fromResult(scope, 200);
2797
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2798
+ if (removed.ok)
2799
+ wrote(namespace);
2800
+ return fromResult(removed, 200);
2801
+ }
2802
+ };
2803
+ };
2804
+
1439
2805
  // ../core/dist/version.js
1440
- var PACKAGE_VERSION = true ? "1.2.0" : UNRELEASED_VERSION;
2806
+ var PACKAGE_VERSION = true ? "1.4.0" : UNRELEASED_VERSION;
1441
2807
 
1442
2808
  // ../core/dist/webhooks.js
1443
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1444
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1445
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2809
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2810
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2811
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1446
2812
  var parseEndpoint = (value) => {
1447
- if (!isRecord2(value) || typeof value.url !== "string")
2813
+ if (!isRecord3(value) || typeof value.url !== "string")
1448
2814
  return "each endpoint needs a url";
1449
2815
  try {
1450
2816
  new URL(value.url);
@@ -1461,18 +2827,18 @@ var parseEndpoint = (value) => {
1461
2827
  const events = value.events ?? value.enabledEvents;
1462
2828
  if (Array.isArray(events))
1463
2829
  endpoint.events = events.map(String);
1464
- if (isRecord2(value.tags)) {
2830
+ if (isRecord3(value.tags)) {
1465
2831
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1466
2832
  }
1467
2833
  if (typeof value.account === "string")
1468
2834
  endpoint.tags = { ...endpoint.tags, account: value.account };
1469
- if (isRecord2(value.headers)) {
2835
+ if (isRecord3(value.headers)) {
1470
2836
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1471
2837
  }
1472
2838
  return endpoint;
1473
2839
  };
1474
2840
  var webhookAdminRoutes = (hub) => ({
1475
- "GET /webhooks": ({ url, namespace }) => json2(200, {
2841
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
1476
2842
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1477
2843
  const type = url.searchParams.get("type");
1478
2844
  return type === null || d.type === type;
@@ -1480,51 +2846,51 @@ var webhookAdminRoutes = (hub) => ({
1480
2846
  }),
1481
2847
  "GET /webhooks/events": ({ url, namespace }) => {
1482
2848
  const type = url.searchParams.get("type");
1483
- return json2(200, {
2849
+ return json4(200, {
1484
2850
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1485
2851
  });
1486
2852
  },
1487
2853
  "POST /webhooks/:id/replay": async ({ params }) => {
1488
2854
  const replayed = await hub.replay(params.id);
1489
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
2855
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1490
2856
  },
1491
2857
  "POST /webhooks/flush": async () => {
1492
2858
  await hub.flush();
1493
- return json2(200, { status: "ok" });
2859
+ return json4(200, { status: "ok" });
1494
2860
  },
1495
2861
  "POST /webhooks/faults": ({ body, namespace }) => {
1496
- if (!isRecord2(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1497
- return adminError2(400, "mode must be duplicate, reorder or drop");
2862
+ if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2863
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1498
2864
  }
1499
2865
  const fault = { mode: body.mode };
1500
2866
  if (typeof body.count === "number")
1501
2867
  fault.count = body.count;
1502
2868
  hub.fault(namespace, fault);
1503
- return json2(201, { namespace, ...fault });
2869
+ return json4(201, { namespace, ...fault });
1504
2870
  },
1505
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
2871
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
1506
2872
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1507
2873
  ...rest,
1508
2874
  secret: secret ? "(set)" : null
1509
2875
  }))
1510
2876
  }),
1511
2877
  "PUT /webhook-endpoints": ({ body, namespace }) => {
1512
- const list = Array.isArray(body) ? body : isRecord2(body) ? body.endpoints : void 0;
2878
+ const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
1513
2879
  if (!Array.isArray(list))
1514
- return adminError2(400, "expected [{url, secret?, events?}]");
2880
+ return adminError3(400, "expected [{url, secret?, events?}]");
1515
2881
  const parsed = [];
1516
2882
  for (const each of list) {
1517
2883
  const endpoint = parseEndpoint(each);
1518
2884
  if (typeof endpoint === "string")
1519
- return adminError2(400, endpoint);
2885
+ return adminError3(400, endpoint);
1520
2886
  parsed.push(endpoint);
1521
2887
  }
1522
2888
  const set = hub.setEndpoints(namespace, parsed);
1523
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2889
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1524
2890
  },
1525
2891
  "DELETE /webhook-endpoints": ({ namespace }) => {
1526
2892
  hub.setEndpoints(namespace, []);
1527
- return json2(200, { status: "ok" });
2893
+ return json4(200, { status: "ok" });
1528
2894
  }
1529
2895
  });
1530
2896
  var parsePayload = (message) => {
@@ -1587,6 +2953,7 @@ var operationMatcher = (document2) => {
1587
2953
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1588
2954
  };
1589
2955
  var createRuntime = (options) => {
2956
+ assertAdminUi(options.adminUi);
1590
2957
  const sqlite = bootSqlite(options.sqlite);
1591
2958
  const clock = options.clock ?? createClock();
1592
2959
  const rng = createRng(options.seed ?? 0);
@@ -1793,6 +3160,19 @@ var createRuntime = (options) => {
1793
3160
  else
1794
3161
  timeline(name);
1795
3162
  };
3163
+ const declarationsFor = (namespace) => {
3164
+ const declared = options.state;
3165
+ if (!declared)
3166
+ return [];
3167
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3168
+ };
3169
+ const stateScope = (namespace) => ({
3170
+ sqlite,
3171
+ namespace,
3172
+ storageNamespace: storageNamespace(namespace),
3173
+ root: instance(namespace),
3174
+ declarations: declarationsFor(namespace)
3175
+ });
1796
3176
  const runtime = {
1797
3177
  name: options.name,
1798
3178
  sqlite,
@@ -1831,6 +3211,7 @@ var createRuntime = (options) => {
1831
3211
  branch,
1832
3212
  checkout,
1833
3213
  timeline,
3214
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
1834
3215
  fetch: async (incoming) => {
1835
3216
  let request = incoming;
1836
3217
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -2024,11 +3405,20 @@ var createRuntime = (options) => {
2024
3405
  ...credentialRoutes(credentials),
2025
3406
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
2026
3407
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2027
- ...options.admin?.(runtime) ?? {}
3408
+ ...options.admin?.(runtime) ?? {},
3409
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3410
+ // beside these; it does not replace `/state` or `/ui`.
3411
+ ...stateAdminRoutes({
3412
+ open: stateScope,
3413
+ afterWrite: (namespace) => {
3414
+ checkpoint(namespace, "main");
3415
+ }
3416
+ }),
3417
+ ...adminUiRoutes(options.name, options.adminUi)
2028
3418
  },
2029
3419
  adminKey: options.adminKey
2030
3420
  });
2031
- return runtime;
3421
+ return defineMock(runtime);
2032
3422
  };
2033
3423
  var mutableResponse = (response) => {
2034
3424
  try {
@@ -2442,4 +3832,4 @@ export {
2442
3832
  accessKeyCredential,
2443
3833
  StepFunctionsAPI
2444
3834
  };
2445
- //# sourceMappingURL=chunk-G54USQHW.js.map
3835
+ //# sourceMappingURL=chunk-4S65JRDA.js.map