@crvouga/mockingbird-service-oauth 1.6.0 → 1.7.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;
@@ -916,6 +918,936 @@ var clearNamespace = (sqlite, namespace) => {
916
918
  });
917
919
  };
918
920
 
921
+ // ../core/dist/surface.js
922
+ var defineMock = (runtime) => runtime;
923
+ var STANDARD_ADMIN_ROUTES = [
924
+ "GET /",
925
+ "POST /reset",
926
+ "GET /namespaces",
927
+ "GET /clock",
928
+ "POST /clock",
929
+ "GET /faults",
930
+ "POST /faults",
931
+ "DELETE /faults",
932
+ "POST /snapshots",
933
+ "POST /snapshots/:id/restore",
934
+ "DELETE /snapshots/:id",
935
+ "GET /timeline",
936
+ "POST /checkpoints",
937
+ "POST /branches/:name",
938
+ "POST /branches/:name/checkout",
939
+ "GET /requests",
940
+ "DELETE /requests",
941
+ "GET /metrics",
942
+ "DELETE /metrics",
943
+ "GET /credentials",
944
+ "PUT /credentials",
945
+ "DELETE /credentials",
946
+ "GET /state",
947
+ "GET /state/:collection",
948
+ "GET /state/:collection/:id",
949
+ "POST /state/:collection",
950
+ "PUT /state/:collection/:id",
951
+ "PATCH /state/:collection/:id",
952
+ "DELETE /state/:collection/:id",
953
+ "GET /ui",
954
+ "GET /ui/",
955
+ "GET /ui/manifest"
956
+ ];
957
+ var PANEL_ID = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
958
+ var assertAdminUi = (ui) => {
959
+ if (!ui?.panels)
960
+ return;
961
+ const seen = /* @__PURE__ */ new Set();
962
+ for (const panel of ui.panels) {
963
+ if (!PANEL_ID.test(panel.id)) {
964
+ throw new RangeError(`admin panel id must match ${PANEL_ID}: ${JSON.stringify(panel.id)}`);
965
+ }
966
+ if (seen.has(panel.id))
967
+ throw new RangeError(`duplicate admin panel id ${panel.id}`);
968
+ seen.add(panel.id);
969
+ if (panel.title.trim() === "")
970
+ throw new RangeError(`admin panel ${panel.id} needs a title`);
971
+ }
972
+ };
973
+
974
+ // ../core/dist/admin-ui.js
975
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => {
976
+ switch (char) {
977
+ case "&":
978
+ return "&amp;";
979
+ case "<":
980
+ return "&lt;";
981
+ case ">":
982
+ return "&gt;";
983
+ case '"':
984
+ return "&quot;";
985
+ default:
986
+ return "&#39;";
987
+ }
988
+ });
989
+ var renderAdminDocument = (service) => {
990
+ const name = escapeHtml(service);
991
+ const standard = JSON.stringify(STANDARD_ADMIN_ROUTES);
992
+ return `<!DOCTYPE html>
993
+ <html lang="en">
994
+ <head>
995
+ <meta charset="utf-8">
996
+ <meta name="viewport" content="width=device-width, initial-scale=1">
997
+ <meta name="color-scheme" content="light dark">
998
+ <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">
999
+ <title>${name} admin</title>
1000
+ <style>
1001
+ :root {
1002
+ color-scheme: light;
1003
+ --bg: #f6f5f2;
1004
+ --bg-elev: #ffffff;
1005
+ --bg-muted: #eeece6;
1006
+ --bg-inset: #f3f1eb;
1007
+ --line: #e2dfd6;
1008
+ --line-strong: #d0ccc1;
1009
+ --ink: #1c1915;
1010
+ --muted: #5e584f;
1011
+ --faint: #8a8378;
1012
+ --accent: #3d4f3a;
1013
+ --accent-ink: #f7f6f2;
1014
+ --accent-soft: #e5ece2;
1015
+ --ok: #1f7a45;
1016
+ --ok-soft: #e5f4eb;
1017
+ --warn: #9a6700;
1018
+ --warn-soft: #fbf3df;
1019
+ --err: #a33b32;
1020
+ --err-soft: #fdecea;
1021
+ --shadow: 0 1px 2px rgb(28 25 21 / 0.05), 0 12px 32px rgb(28 25 21 / 0.06);
1022
+ --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1023
+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
1024
+ --radius: 14px;
1025
+ --header: 60px;
1026
+ --nav: 220px;
1027
+ }
1028
+ :root[data-theme="dark"] {
1029
+ color-scheme: dark;
1030
+ --bg: #141311;
1031
+ --bg-elev: #1e1c19;
1032
+ --bg-muted: #26231f;
1033
+ --bg-inset: #181715;
1034
+ --line: #34302b;
1035
+ --line-strong: #4a453d;
1036
+ --ink: #f4f1ea;
1037
+ --muted: #c4bdb1;
1038
+ --faint: #8f877c;
1039
+ --accent: #c5d5b8;
1040
+ --accent-ink: #1a2118;
1041
+ --accent-soft: #2a3328;
1042
+ --ok: #8fd6a8;
1043
+ --ok-soft: #1a2e22;
1044
+ --warn: #f0cc78;
1045
+ --warn-soft: #332911;
1046
+ --err: #f0a8a2;
1047
+ --err-soft: #3a201e;
1048
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1049
+ }
1050
+ @media (prefers-color-scheme: dark) {
1051
+ :root:not([data-theme="light"]) {
1052
+ color-scheme: dark;
1053
+ --bg: #141311;
1054
+ --bg-elev: #1e1c19;
1055
+ --bg-muted: #26231f;
1056
+ --bg-inset: #181715;
1057
+ --line: #34302b;
1058
+ --line-strong: #4a453d;
1059
+ --ink: #f4f1ea;
1060
+ --muted: #c4bdb1;
1061
+ --faint: #8f877c;
1062
+ --accent: #c5d5b8;
1063
+ --accent-ink: #1a2118;
1064
+ --accent-soft: #2a3328;
1065
+ --ok: #8fd6a8;
1066
+ --ok-soft: #1a2e22;
1067
+ --warn: #f0cc78;
1068
+ --warn-soft: #332911;
1069
+ --err: #f0a8a2;
1070
+ --err-soft: #3a201e;
1071
+ --shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 16px 40px rgb(0 0 0 / 0.28);
1072
+ }
1073
+ }
1074
+ * { box-sizing: border-box; }
1075
+ html, body { margin: 0; height: 100%; }
1076
+ body {
1077
+ font-family: var(--sans);
1078
+ background: var(--bg);
1079
+ color: var(--ink);
1080
+ line-height: 1.45;
1081
+ padding-left: env(safe-area-inset-left);
1082
+ padding-right: env(safe-area-inset-right);
1083
+ -webkit-text-size-adjust: 100%;
1084
+ }
1085
+ button, input, select, textarea { font: inherit; color: inherit; }
1086
+ button { cursor: pointer; }
1087
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
1088
+ @media (prefers-reduced-motion: reduce) {
1089
+ * { scroll-behavior: auto !important; transition: none !important; }
1090
+ }
1091
+ .app { min-height: 100%; display: flex; flex-direction: column; }
1092
+ header.top {
1093
+ position: sticky; top: 0; z-index: 5;
1094
+ display: flex; align-items: center; gap: 12px;
1095
+ min-height: var(--header); padding: 10px 16px;
1096
+ background: color-mix(in srgb, var(--bg-elev) 92%, transparent);
1097
+ border-bottom: 1px solid var(--line);
1098
+ backdrop-filter: blur(10px);
1099
+ }
1100
+ .brand { display: flex; flex-direction: column; min-width: 0; margin-right: auto; }
1101
+ .brand strong { font-size: 15px; letter-spacing: -0.01em; }
1102
+ .brand span { color: var(--faint); font-size: 12px; }
1103
+ .controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
1104
+ label.field { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--faint); }
1105
+ label.field input, label.field select, .controls input[type="password"] {
1106
+ background: var(--bg-inset); border: 1px solid var(--line); border-radius: 8px;
1107
+ padding: 7px 8px; min-height: 36px;
1108
+ }
1109
+ .icon-btn, .btn, .btn-primary, .btn-quiet, .btn-danger {
1110
+ border-radius: 9px; min-height: 36px; padding: 0 12px; border: 1px solid var(--line);
1111
+ background: var(--bg-elev);
1112
+ }
1113
+ .btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
1114
+ .btn-quiet { background: transparent; }
1115
+ .btn-danger { color: var(--err); }
1116
+ /* minmax(0, 1fr): a 1fr column will not shrink below its content, so a long
1117
+ record or the full nav row would widen the page past the viewport. */
1118
+ .layout {
1119
+ display: grid; grid-template-columns: var(--nav) minmax(0, 1fr);
1120
+ flex: 1; min-height: 0; min-width: 0;
1121
+ }
1122
+ nav.side {
1123
+ border-right: 1px solid var(--line); padding: 12px;
1124
+ display: flex; flex-direction: column; gap: 4px;
1125
+ background: var(--bg-elev);
1126
+ }
1127
+ nav.side button {
1128
+ text-align: left; border: 0; background: transparent; border-radius: 9px;
1129
+ padding: 9px 10px; min-height: 40px; color: var(--muted);
1130
+ }
1131
+ nav.side button[aria-current="true"] { background: var(--accent-soft); color: var(--ink); font-weight: 600; }
1132
+ main { padding: 20px; max-width: 1100px; width: 100%; min-width: 0; }
1133
+ .view h2 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.02em; }
1134
+ .lede { margin: 0 0 16px; color: var(--muted); }
1135
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
1136
+ .card {
1137
+ background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius);
1138
+ padding: 14px 16px; box-shadow: var(--shadow);
1139
+ }
1140
+ .card .k { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
1141
+ .card .v { display: flex; flex-direction: column; gap: 2px; font-size: 22px; margin-top: 4px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1142
+ .card .v .clock-time { font-size: 14px; color: var(--muted); }
1143
+ .split { display: grid; grid-template-columns: minmax(0, 240px) minmax(0, 1fr); gap: 16px; align-items: start; }
1144
+ .collection {
1145
+ width: 100%; text-align: left; border: 1px solid transparent; background: transparent;
1146
+ border-radius: 10px; padding: 8px 10px; min-height: 44px;
1147
+ }
1148
+ .collection[aria-current="true"] { background: var(--bg-elev); border-color: var(--line); }
1149
+ .collection small { display: block; color: var(--faint); }
1150
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 14px; }
1151
+ .chip {
1152
+ font-family: var(--mono); font-size: 12px; background: var(--bg-muted);
1153
+ border-radius: 999px; padding: 4px 8px;
1154
+ }
1155
+ .chip i { color: var(--faint); font-style: normal; }
1156
+ table { width: 100%; border-collapse: collapse; font-size: 14px; }
1157
+ th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
1158
+ th { color: var(--faint); font-weight: 600; font-size: 12px; }
1159
+ tr.clickable { cursor: pointer; }
1160
+ tr.clickable:hover { background: var(--bg-muted); }
1161
+ pre, code, .mono { font-family: var(--mono); overflow-wrap: anywhere; }
1162
+ pre {
1163
+ margin: 0; white-space: pre-wrap; word-break: break-word;
1164
+ background: var(--bg-inset); border-radius: 10px; padding: 12px; font-size: 12px;
1165
+ }
1166
+ .row-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
1167
+ .banner {
1168
+ display: none; margin-bottom: 12px; padding: 10px 12px; border-radius: 10px;
1169
+ background: var(--err-soft); color: var(--err);
1170
+ }
1171
+ .banner.show { display: block; }
1172
+ .empty { color: var(--muted); padding: 24px 8px; }
1173
+ dialog {
1174
+ border: 1px solid var(--line); border-radius: 16px; padding: 0; background: var(--bg-elev);
1175
+ color: var(--ink); width: min(640px, calc(100vw - 24px)); box-shadow: var(--shadow);
1176
+ }
1177
+ dialog::backdrop { background: rgb(20 19 17 / 0.45); }
1178
+ dialog form, .dialog-body { padding: 16px; display: flex; flex-direction: column; gap: 10px; }
1179
+ textarea {
1180
+ width: 100%; min-height: 180px; resize: vertical; border-radius: 10px;
1181
+ border: 1px solid var(--line); background: var(--bg-inset); padding: 10px;
1182
+ font-family: var(--mono); font-size: 12px;
1183
+ }
1184
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
1185
+ .badge { font-size: 11px; border-radius: 999px; padding: 2px 7px; background: var(--bg-muted); color: var(--muted); }
1186
+ .badge.ok { background: var(--ok-soft); color: var(--ok); }
1187
+ .badge.warn { background: var(--warn-soft); color: var(--warn); }
1188
+ .status-2 { color: var(--ok); }
1189
+ .status-4, .status-5, .status-0 { color: var(--err); }
1190
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1191
+ .route {
1192
+ display: grid; grid-template-columns: 88px 1fr auto; gap: 8px; align-items: center;
1193
+ padding: 8px 0; border-bottom: 1px solid var(--line);
1194
+ }
1195
+ .method { font-family: var(--mono); font-size: 12px; font-weight: 700; }
1196
+ @media (max-width: 800px) {
1197
+ header.top {
1198
+ align-items: stretch; flex-direction: column;
1199
+ padding-top: max(10px, env(safe-area-inset-top));
1200
+ }
1201
+ input, select, textarea { font-size: 16px; }
1202
+ .controls { width: 100%; }
1203
+ label.field, label.field select, label.field input { flex: 1; min-width: 0; }
1204
+ .layout { grid-template-columns: minmax(0, 1fr); }
1205
+ nav.side {
1206
+ flex-direction: row; align-items: center; overflow-x: auto; min-width: 0;
1207
+ border-right: 0; border-bottom: 1px solid var(--line);
1208
+ padding: 8px;
1209
+ }
1210
+ nav.side button { white-space: nowrap; flex: none; }
1211
+ .split { grid-template-columns: minmax(0, 1fr); }
1212
+ main { padding: 14px; }
1213
+ table, thead, tbody, tr, th, td { display: block; }
1214
+ thead { display: none; }
1215
+ tr {
1216
+ border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; padding: 6px;
1217
+ background: var(--bg-elev); min-width: 0;
1218
+ }
1219
+ td {
1220
+ border: 0; display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px;
1221
+ min-width: 0; overflow-wrap: anywhere;
1222
+ }
1223
+ td::before { content: attr(data-label); color: var(--faint); font-size: 12px; flex: none; }
1224
+ .route { grid-template-columns: 72px 1fr; }
1225
+ .route button { grid-column: 1 / -1; }
1226
+ }
1227
+ </style>
1228
+ </head>
1229
+ <body>
1230
+ <div class="app" data-service="${name}" data-mockingbird-admin>
1231
+ <header class="top">
1232
+ <div class="brand">
1233
+ <strong>${name}</strong>
1234
+ <span>Mockingbird admin</span>
1235
+ </div>
1236
+ <div class="controls">
1237
+ <label class="field">Namespace
1238
+ <select id="namespace" aria-label="Namespace"></select>
1239
+ </label>
1240
+ <label class="field">Admin key
1241
+ <input id="admin-key" type="password" autocomplete="off" spellcheck="false" aria-label="Admin key">
1242
+ </label>
1243
+ <button class="icon-btn" id="theme" type="button" aria-label="Toggle color theme">Theme</button>
1244
+ <button class="btn" id="refresh" type="button">Refresh</button>
1245
+ </div>
1246
+ </header>
1247
+ <div class="layout">
1248
+ <nav class="side" id="nav" aria-label="Admin sections">
1249
+ <button type="button" data-view="overview" aria-current="true">Overview</button>
1250
+ <button type="button" data-view="state">State</button>
1251
+ <button type="button" data-view="clock">Clock</button>
1252
+ <button type="button" data-view="faults">Faults</button>
1253
+ <button type="button" data-view="journal">Journal</button>
1254
+ <button type="button" data-view="routes">Routes</button>
1255
+ </nav>
1256
+ <main id="views">
1257
+ <p class="banner" id="banner" role="alert"></p>
1258
+ <section class="view" id="view-overview">
1259
+ <h2>Overview</h2>
1260
+ <p class="lede">Health, clock, and the collections this namespace is holding.</p>
1261
+ <div class="grid" id="overview-cards"></div>
1262
+ <h3>Recent requests</h3>
1263
+ <div id="overview-requests"></div>
1264
+ </section>
1265
+ <section class="view" id="view-state" hidden>
1266
+ <h2>State</h2>
1267
+ <p class="lede">Every collection in this namespace. Declared fields stay visible before any row exists; stored rows add whatever else they contain.</p>
1268
+ <div class="split">
1269
+ <div id="collections"></div>
1270
+ <div>
1271
+ <div id="schema"></div>
1272
+ <div class="row-actions">
1273
+ <button class="btn-primary" id="new-record" type="button">New record</button>
1274
+ </div>
1275
+ <div id="records"></div>
1276
+ </div>
1277
+ </div>
1278
+ </section>
1279
+ <section class="view" id="view-clock" hidden>
1280
+ <h2>Clock</h2>
1281
+ <p class="lede">The clock every timestamp in this mock reads.</p>
1282
+ <div class="card" id="clock-readout"></div>
1283
+ <div class="row-actions">
1284
+ <button class="btn" type="button" data-advance="60000">+1m</button>
1285
+ <button class="btn" type="button" data-advance="900000">+15m</button>
1286
+ <button class="btn" type="button" data-advance="3600000">+1h</button>
1287
+ <button class="btn" type="button" data-advance="86400000">+1d</button>
1288
+ <button class="btn" type="button" data-advance="-3600000">\u22121h</button>
1289
+ <button class="btn" id="freeze" type="button">Freeze</button>
1290
+ <button class="btn-quiet" id="clock-reset" type="button">Reset</button>
1291
+ </div>
1292
+ <form id="clock-set" class="row-actions">
1293
+ <label class="field">Set instant
1294
+ <input id="clock-instant" type="text" placeholder="2026-01-01T00:00:00Z or epoch ms" size="32">
1295
+ </label>
1296
+ <button class="btn-primary" type="submit">Set</button>
1297
+ </form>
1298
+ </section>
1299
+ <section class="view" id="view-faults" hidden>
1300
+ <h2>Faults</h2>
1301
+ <p class="lede">Inject a response, a delay, or a named preset. Rules apply to this namespace.</p>
1302
+ <form id="fault-form" class="card stack">
1303
+ <label class="field">Preset
1304
+ <select id="fault-preset"><option value="">Custom rule</option></select>
1305
+ </label>
1306
+ <label class="field">Status
1307
+ <input id="fault-status" inputmode="numeric" placeholder="503">
1308
+ </label>
1309
+ <label class="field">Path prefix
1310
+ <input id="fault-path" placeholder="/v1">
1311
+ </label>
1312
+ <label class="field">Method
1313
+ <input id="fault-method" placeholder="GET">
1314
+ </label>
1315
+ <div class="dialog-actions">
1316
+ <button class="btn-primary" type="submit">Add fault</button>
1317
+ <button class="btn-danger" id="fault-clear" type="button">Clear all</button>
1318
+ </div>
1319
+ </form>
1320
+ <div id="fault-list"></div>
1321
+ </section>
1322
+ <section class="view" id="view-journal" hidden>
1323
+ <h2>Journal</h2>
1324
+ <p class="lede">Requests this namespace has seen. Bodies are not stored.</p>
1325
+ <div class="row-actions">
1326
+ <button class="btn-danger" id="journal-clear" type="button">Clear journal</button>
1327
+ </div>
1328
+ <div id="journal"></div>
1329
+ </section>
1330
+ <section class="view" id="view-routes" hidden>
1331
+ <h2>Routes</h2>
1332
+ <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>
1333
+ <div id="route-list"></div>
1334
+ <form id="route-form" class="card stack">
1335
+ <strong id="route-title">Select a route</strong>
1336
+ <label class="field">JSON body
1337
+ <textarea id="route-body" placeholder="{ }"></textarea>
1338
+ </label>
1339
+ <div class="dialog-actions">
1340
+ <button class="btn-primary" type="submit">Send</button>
1341
+ </div>
1342
+ <pre id="route-result">Response will show here.</pre>
1343
+ </form>
1344
+ </section>
1345
+ </main>
1346
+ </div>
1347
+ </div>
1348
+ <dialog id="editor">
1349
+ <form method="dialog" id="editor-form">
1350
+ <strong id="editor-title">Record</strong>
1351
+ <label class="field">Id
1352
+ <input id="editor-id" required>
1353
+ </label>
1354
+ <label class="field">JSON value
1355
+ <textarea id="editor-value"></textarea>
1356
+ </label>
1357
+ <div class="dialog-actions">
1358
+ <button class="btn-danger" id="editor-delete" type="button" value="delete">Delete</button>
1359
+ <button class="btn-quiet" type="submit" value="cancel">Cancel</button>
1360
+ <button class="btn-primary" type="submit" value="save">Save</button>
1361
+ </div>
1362
+ </form>
1363
+ </dialog>
1364
+ <script>
1365
+ (() => {
1366
+ const STANDARD = new Set(${standard})
1367
+ const state = {
1368
+ namespace: "default",
1369
+ key: sessionStorage.getItem("mockingbird-admin-key") || "",
1370
+ view: "overview",
1371
+ collection: "",
1372
+ shape: null,
1373
+ route: null,
1374
+ editing: null
1375
+ }
1376
+ const $ = (id) => document.getElementById(id)
1377
+ const banner = $("banner")
1378
+ const keyInput = $("admin-key")
1379
+ keyInput.value = state.key
1380
+ const params = new URLSearchParams(location.search)
1381
+ if (params.get("key")) {
1382
+ state.key = params.get("key")
1383
+ keyInput.value = state.key
1384
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1385
+ params.delete("key")
1386
+ const next = params.toString()
1387
+ history.replaceState(null, "", location.pathname + (next ? "?" + next : ""))
1388
+ }
1389
+ if (params.get("namespace")) state.namespace = params.get("namespace")
1390
+
1391
+ const showError = (error) => {
1392
+ banner.textContent = error instanceof Error ? error.message : String(error)
1393
+ banner.classList.add("show")
1394
+ }
1395
+ const clearError = () => banner.classList.remove("show")
1396
+
1397
+ async function originGet(path) {
1398
+ const response = await fetch(path, { headers: { accept: "application/json" } })
1399
+ if (!response.ok) throw new Error(response.status + " " + path)
1400
+ return response.json()
1401
+ }
1402
+ async function api(method, path, body) {
1403
+ const headers = { accept: "application/json" }
1404
+ if (state.key) headers["${ADMIN_KEY_HEADER}"] = state.key
1405
+ if (state.namespace) headers["x-mockingbird-namespace"] = state.namespace
1406
+ if (body !== undefined) headers["content-type"] = "application/json"
1407
+ const response = await fetch("${ADMIN_PREFIX}" + path, {
1408
+ method,
1409
+ headers,
1410
+ body: body === undefined ? undefined : JSON.stringify(body)
1411
+ })
1412
+ const text = await response.text()
1413
+ let data = null
1414
+ if (text) {
1415
+ try { data = JSON.parse(text) } catch { data = { raw: text } }
1416
+ }
1417
+ if (response.status === 401) {
1418
+ keyInput.focus()
1419
+ throw new Error((data && data.error && data.error.message) || "Admin key required")
1420
+ }
1421
+ if (!response.ok) {
1422
+ throw new Error((data && data.error && data.error.message) || (response.status + " " + method + " " + path))
1423
+ }
1424
+ return data
1425
+ }
1426
+ const panelApi = {
1427
+ get: (path) => api("GET", path),
1428
+ send: (method, path, body) => api(method, path, body),
1429
+ namespace: () => state.namespace
1430
+ }
1431
+
1432
+ function setTheme(theme) {
1433
+ if (theme) document.documentElement.dataset.theme = theme
1434
+ else delete document.documentElement.dataset.theme
1435
+ }
1436
+ const storedTheme = localStorage.getItem("mockingbird-admin-theme")
1437
+ if (storedTheme) setTheme(storedTheme)
1438
+ $("theme").addEventListener("click", () => {
1439
+ const current = document.documentElement.dataset.theme
1440
+ const dark = current ? current === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
1441
+ const next = dark ? "light" : "dark"
1442
+ localStorage.setItem("mockingbird-admin-theme", next)
1443
+ setTheme(next)
1444
+ })
1445
+
1446
+ function show(view) {
1447
+ state.view = view
1448
+ for (const button of document.querySelectorAll("#nav button")) {
1449
+ button.setAttribute("aria-current", button.dataset.view === view ? "true" : "false")
1450
+ }
1451
+ for (const section of document.querySelectorAll("main .view")) {
1452
+ section.hidden = section.id !== "view-" + view
1453
+ }
1454
+ }
1455
+ document.getElementById("nav").addEventListener("click", (event) => {
1456
+ const button = event.target.closest("button[data-view]")
1457
+ if (!button) return
1458
+ show(button.dataset.view)
1459
+ refresh().catch(showError)
1460
+ })
1461
+
1462
+ function cards(items) {
1463
+ return '<div class="grid">' + items.map((item) =>
1464
+ '<article class="card"><div class="k">' + item.k + '</div><div class="v">' + item.v + '</div></article>'
1465
+ ).join("") + "</div>"
1466
+ }
1467
+ function table(columns, rows) {
1468
+ if (rows.length === 0) return '<p class="empty">Nothing here yet.</p>'
1469
+ const head = "<tr>" + columns.map((column) => "<th>" + column.label + "</th>").join("") + "</tr>"
1470
+ const body = rows.map((row) => "<tr" + (row.attrs || "") + ">" + columns.map((column) =>
1471
+ '<td data-label="' + column.label + '">' + column.cell(row) + "</td>"
1472
+ ).join("") + "</tr>").join("")
1473
+ return "<table><thead>" + head + "</thead><tbody>" + body + "</tbody></table>"
1474
+ }
1475
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
1476
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
1477
+ }[char]))
1478
+ const preview = (value) => {
1479
+ const text = JSON.stringify(value)
1480
+ return esc(text.length > 180 ? text.slice(0, 180) + "\u2026" : text)
1481
+ }
1482
+ const when = (epoch) => {
1483
+ const date = new Date(epoch)
1484
+ return Number.isNaN(date.getTime()) ? String(epoch) : date.toISOString()
1485
+ }
1486
+ const clockCard = (epoch) => {
1487
+ const date = new Date(epoch)
1488
+ if (Number.isNaN(date.getTime())) return esc(String(epoch))
1489
+ const iso = date.toISOString()
1490
+ return esc(iso.slice(0, 10)) + '<span class="clock-time">' + esc(iso.slice(11, 19)) + " UTC</span>"
1491
+ }
1492
+
1493
+ async function loadNamespaces() {
1494
+ const data = await api("GET", "/namespaces")
1495
+ const select = $("namespace")
1496
+ const names = data.namespaces && data.namespaces.length ? data.namespaces : [data.default || "default"]
1497
+ if (!names.includes(state.namespace)) names.unshift(state.namespace)
1498
+ select.innerHTML = names.map((name) =>
1499
+ '<option value="' + esc(name) + '">' + esc(name) + "</option>"
1500
+ ).join("")
1501
+ select.value = state.namespace
1502
+ }
1503
+
1504
+ async function renderOverview() {
1505
+ const [health, shape, clock, journal] = await Promise.all([
1506
+ originGet("/health"),
1507
+ api("GET", "/state"),
1508
+ api("GET", "/clock"),
1509
+ api("GET", "/requests?limit=8")
1510
+ ])
1511
+ state.shape = shape
1512
+ $("overview-cards").innerHTML = cards([
1513
+ { k: "Service", v: esc(health.service || "${name}") },
1514
+ { k: "Status", v: esc(health.status || "ok") },
1515
+ { k: "Namespace", v: esc(state.namespace) },
1516
+ { k: "Collections", v: String(shape.collections.length) },
1517
+ { k: "Records", v: String(shape.collections.reduce((sum, item) => sum + item.count, 0)) },
1518
+ { k: "Clock", v: clockCard(clock.now) }
1519
+ ])
1520
+ const requests = (journal && journal.requests) || []
1521
+ $("overview-requests").innerHTML = table(
1522
+ [
1523
+ { label: "Method", cell: (row) => esc(row.method) },
1524
+ { label: "Path", cell: (row) => esc(row.path) },
1525
+ { label: "Status", cell: (row) => '<span class="status-' + String(row.status).charAt(0) + '">' + esc(row.status) + "</span>" },
1526
+ { label: "Operation", cell: (row) => esc(row.operationId || "") }
1527
+ ],
1528
+ requests
1529
+ )
1530
+ }
1531
+
1532
+ function schemaChips(collection) {
1533
+ if (!collection || collection.fields.length === 0) {
1534
+ return '<p class="empty">No fields yet. Add a record or declare the collection on the service.</p>'
1535
+ }
1536
+ return '<div class="chips">' + collection.fields.map((field) =>
1537
+ '<span class="chip">' + esc(field.name) + ' <i>' + esc(field.kind) + (field.optional ? "?" : "") + "</i></span>"
1538
+ ).join("") + "</div>"
1539
+ }
1540
+
1541
+ async function renderState() {
1542
+ const shape = await api("GET", "/state")
1543
+ state.shape = shape
1544
+ const host = $("collections")
1545
+ if (shape.collections.length === 0) {
1546
+ host.innerHTML = '<p class="empty">This namespace has no collections yet.</p>'
1547
+ $("schema").innerHTML = ""
1548
+ $("records").innerHTML = ""
1549
+ return
1550
+ }
1551
+ if (!shape.collections.some((item) => item.name === state.collection)) {
1552
+ state.collection = shape.collections[0].name
1553
+ }
1554
+ host.innerHTML = shape.collections.map((item) =>
1555
+ '<button type="button" class="collection" data-collection="' + esc(item.name) + '" aria-current="' +
1556
+ (item.name === state.collection ? "true" : "false") + '"><strong>' + esc(item.label) +
1557
+ '</strong><small>' + esc(item.count) + " \xB7 " + esc(item.source) + "</small></button>"
1558
+ ).join("")
1559
+ const selected = shape.collections.find((item) => item.name === state.collection)
1560
+ $("schema").innerHTML = "<h3>" + esc(selected.label) + "</h3>" +
1561
+ (selected.description ? "<p class=" + '"lede">' + esc(selected.description) + "</p>" : "") +
1562
+ schemaChips(selected)
1563
+ const page = await api("GET", "/state/" + encodeURIComponent(state.collection) + "?limit=50")
1564
+ const rows = page.records.map((record) => ({
1565
+ ...record,
1566
+ attrs: ' class="clickable" data-id="' + esc(record.id) + '"'
1567
+ }))
1568
+ $("records").innerHTML = table(
1569
+ [
1570
+ { label: "Id", cell: (row) => "<code>" + esc(row.id) + "</code>" },
1571
+ { label: "Seq", cell: (row) => esc(row.seq) },
1572
+ { label: "Value", cell: (row) => preview(row.value) }
1573
+ ],
1574
+ rows
1575
+ )
1576
+ }
1577
+
1578
+ async function renderClock() {
1579
+ const clock = await api("GET", "/clock")
1580
+ $("clock-readout").innerHTML = "<div class='k'>Now</div><div class='v'>" + esc(when(clock.now)) +
1581
+ "</div><p>" + esc(clock.now) + " ms \xB7 offset " + esc(clock.offsetMs) + " ms " +
1582
+ (clock.frozen ? "<span class='badge warn'>frozen</span>" : "<span class='badge ok'>live</span>") + "</p>"
1583
+ $("freeze").textContent = clock.frozen ? "Unfreeze" : "Freeze"
1584
+ $("freeze").dataset.frozen = clock.frozen ? "1" : "0"
1585
+ }
1586
+
1587
+ async function renderFaults() {
1588
+ const [faults, presets] = await Promise.all([
1589
+ api("GET", "/faults"),
1590
+ api("GET", "/faults/presets").catch(() => ({ presets: [] }))
1591
+ ])
1592
+ const select = $("fault-preset")
1593
+ const current = select.value
1594
+ const list = presets.presets || []
1595
+ select.innerHTML = '<option value="">Custom rule</option>' + list.map((preset) =>
1596
+ '<option value="' + esc(preset.name) + '">' + esc(preset.name) + "</option>"
1597
+ ).join("")
1598
+ select.value = current
1599
+ const rules = faults.faults || []
1600
+ $("fault-list").innerHTML = table(
1601
+ [
1602
+ { label: "Id", cell: (row) => esc(row.id) },
1603
+ { label: "Match", cell: (row) => esc([row.method, row.pathPrefix, row.operationId].filter(Boolean).join(" ") || "all") },
1604
+ { label: "Effect", cell: (row) => esc(row.status ?? row.effect ?? (row.drop ? "drop" : row.latencyMs || "")) }
1605
+ ],
1606
+ rules
1607
+ )
1608
+ }
1609
+
1610
+ async function renderJournal() {
1611
+ const journal = await api("GET", "/requests?limit=100")
1612
+ $("journal").innerHTML = table(
1613
+ [
1614
+ { label: "When", cell: (row) => esc(row.at || "") },
1615
+ { label: "Method", cell: (row) => esc(row.method) },
1616
+ { label: "Path", cell: (row) => esc(row.path) },
1617
+ { label: "Status", cell: (row) => esc(row.status) },
1618
+ { label: "ms", cell: (row) => esc(row.durationMs) }
1619
+ ],
1620
+ journal.requests || []
1621
+ )
1622
+ }
1623
+
1624
+ async function renderRoutes() {
1625
+ const data = await api("GET", "/")
1626
+ const routes = data.routes || []
1627
+ $("route-list").innerHTML = routes.map((route) => {
1628
+ const extra = STANDARD.has(route) ? "" : " <span class='badge'>extension</span>"
1629
+ return '<div class="route"><span class="method">' + esc(route.split(" ")[0]) +
1630
+ '</span><span>' + esc(route.split(" ").slice(1).join(" ")) + extra +
1631
+ '</span><button class="btn" type="button" data-route="' + esc(route) + '">Use</button></div>'
1632
+ }).join("")
1633
+ }
1634
+
1635
+ const renderers = {
1636
+ overview: renderOverview,
1637
+ state: renderState,
1638
+ clock: renderClock,
1639
+ faults: renderFaults,
1640
+ journal: renderJournal,
1641
+ routes: renderRoutes
1642
+ }
1643
+
1644
+ async function refresh() {
1645
+ clearError()
1646
+ if (state.view in renderers) await renderers[state.view]()
1647
+ }
1648
+
1649
+ $("namespace").addEventListener("change", () => {
1650
+ state.namespace = $("namespace").value
1651
+ refresh().catch(showError)
1652
+ })
1653
+ keyInput.addEventListener("change", () => {
1654
+ state.key = keyInput.value.trim()
1655
+ sessionStorage.setItem("mockingbird-admin-key", state.key)
1656
+ refresh().catch(showError)
1657
+ })
1658
+ $("refresh").addEventListener("click", () => refresh().catch(showError))
1659
+
1660
+ $("collections").addEventListener("click", (event) => {
1661
+ const button = event.target.closest("[data-collection]")
1662
+ if (!button) return
1663
+ state.collection = button.dataset.collection
1664
+ renderState().catch(showError)
1665
+ })
1666
+ $("records").addEventListener("click", (event) => {
1667
+ const row = event.target.closest("[data-id]")
1668
+ if (!row) return
1669
+ openEditor(row.dataset.id).catch(showError)
1670
+ })
1671
+
1672
+ const editor = $("editor")
1673
+ async function openEditor(id) {
1674
+ state.editing = id || null
1675
+ $("editor-title").textContent = id ? "Edit record" : "New record"
1676
+ $("editor-id").value = id || ""
1677
+ $("editor-id").readOnly = Boolean(id)
1678
+ $("editor-delete").hidden = !id
1679
+ if (id) {
1680
+ const record = await api("GET", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1681
+ $("editor-value").value = JSON.stringify(record.value, null, 2)
1682
+ } else {
1683
+ $("editor-value").value = "{\\n \\n}"
1684
+ }
1685
+ editor.showModal()
1686
+ }
1687
+ $("new-record").addEventListener("click", () => openEditor(null).catch(showError))
1688
+ $("editor-form").addEventListener("submit", (event) => {
1689
+ const submitter = event.submitter
1690
+ if (!submitter || submitter.value !== "save") return
1691
+ event.preventDefault()
1692
+ let value
1693
+ try { value = JSON.parse($("editor-value").value) }
1694
+ catch { showError(new Error("Value is not JSON")); return }
1695
+ const id = $("editor-id").value.trim()
1696
+ const path = "/state/" + encodeURIComponent(state.collection)
1697
+ const request = state.editing
1698
+ ? api("PUT", path + "/" + encodeURIComponent(id), { value })
1699
+ : api("POST", path, { id: id || undefined, value })
1700
+ request.then(() => { editor.close(); return renderState() }).catch(showError)
1701
+ })
1702
+ $("editor-delete").addEventListener("click", () => {
1703
+ const id = state.editing
1704
+ if (!id) return
1705
+ api("DELETE", "/state/" + encodeURIComponent(state.collection) + "/" + encodeURIComponent(id))
1706
+ .then(() => { editor.close(); return renderState() })
1707
+ .catch(showError)
1708
+ })
1709
+
1710
+ document.querySelectorAll("[data-advance]").forEach((button) => {
1711
+ button.addEventListener("click", () => {
1712
+ api("POST", "/clock", { advance: Number(button.dataset.advance) }).then(renderClock).catch(showError)
1713
+ })
1714
+ })
1715
+ $("freeze").addEventListener("click", () => {
1716
+ const frozen = $("freeze").dataset.frozen === "1"
1717
+ api("POST", "/clock", { freeze: !frozen }).then(renderClock).catch(showError)
1718
+ })
1719
+ $("clock-reset").addEventListener("click", () => {
1720
+ api("POST", "/clock", { reset: true }).then(renderClock).catch(showError)
1721
+ })
1722
+ $("clock-set").addEventListener("submit", (event) => {
1723
+ event.preventDefault()
1724
+ const raw = $("clock-instant").value.trim()
1725
+ const set = /^-?\\d+$/.test(raw) ? Number(raw) : raw
1726
+ api("POST", "/clock", { set }).then(renderClock).catch(showError)
1727
+ })
1728
+
1729
+ $("fault-form").addEventListener("submit", (event) => {
1730
+ event.preventDefault()
1731
+ const preset = $("fault-preset").value
1732
+ const body = preset
1733
+ ? { preset }
1734
+ : {
1735
+ status: Number($("fault-status").value),
1736
+ ...($("fault-path").value ? { pathPrefix: $("fault-path").value } : {}),
1737
+ ...($("fault-method").value ? { method: $("fault-method").value } : {})
1738
+ }
1739
+ if (!preset && !Number.isFinite(body.status)) {
1740
+ showError(new Error("Status must be a number, or choose a preset"))
1741
+ return
1742
+ }
1743
+ api("POST", "/faults", body).then(renderFaults).catch(showError)
1744
+ })
1745
+ $("fault-clear").addEventListener("click", () => api("DELETE", "/faults").then(renderFaults).catch(showError))
1746
+ $("journal-clear").addEventListener("click", () => api("DELETE", "/requests").then(renderJournal).catch(showError))
1747
+
1748
+ $("route-list").addEventListener("click", (event) => {
1749
+ const button = event.target.closest("[data-route]")
1750
+ if (!button) return
1751
+ state.route = button.dataset.route
1752
+ $("route-title").textContent = state.route
1753
+ const method = state.route.split(" ")[0]
1754
+ $("route-body").disabled = method === "GET" || method === "DELETE"
1755
+ })
1756
+ $("route-form").addEventListener("submit", async (event) => {
1757
+ event.preventDefault()
1758
+ if (!state.route) return showError(new Error("Choose a route first"))
1759
+ const [method, path] = [state.route.split(" ")[0], state.route.split(" ").slice(1).join(" ")]
1760
+ const concrete = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => prompt("Value for " + key) || "")
1761
+ let body
1762
+ if (method !== "GET" && method !== "DELETE" && $("route-body").value.trim()) {
1763
+ try { body = JSON.parse($("route-body").value) }
1764
+ catch { return showError(new Error("Body is not JSON")) }
1765
+ }
1766
+ try {
1767
+ const data = await api(method, concrete, body)
1768
+ $("route-result").textContent = JSON.stringify(data, null, 2)
1769
+ } catch (error) {
1770
+ showError(error)
1771
+ }
1772
+ })
1773
+
1774
+ function mountPanels(panels) {
1775
+ const nav = $("nav")
1776
+ const views = $("views")
1777
+ for (const panel of panels) {
1778
+ const button = document.createElement("button")
1779
+ button.type = "button"
1780
+ button.dataset.view = panel.id
1781
+ button.textContent = panel.title
1782
+ nav.append(button)
1783
+ const section = document.createElement("section")
1784
+ section.className = "view"
1785
+ section.id = "view-" + panel.id
1786
+ section.hidden = true
1787
+ const title = document.createElement("h2")
1788
+ title.textContent = panel.title
1789
+ const lede = document.createElement("p")
1790
+ lede.className = "lede"
1791
+ lede.textContent = panel.description || ""
1792
+ const body = document.createElement("div")
1793
+ body.className = "panel-body"
1794
+ body.id = "panel-" + panel.id
1795
+ body.innerHTML = panel.html || ""
1796
+ section.append(title, lede, body)
1797
+ views.append(section)
1798
+ if (panel.script) {
1799
+ try {
1800
+ const run = new Function("root", "api", panel.script)
1801
+ run(body, panelApi)
1802
+ } catch (error) {
1803
+ const note = document.createElement("p")
1804
+ note.className = "banner show"
1805
+ note.textContent = error instanceof Error ? error.message : String(error)
1806
+ body.append(note)
1807
+ }
1808
+ }
1809
+ }
1810
+ }
1811
+
1812
+ loadNamespaces()
1813
+ .then(() => api("GET", "/ui/manifest"))
1814
+ .then((manifest) => { mountPanels((manifest && manifest.panels) || []); return refresh() })
1815
+ .catch(showError)
1816
+ })()
1817
+ </script>
1818
+ </body>
1819
+ </html>`;
1820
+ };
1821
+ var htmlResponse = (body) => new Response(body, {
1822
+ status: 200,
1823
+ headers: {
1824
+ "content-type": "text/html; charset=utf-8",
1825
+ "cache-control": "no-store"
1826
+ }
1827
+ });
1828
+ var json2 = (body) => new Response(JSON.stringify(body), {
1829
+ status: 200,
1830
+ headers: { "content-type": "application/json; charset=utf-8" }
1831
+ });
1832
+ var adminUiRoutes = (service, ui) => {
1833
+ const shell = () => renderAdminDocument(service);
1834
+ const document2 = () => ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
1835
+ return {
1836
+ "GET /ui": () => htmlResponse(document2()),
1837
+ "GET /ui/": () => htmlResponse(document2()),
1838
+ "GET /ui/manifest": () => json2({
1839
+ service,
1840
+ panels: (ui?.panels ?? []).map((panel) => ({
1841
+ id: panel.id,
1842
+ title: panel.title,
1843
+ ...panel.description !== void 0 ? { description: panel.description } : {},
1844
+ html: panel.html,
1845
+ ...panel.script !== void 0 ? { script: panel.script } : {}
1846
+ }))
1847
+ })
1848
+ };
1849
+ };
1850
+
919
1851
  // ../../../node_modules/.bun/hono@4.11.9/node_modules/hono/dist/request/constants.js
920
1852
  var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
921
1853
 
@@ -1383,15 +2315,449 @@ var restoreNamespace = (sqlite, namespace, snapshot) => {
1383
2315
  });
1384
2316
  };
1385
2317
 
2318
+ // ../core/dist/state-view.js
2319
+ var COLLECTION_NAME = /^[A-Za-z0-9_.@:-]{1,200}$/;
2320
+ var RECORD_ID = /^[^\s/]{1,256}$/;
2321
+ var SAMPLE = 25;
2322
+ var WALK_LIMIT = 1e4;
2323
+ var SKIP_CTORS = /* @__PURE__ */ new Set(["Hono", "HonoRequest", "Router"]);
2324
+ var fail = (status, message) => ({ ok: false, status, message });
2325
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2326
+ var kindOf = (value) => {
2327
+ if (value === null)
2328
+ return "null";
2329
+ if (Array.isArray(value))
2330
+ return "array";
2331
+ switch (typeof value) {
2332
+ case "string":
2333
+ return "string";
2334
+ case "number":
2335
+ return Number.isFinite(value) ? "number" : "unknown";
2336
+ case "boolean":
2337
+ return "boolean";
2338
+ case "object":
2339
+ return "object";
2340
+ default:
2341
+ return "unknown";
2342
+ }
2343
+ };
2344
+ var humanize = (name) => {
2345
+ const words = name.replace(/[@:_-]+/g, " ").trim();
2346
+ if (words === "")
2347
+ return name;
2348
+ return words.charAt(0).toUpperCase() + words.slice(1);
2349
+ };
2350
+ var jsonValue = (value) => {
2351
+ if (value === void 0)
2352
+ return fail(400, "value is required");
2353
+ try {
2354
+ return { ok: true, value: JSON.parse(JSON.stringify(value)) };
2355
+ } catch {
2356
+ return fail(400, "value must be JSON");
2357
+ }
2358
+ };
2359
+ var ctorName = (value) => {
2360
+ const ctor = value.constructor;
2361
+ return typeof ctor?.name === "string" ? ctor.name : "";
2362
+ };
2363
+ var isSqlite = (value) => "prepare" in value && typeof value.prepare === "function" && "transaction" in value;
2364
+ var discoverCollections = (root) => {
2365
+ const found = [];
2366
+ const seen = /* @__PURE__ */ new Set();
2367
+ const visit = (value, depth) => {
2368
+ if (found.length + seen.size > WALK_LIMIT)
2369
+ return;
2370
+ if (value === null || typeof value !== "object")
2371
+ return;
2372
+ if (seen.has(value))
2373
+ return;
2374
+ seen.add(value);
2375
+ if (value instanceof Collection) {
2376
+ found.push(value);
2377
+ return;
2378
+ }
2379
+ if (value instanceof Map) {
2380
+ for (const child of value.values())
2381
+ visit(child, depth + 1);
2382
+ return;
2383
+ }
2384
+ if (value instanceof Set) {
2385
+ for (const child of value.values())
2386
+ visit(child, depth + 1);
2387
+ return;
2388
+ }
2389
+ if (depth > 6 || isSqlite(value) || SKIP_CTORS.has(ctorName(value)))
2390
+ return;
2391
+ if (Array.isArray(value)) {
2392
+ const cap = Math.min(value.length, 32);
2393
+ for (let i = 0; i < cap; i++)
2394
+ visit(value[i], depth + 1);
2395
+ return;
2396
+ }
2397
+ let children;
2398
+ try {
2399
+ children = Object.values(value);
2400
+ } catch {
2401
+ return;
2402
+ }
2403
+ for (const child of children)
2404
+ visit(child, depth + 1);
2405
+ };
2406
+ visit(root, 0);
2407
+ return found;
2408
+ };
2409
+ var storedNames = (sqlite, namespace) => {
2410
+ const records = sqlite.prepare("SELECT DISTINCT collection AS name FROM mockingbird_records WHERE namespace = ?").all(namespace);
2411
+ const sequences = sqlite.prepare("SELECT DISTINCT name FROM mockingbird_sequences WHERE namespace = ? AND kind = 'collection'").all(namespace);
2412
+ return [...records, ...sequences].map((row) => row.name);
2413
+ };
2414
+ var blankAccum = (name) => ({
2415
+ name,
2416
+ kinds: /* @__PURE__ */ new Set(),
2417
+ present: 0,
2418
+ nested: /* @__PURE__ */ new Map()
2419
+ });
2420
+ var absorb = (accum, value) => {
2421
+ const kind = kindOf(value);
2422
+ accum.kinds.add(kind);
2423
+ accum.present++;
2424
+ if (!isRecord2(value))
2425
+ return;
2426
+ for (const [key, child] of Object.entries(value)) {
2427
+ const nested = accum.nested.get(key) ?? blankAccum(key);
2428
+ absorb(nested, child);
2429
+ accum.nested.set(key, nested);
2430
+ }
2431
+ };
2432
+ var finishField = (accum, samples) => {
2433
+ const kinds = [...accum.kinds];
2434
+ const kind = kinds.length === 1 ? kinds[0] : "unknown";
2435
+ const field = {
2436
+ name: accum.name,
2437
+ kind,
2438
+ optional: accum.present < samples || kinds.includes("null")
2439
+ };
2440
+ if (accum.nested.size > 0) {
2441
+ field.fields = [...accum.nested.values()].sort((a, b) => a.name.localeCompare(b.name)).map((child) => finishField(child, accum.present));
2442
+ }
2443
+ return field;
2444
+ };
2445
+ var inferFields = (records) => {
2446
+ if (records.length === 0)
2447
+ return [];
2448
+ const sample = records.slice(0, SAMPLE);
2449
+ const objects = sample.filter((record) => isRecord2(record.value));
2450
+ if (objects.length === 0) {
2451
+ const kinds = new Set(sample.map((record) => kindOf(record.value)));
2452
+ const list = [...kinds];
2453
+ return [
2454
+ {
2455
+ name: "(value)",
2456
+ kind: list.length === 1 ? list[0] : "unknown",
2457
+ optional: false
2458
+ }
2459
+ ];
2460
+ }
2461
+ const root = /* @__PURE__ */ new Map();
2462
+ for (const record of objects) {
2463
+ for (const [key, value] of Object.entries(record.value)) {
2464
+ const accum = root.get(key) ?? blankAccum(key);
2465
+ absorb(accum, value);
2466
+ root.set(key, accum);
2467
+ }
2468
+ }
2469
+ return [...root.values()].sort((a, b) => a.name.localeCompare(b.name)).map((accum) => finishField(accum, objects.length));
2470
+ };
2471
+ var mergeFields = (declared, inferred) => {
2472
+ const byName = /* @__PURE__ */ new Map();
2473
+ for (const field of inferred)
2474
+ byName.set(field.name, field);
2475
+ const ordered = [];
2476
+ const seen = /* @__PURE__ */ new Set();
2477
+ for (const field of declared ?? []) {
2478
+ const found = byName.get(field.name);
2479
+ seen.add(field.name);
2480
+ if (!found) {
2481
+ ordered.push({ ...field, optional: field.optional });
2482
+ continue;
2483
+ }
2484
+ ordered.push({
2485
+ ...found,
2486
+ kind: field.kind === "unknown" ? found.kind : field.kind,
2487
+ optional: field.optional || found.optional,
2488
+ ...field.description !== void 0 ? { description: field.description } : {},
2489
+ ...field.meta !== void 0 ? { meta: field.meta } : {},
2490
+ ...field.fields !== void 0 ? { fields: mergeFields(field.fields, found.fields ?? []) } : {}
2491
+ });
2492
+ }
2493
+ for (const field of inferred) {
2494
+ if (!seen.has(field.name))
2495
+ ordered.push(field);
2496
+ }
2497
+ return ordered;
2498
+ };
2499
+ var collectionOf = (sqlite, namespace, name) => new Collection(sqlite, namespace, name);
2500
+ var readRecord = (collection, id) => {
2501
+ const rows = collection.list({ where: (_value, _seq) => true, order: "oldest" });
2502
+ const row = rows.find((entry) => entry.id === id);
2503
+ return row ? { id: row.id, seq: row.seq, value: row.value } : void 0;
2504
+ };
2505
+ var inspectState = (scope) => {
2506
+ const declared = /* @__PURE__ */ new Map();
2507
+ for (const declaration of scope.declarations ?? []) {
2508
+ if (COLLECTION_NAME.test(declaration.name))
2509
+ declared.set(declaration.name, declaration);
2510
+ }
2511
+ const names = new Set(declared.keys());
2512
+ for (const name of storedNames(scope.sqlite, scope.storageNamespace))
2513
+ names.add(name);
2514
+ for (const collection of discoverCollections(scope.root)) {
2515
+ if (collection.namespace === scope.storageNamespace)
2516
+ names.add(collection.collectionName);
2517
+ }
2518
+ const collections = [];
2519
+ for (const name of names) {
2520
+ if (!COLLECTION_NAME.test(name))
2521
+ continue;
2522
+ const declaration = declared.get(name);
2523
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2524
+ const records = collection.list({ order: "newest" }).slice(0, SAMPLE).map((row) => ({ id: row.id, seq: row.seq, value: row.value }));
2525
+ const inferred = inferFields(records);
2526
+ const fields = mergeFields(declaration?.fields, inferred);
2527
+ const source = declaration && records.length > 0 ? "mixed" : declaration ? "declared" : "inferred";
2528
+ collections.push({
2529
+ name,
2530
+ label: declaration?.label ?? humanize(name),
2531
+ ...declaration?.description !== void 0 ? { description: declaration.description } : {},
2532
+ count: collection.count(),
2533
+ source,
2534
+ fields,
2535
+ ...declaration?.meta !== void 0 ? { meta: declaration.meta } : {}
2536
+ });
2537
+ }
2538
+ const order = /* @__PURE__ */ new Map();
2539
+ for (const [index, item] of (scope.declarations ?? []).entries())
2540
+ order.set(item.name, index);
2541
+ collections.sort((a, b) => {
2542
+ const left = order.get(a.name);
2543
+ const right = order.get(b.name);
2544
+ if (left !== void 0 && right !== void 0)
2545
+ return left - right;
2546
+ if (left !== void 0)
2547
+ return -1;
2548
+ if (right !== void 0)
2549
+ return 1;
2550
+ return a.name.localeCompare(b.name);
2551
+ });
2552
+ return {
2553
+ namespace: scope.namespace,
2554
+ storageNamespace: scope.storageNamespace,
2555
+ collections
2556
+ };
2557
+ };
2558
+ var pageOf = (sqlite, storageNamespace, name, query) => {
2559
+ if (!COLLECTION_NAME.test(name))
2560
+ return fail(400, "collection name is not allowed");
2561
+ const limit = query.limit ?? 50;
2562
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
2563
+ return fail(400, "limit must be an integer from 1 to 200");
2564
+ }
2565
+ const order = query.order ?? "newest";
2566
+ if (order !== "newest" && order !== "oldest")
2567
+ return fail(400, 'order must be "newest" or "oldest"');
2568
+ const collection = collectionOf(sqlite, storageNamespace, name);
2569
+ const rows = collection.list({ order }).filter((row) => {
2570
+ if (query.after === void 0)
2571
+ return true;
2572
+ return order === "newest" ? row.seq < query.after : row.seq > query.after;
2573
+ });
2574
+ const slice = rows.slice(0, limit);
2575
+ const last = slice.at(-1);
2576
+ return {
2577
+ ok: true,
2578
+ value: {
2579
+ collection: name,
2580
+ count: collection.count(),
2581
+ records: slice.map((row) => ({ id: row.id, seq: row.seq, value: row.value })),
2582
+ next: rows.length > limit && last ? last.seq : null
2583
+ }
2584
+ };
2585
+ };
2586
+ var readStatePage = (scope, name, query = {}) => pageOf(scope.sqlite, scope.storageNamespace, name, query);
2587
+ var readStateRecord = (scope, name, id) => {
2588
+ if (!COLLECTION_NAME.test(name))
2589
+ return fail(400, "collection name is not allowed");
2590
+ if (!RECORD_ID.test(id))
2591
+ return fail(400, "record id is not allowed");
2592
+ const record = readRecord(collectionOf(scope.sqlite, scope.storageNamespace, name), id);
2593
+ return record ? { ok: true, value: record } : fail(404, `no record ${id} in ${name}`);
2594
+ };
2595
+ var requireId = (id) => RECORD_ID.test(id) ? { ok: true, value: id } : fail(400, "id must be a single path segment");
2596
+ var createStateRecord = (scope, name, input) => {
2597
+ if (!COLLECTION_NAME.test(name))
2598
+ return fail(400, "collection name is not allowed");
2599
+ const parsed = jsonValue(input.value);
2600
+ if (!parsed.ok)
2601
+ return parsed;
2602
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2603
+ const id = input.id ?? `${name}_${collection.nextSequence()}`;
2604
+ const checked = requireId(id);
2605
+ if (!checked.ok)
2606
+ return checked;
2607
+ if (collection.has(checked.value))
2608
+ return fail(409, `record ${checked.value} already exists`);
2609
+ const stored = collection.insert(checked.value, parsed.value);
2610
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2611
+ };
2612
+ var replaceStateRecord = (scope, name, id, value) => {
2613
+ if (!COLLECTION_NAME.test(name))
2614
+ return fail(400, "collection name is not allowed");
2615
+ const checked = requireId(id);
2616
+ if (!checked.ok)
2617
+ return checked;
2618
+ const parsed = jsonValue(value);
2619
+ if (!parsed.ok)
2620
+ return parsed;
2621
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2622
+ if (!collection.has(checked.value))
2623
+ return fail(404, `no record ${checked.value} in ${name}`);
2624
+ const stored = collection.update(checked.value, parsed.value);
2625
+ if (!stored)
2626
+ return fail(404, `no record ${checked.value} in ${name}`);
2627
+ return { ok: true, value: { id: checked.value, seq: stored.seq, value: stored.value } };
2628
+ };
2629
+ var patchStateRecord = (scope, name, id, value) => {
2630
+ const current = readStateRecord(scope, name, id);
2631
+ if (!current.ok)
2632
+ return current;
2633
+ const parsed = jsonValue(value);
2634
+ if (!parsed.ok)
2635
+ return parsed;
2636
+ const next = isRecord2(current.value.value) && isRecord2(parsed.value) ? { ...current.value.value, ...parsed.value } : parsed.value;
2637
+ return replaceStateRecord(scope, name, id, next);
2638
+ };
2639
+ var deleteStateRecord = (scope, name, id) => {
2640
+ if (!COLLECTION_NAME.test(name))
2641
+ return fail(400, "collection name is not allowed");
2642
+ const checked = requireId(id);
2643
+ if (!checked.ok)
2644
+ return checked;
2645
+ const collection = collectionOf(scope.sqlite, scope.storageNamespace, name);
2646
+ return collection.delete(checked.value) ? { ok: true, value: { id: checked.value } } : fail(404, `no record ${checked.value} in ${name}`);
2647
+ };
2648
+ var json3 = (status, body) => new Response(JSON.stringify(body), {
2649
+ status,
2650
+ headers: { "content-type": "application/json; charset=utf-8" }
2651
+ });
2652
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2653
+ var fromResult = (result, status) => result.ok ? json3(status, result.value) : adminError2(result.status, result.message);
2654
+ var integerParam = (value) => {
2655
+ if (value === null)
2656
+ return void 0;
2657
+ if (!/^-?\d+$/.test(value))
2658
+ return "bad";
2659
+ return Number(value);
2660
+ };
2661
+ var stateAdminRoutes = (routes) => {
2662
+ const open = (namespace) => {
2663
+ try {
2664
+ return { ok: true, value: routes.open(namespace) };
2665
+ } catch (error) {
2666
+ return fail(400, error instanceof Error ? error.message : String(error));
2667
+ }
2668
+ };
2669
+ const wrote = (namespace) => {
2670
+ routes.afterWrite?.(namespace);
2671
+ };
2672
+ return {
2673
+ "GET /state": ({ namespace }) => {
2674
+ const scope = open(namespace);
2675
+ return fromResult(scope.ok ? { ok: true, value: inspectState(scope.value) } : scope, 200);
2676
+ },
2677
+ "GET /state/:collection": ({ namespace, params, url }) => {
2678
+ const scope = open(namespace);
2679
+ if (!scope.ok)
2680
+ return fromResult(scope, 200);
2681
+ const limit = integerParam(url.searchParams.get("limit"));
2682
+ const after = integerParam(url.searchParams.get("after"));
2683
+ if (limit === "bad")
2684
+ return adminError2(400, "limit: expected an integer");
2685
+ if (after === "bad")
2686
+ return adminError2(400, "after: expected a sequence number");
2687
+ const order = url.searchParams.get("order");
2688
+ return fromResult(readStatePage(scope.value, params.collection ?? "", {
2689
+ ...limit !== void 0 ? { limit } : {},
2690
+ ...after !== void 0 ? { after } : {},
2691
+ ...order === "newest" || order === "oldest" ? { order } : {}
2692
+ }), 200);
2693
+ },
2694
+ "GET /state/:collection/:id": ({ namespace, params }) => {
2695
+ const scope = open(namespace);
2696
+ if (!scope.ok)
2697
+ return fromResult(scope, 200);
2698
+ return fromResult(readStateRecord(scope.value, params.collection ?? "", params.id ?? ""), 200);
2699
+ },
2700
+ "POST /state/:collection": ({ namespace, params, body }) => {
2701
+ const scope = open(namespace);
2702
+ if (!scope.ok)
2703
+ return fromResult(scope, 201);
2704
+ if (!isRecord2(body) || !("value" in body)) {
2705
+ return adminError2(400, 'expected {"id?": "<id>", "value": <json>}');
2706
+ }
2707
+ const id = body.id;
2708
+ if (id !== void 0 && typeof id !== "string")
2709
+ return adminError2(400, "id must be a string");
2710
+ const created = createStateRecord(scope.value, params.collection ?? "", {
2711
+ ...typeof id === "string" ? { id } : {},
2712
+ value: body.value
2713
+ });
2714
+ if (created.ok)
2715
+ wrote(namespace);
2716
+ return fromResult(created, 201);
2717
+ },
2718
+ "PUT /state/:collection/:id": ({ namespace, params, body }) => {
2719
+ const scope = open(namespace);
2720
+ if (!scope.ok)
2721
+ return fromResult(scope, 200);
2722
+ if (!isRecord2(body) || !("value" in body))
2723
+ return adminError2(400, 'expected {"value": <json>}');
2724
+ const replaced = replaceStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2725
+ if (replaced.ok)
2726
+ wrote(namespace);
2727
+ return fromResult(replaced, 200);
2728
+ },
2729
+ "PATCH /state/:collection/:id": ({ namespace, params, body }) => {
2730
+ const scope = open(namespace);
2731
+ if (!scope.ok)
2732
+ return fromResult(scope, 200);
2733
+ if (!isRecord2(body) || !("value" in body))
2734
+ return adminError2(400, 'expected {"value": <json>}');
2735
+ const patched = patchStateRecord(scope.value, params.collection ?? "", params.id ?? "", body.value);
2736
+ if (patched.ok)
2737
+ wrote(namespace);
2738
+ return fromResult(patched, 200);
2739
+ },
2740
+ "DELETE /state/:collection/:id": ({ namespace, params }) => {
2741
+ const scope = open(namespace);
2742
+ if (!scope.ok)
2743
+ return fromResult(scope, 200);
2744
+ const removed = deleteStateRecord(scope.value, params.collection ?? "", params.id ?? "");
2745
+ if (removed.ok)
2746
+ wrote(namespace);
2747
+ return fromResult(removed, 200);
2748
+ }
2749
+ };
2750
+ };
2751
+
1386
2752
  // ../core/dist/version.js
1387
- var PACKAGE_VERSION = true ? "1.6.0" : UNRELEASED_VERSION;
2753
+ var PACKAGE_VERSION = true ? "1.7.0" : UNRELEASED_VERSION;
1388
2754
 
1389
2755
  // ../core/dist/webhooks.js
1390
- var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1391
- var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1392
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2756
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2757
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2758
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1393
2759
  var parseEndpoint = (value) => {
1394
- if (!isRecord2(value) || typeof value.url !== "string")
2760
+ if (!isRecord3(value) || typeof value.url !== "string")
1395
2761
  return "each endpoint needs a url";
1396
2762
  try {
1397
2763
  new URL(value.url);
@@ -1408,18 +2774,18 @@ var parseEndpoint = (value) => {
1408
2774
  const events = value.events ?? value.enabledEvents;
1409
2775
  if (Array.isArray(events))
1410
2776
  endpoint.events = events.map(String);
1411
- if (isRecord2(value.tags)) {
2777
+ if (isRecord3(value.tags)) {
1412
2778
  endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1413
2779
  }
1414
2780
  if (typeof value.account === "string")
1415
2781
  endpoint.tags = { ...endpoint.tags, account: value.account };
1416
- if (isRecord2(value.headers)) {
2782
+ if (isRecord3(value.headers)) {
1417
2783
  endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1418
2784
  }
1419
2785
  return endpoint;
1420
2786
  };
1421
2787
  var webhookAdminRoutes = (hub) => ({
1422
- "GET /webhooks": ({ url, namespace }) => json2(200, {
2788
+ "GET /webhooks": ({ url, namespace }) => json4(200, {
1423
2789
  deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1424
2790
  const type = url.searchParams.get("type");
1425
2791
  return type === null || d.type === type;
@@ -1427,51 +2793,51 @@ var webhookAdminRoutes = (hub) => ({
1427
2793
  }),
1428
2794
  "GET /webhooks/events": ({ url, namespace }) => {
1429
2795
  const type = url.searchParams.get("type");
1430
- return json2(200, {
2796
+ return json4(200, {
1431
2797
  events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1432
2798
  });
1433
2799
  },
1434
2800
  "POST /webhooks/:id/replay": async ({ params }) => {
1435
2801
  const replayed = await hub.replay(params.id);
1436
- return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
2802
+ return replayed ? json4(200, replayed) : adminError3(404, `no delivery ${params.id}`);
1437
2803
  },
1438
2804
  "POST /webhooks/flush": async () => {
1439
2805
  await hub.flush();
1440
- return json2(200, { status: "ok" });
2806
+ return json4(200, { status: "ok" });
1441
2807
  },
1442
2808
  "POST /webhooks/faults": ({ body, namespace }) => {
1443
- if (!isRecord2(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1444
- return adminError2(400, "mode must be duplicate, reorder or drop");
2809
+ if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
2810
+ return adminError3(400, "mode must be duplicate, reorder or drop");
1445
2811
  }
1446
2812
  const fault = { mode: body.mode };
1447
2813
  if (typeof body.count === "number")
1448
2814
  fault.count = body.count;
1449
2815
  hub.fault(namespace, fault);
1450
- return json2(201, { namespace, ...fault });
2816
+ return json4(201, { namespace, ...fault });
1451
2817
  },
1452
- "GET /webhook-endpoints": ({ namespace }) => json2(200, {
2818
+ "GET /webhook-endpoints": ({ namespace }) => json4(200, {
1453
2819
  endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1454
2820
  ...rest,
1455
2821
  secret: secret ? "(set)" : null
1456
2822
  }))
1457
2823
  }),
1458
2824
  "PUT /webhook-endpoints": ({ body, namespace }) => {
1459
- const list = Array.isArray(body) ? body : isRecord2(body) ? body.endpoints : void 0;
2825
+ const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
1460
2826
  if (!Array.isArray(list))
1461
- return adminError2(400, "expected [{url, secret?, events?}]");
2827
+ return adminError3(400, "expected [{url, secret?, events?}]");
1462
2828
  const parsed = [];
1463
2829
  for (const each of list) {
1464
2830
  const endpoint = parseEndpoint(each);
1465
2831
  if (typeof endpoint === "string")
1466
- return adminError2(400, endpoint);
2832
+ return adminError3(400, endpoint);
1467
2833
  parsed.push(endpoint);
1468
2834
  }
1469
2835
  const set = hub.setEndpoints(namespace, parsed);
1470
- return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
2836
+ return json4(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1471
2837
  },
1472
2838
  "DELETE /webhook-endpoints": ({ namespace }) => {
1473
2839
  hub.setEndpoints(namespace, []);
1474
- return json2(200, { status: "ok" });
2840
+ return json4(200, { status: "ok" });
1475
2841
  }
1476
2842
  });
1477
2843
  var parsePayload = (message) => {
@@ -1534,6 +2900,7 @@ var operationMatcher = (document2) => {
1534
2900
  return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1535
2901
  };
1536
2902
  var createRuntime = (options) => {
2903
+ assertAdminUi(options.adminUi);
1537
2904
  const sqlite = bootSqlite(options.sqlite);
1538
2905
  const clock = options.clock ?? createClock();
1539
2906
  const rng = createRng(options.seed ?? 0);
@@ -1740,6 +3107,19 @@ var createRuntime = (options) => {
1740
3107
  else
1741
3108
  timeline(name);
1742
3109
  };
3110
+ const declarationsFor = (namespace) => {
3111
+ const declared = options.state;
3112
+ if (!declared)
3113
+ return [];
3114
+ return typeof declared === "function" ? declared(instance(namespace), namespace) : declared;
3115
+ };
3116
+ const stateScope = (namespace) => ({
3117
+ sqlite,
3118
+ namespace,
3119
+ storageNamespace: storageNamespace(namespace),
3120
+ root: instance(namespace),
3121
+ declarations: declarationsFor(namespace)
3122
+ });
1743
3123
  const runtime = {
1744
3124
  name: options.name,
1745
3125
  sqlite,
@@ -1778,6 +3158,7 @@ var createRuntime = (options) => {
1778
3158
  branch,
1779
3159
  checkout,
1780
3160
  timeline,
3161
+ state: (namespace = DEFAULT_NAMESPACE) => inspectState(stateScope(namespace)),
1781
3162
  fetch: async (incoming) => {
1782
3163
  let request = incoming;
1783
3164
  const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
@@ -1971,11 +3352,20 @@ var createRuntime = (options) => {
1971
3352
  ...credentialRoutes(credentials),
1972
3353
  ...options.presets ? presetRoutes(options.presets, runtime) : {},
1973
3354
  ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
1974
- ...options.admin?.(runtime) ?? {}
3355
+ ...options.admin?.(runtime) ?? {},
3356
+ // Standard state and UI routes win a colliding key. A service adds its own keys
3357
+ // beside these; it does not replace `/state` or `/ui`.
3358
+ ...stateAdminRoutes({
3359
+ open: stateScope,
3360
+ afterWrite: (namespace) => {
3361
+ checkpoint(namespace, "main");
3362
+ }
3363
+ }),
3364
+ ...adminUiRoutes(options.name, options.adminUi)
1975
3365
  },
1976
3366
  adminKey: options.adminKey
1977
3367
  });
1978
- return runtime;
3368
+ return defineMock(runtime);
1979
3369
  };
1980
3370
  var mutableResponse = (response) => {
1981
3371
  try {
@@ -2468,7 +3858,7 @@ var Credentials = class {
2468
3858
  };
2469
3859
 
2470
3860
  // src/ui.ts
2471
- var escapeHtml = (value) => value.replace(
3861
+ var escapeHtml2 = (value) => value.replace(
2472
3862
  /[&<>"']/g,
2473
3863
  (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c] ?? c
2474
3864
  );
@@ -2483,7 +3873,7 @@ var style = `
2483
3873
  `;
2484
3874
  function page(title, body, status = 200, action = "'self'", nonce = crypto.randomUUID(), testId = "") {
2485
3875
  return new Response(
2486
- `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>${escapeHtml(title)} \xB7 OAuth Mock</title><style nonce="${nonce}">${style}</style></head><body><a class="skip" href="#main">Skip to content</a><header><span>OAuth Mock</span></header><main id="main"><section class="card" aria-labelledby="title"${testId ? ` data-testid="${testId}"` : ""}>${body}</section><p class="note">Test accounts only.</p></main><footer><fieldset class="theme"><legend>Appearance</legend><label><input type="radio" name="oauth-theme" value="system" checked>System</label><label><input type="radio" name="oauth-theme" value="light">Light</label><label><input type="radio" name="oauth-theme" value="dark">Dark</label></fieldset></footer><script nonce="${nonce}">(()=>{const root=document.documentElement;const inputs=document.querySelectorAll('input[name="oauth-theme"]');const apply=value=>{root.dataset.theme=value;for(const input of inputs)input.checked=input.value===value;try{sessionStorage.setItem('oauth-mock-theme',value)}catch{}};try{const saved=sessionStorage.getItem('oauth-mock-theme');if(['system','light','dark'].includes(saved))apply(saved)}catch{}for(const input of inputs)input.addEventListener('change',()=>apply(input.value))})()</script></body></html>`,
3876
+ `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>${escapeHtml2(title)} \xB7 OAuth Mock</title><style nonce="${nonce}">${style}</style></head><body><a class="skip" href="#main">Skip to content</a><header><span>OAuth Mock</span></header><main id="main"><section class="card" aria-labelledby="title"${testId ? ` data-testid="${testId}"` : ""}>${body}</section><p class="note">Test accounts only.</p></main><footer><fieldset class="theme"><legend>Appearance</legend><label><input type="radio" name="oauth-theme" value="system" checked>System</label><label><input type="radio" name="oauth-theme" value="light">Light</label><label><input type="radio" name="oauth-theme" value="dark">Dark</label></fieldset></footer><script nonce="${nonce}">(()=>{const root=document.documentElement;const inputs=document.querySelectorAll('input[name="oauth-theme"]');const apply=value=>{root.dataset.theme=value;for(const input of inputs)input.checked=input.value===value;try{sessionStorage.setItem('oauth-mock-theme',value)}catch{}};try{const saved=sessionStorage.getItem('oauth-mock-theme');if(['system','light','dark'].includes(saved))apply(saved)}catch{}for(const input of inputs)input.addEventListener('change',()=>apply(input.value))})()</script></body></html>`,
2487
3877
  {
2488
3878
  status,
2489
3879
  headers: {
@@ -2497,10 +3887,10 @@ function page(title, body, status = 200, action = "'self'", nonce = crypto.rando
2497
3887
  );
2498
3888
  }
2499
3889
  function loginPage(transaction, client, accounts, base, action, signup = false, error = "", nonce) {
2500
- const hidden = `<input type="hidden" name="transaction" value="${escapeHtml(transaction)}">`;
2501
- const endpoint = escapeHtml(`${base}/interaction`);
2502
- const intro = `<span class="eyebrow">Sign in</span><h1 id="title">${signup ? "Create your account" : "Choose an account"}</h1><p>${signup ? "Create an account to continue to" : "Choose an account to continue to"}<br><span class="app">${escapeHtml(client)}</span></p>${error ? `<div class="error" role="alert" data-testid="oauth-mock-${signup ? "signup" : "chooser"}-error">${escapeHtml(error)}</div>` : ""}`;
2503
- const body = signup ? `<form method="post" action="${endpoint}">${hidden}<input type="hidden" name="action" value="signup"><div class="fields"><label for="name">Full name</label><input id="name" name="name" data-testid="oauth-mock-signup-name" autocomplete="name" required maxlength="120"><label for="email">Email address</label><input id="email" name="email" data-testid="oauth-mock-signup-email" type="email" autocomplete="email" required maxlength="254" aria-describedby="email-help"><p id="email-help" class="note">Use a fictional address. No email will be sent.</p></div><button class="primary" data-testid="oauth-mock-signup-submit">Create account &amp; continue</button></form><a class="back" href="${endpoint}?transaction=${escapeHtml(transaction)}">Back to accounts</a>` : `<div class="accounts">${accounts.map((a) => `<form method="post" action="${endpoint}" data-testid="oauth-mock-account" data-account-id="${escapeHtml(a.id)}" data-email="${escapeHtml(a.email)}">${hidden}<input type="hidden" name="action" value="select"><button class="account" data-testid="oauth-mock-account-${escapeHtml(a.id)}" name="account" value="${escapeHtml(a.id)}"><span class="avatar" aria-hidden="true">${escapeHtml(a.name.slice(0, 1).toUpperCase())}</span><span class="identity"><strong>${escapeHtml(a.name)}</strong><small>${escapeHtml(a.email)}</small></span><span class="arrow" aria-hidden="true">\u2192</span></button></form>`).join("") || '<p class="empty">No accounts yet. Create your first test identity below.</p>'}</div><form method="get" action="${endpoint}">${hidden}<input type="hidden" name="screen" value="signup"><button class="secondary" data-testid="oauth-mock-create-account">\uFF0B Create a new account</button></form>`;
3890
+ const hidden = `<input type="hidden" name="transaction" value="${escapeHtml2(transaction)}">`;
3891
+ const endpoint = escapeHtml2(`${base}/interaction`);
3892
+ const intro = `<span class="eyebrow">Sign in</span><h1 id="title">${signup ? "Create your account" : "Choose an account"}</h1><p>${signup ? "Create an account to continue to" : "Choose an account to continue to"}<br><span class="app">${escapeHtml2(client)}</span></p>${error ? `<div class="error" role="alert" data-testid="oauth-mock-${signup ? "signup" : "chooser"}-error">${escapeHtml2(error)}</div>` : ""}`;
3893
+ const body = signup ? `<form method="post" action="${endpoint}">${hidden}<input type="hidden" name="action" value="signup"><div class="fields"><label for="name">Full name</label><input id="name" name="name" data-testid="oauth-mock-signup-name" autocomplete="name" required maxlength="120"><label for="email">Email address</label><input id="email" name="email" data-testid="oauth-mock-signup-email" type="email" autocomplete="email" required maxlength="254" aria-describedby="email-help"><p id="email-help" class="note">Use a fictional address. No email will be sent.</p></div><button class="primary" data-testid="oauth-mock-signup-submit">Create account &amp; continue</button></form><a class="back" href="${endpoint}?transaction=${escapeHtml2(transaction)}">Back to accounts</a>` : `<div class="accounts">${accounts.map((a) => `<form method="post" action="${endpoint}" data-testid="oauth-mock-account" data-account-id="${escapeHtml2(a.id)}" data-email="${escapeHtml2(a.email)}">${hidden}<input type="hidden" name="action" value="select"><button class="account" data-testid="oauth-mock-account-${escapeHtml2(a.id)}" name="account" value="${escapeHtml2(a.id)}"><span class="avatar" aria-hidden="true">${escapeHtml2(a.name.slice(0, 1).toUpperCase())}</span><span class="identity"><strong>${escapeHtml2(a.name)}</strong><small>${escapeHtml2(a.email)}</small></span><span class="arrow" aria-hidden="true">\u2192</span></button></form>`).join("") || '<p class="empty">No accounts yet. Create your first test identity below.</p>'}</div><form method="get" action="${endpoint}">${hidden}<input type="hidden" name="screen" value="signup"><button class="secondary" data-testid="oauth-mock-create-account">\uFF0B Create a new account</button></form>`;
2504
3894
  return page(
2505
3895
  signup ? "Create account" : "Choose an account",
2506
3896
  `${intro}${body}<div class="divider"></div><form method="post" action="${endpoint}">${hidden}<button class="secondary" data-testid="oauth-mock-deny" name="action" value="deny">Cancel sign-in</button></form>`,
@@ -2518,14 +3908,14 @@ function consentPage(transaction, client, account, scopes2, base, action, privac
2518
3908
  name: "View your name",
2519
3909
  offline_access: "Stay connected when you\u2019re away"
2520
3910
  };
2521
- const privacyFields = privacy ? privacy.choice ? `<fieldset class="privacy"><legend>Choose what to share</legend><label><input type="radio" name="email_choice" data-testid="oauth-mock-share-email" value="share" ${!privacy.hideEmail ? "checked" : ""}><span>Share my email<small>Your app will receive ${escapeHtml(account.email)}.</small></span></label><label><input type="radio" name="email_choice" data-testid="oauth-mock-hide-email" value="hide" ${privacy.hideEmail ? "checked" : ""}><span>Hide my email<small>Use a private relay address to keep your email private.</small></span></label></fieldset>` : `<p>${privacy.hideEmail ? "A private relay address will be shared with this app." : "Your email address will be shared with this app."}</p>` : "";
3911
+ const privacyFields = privacy ? privacy.choice ? `<fieldset class="privacy"><legend>Choose what to share</legend><label><input type="radio" name="email_choice" data-testid="oauth-mock-share-email" value="share" ${!privacy.hideEmail ? "checked" : ""}><span>Share my email<small>Your app will receive ${escapeHtml2(account.email)}.</small></span></label><label><input type="radio" name="email_choice" data-testid="oauth-mock-hide-email" value="hide" ${privacy.hideEmail ? "checked" : ""}><span>Hide my email<small>Use a private relay address to keep your email private.</small></span></label></fieldset>` : `<p>${privacy.hideEmail ? "A private relay address will be shared with this app." : "Your email address will be shared with this app."}</p>` : "";
2522
3912
  return page(
2523
3913
  "Review access",
2524
- `<span class="eyebrow">Permissions</span><h1 id="title">Review access</h1><p><span class="app">${escapeHtml(client)}</span> would like access to your account.</p><div class="account"><span class="avatar" aria-hidden="true">${escapeHtml(account.name.slice(0, 1))}</span><span class="identity"><strong>${escapeHtml(account.name)}</strong><small>${escapeHtml(account.email)}</small></span></div><ul class="permissions">${scopes2.split(" ").filter(Boolean).map(
2525
- (s) => `<li><span class="check" aria-hidden="true">\u2713</span>${escapeHtml(labels[s] ?? s)}</li>`
3914
+ `<span class="eyebrow">Permissions</span><h1 id="title">Review access</h1><p><span class="app">${escapeHtml2(client)}</span> would like access to your account.</p><div class="account"><span class="avatar" aria-hidden="true">${escapeHtml2(account.name.slice(0, 1))}</span><span class="identity"><strong>${escapeHtml2(account.name)}</strong><small>${escapeHtml2(account.email)}</small></span></div><ul class="permissions">${scopes2.split(" ").filter(Boolean).map(
3915
+ (s) => `<li><span class="check" aria-hidden="true">\u2713</span>${escapeHtml2(labels[s] ?? s)}</li>`
2526
3916
  ).join(
2527
3917
  ""
2528
- )}</ul><p>You can cancel now without sharing anything.</p><form method="post" action="${escapeHtml(base)}/interaction"><input type="hidden" name="transaction" value="${escapeHtml(transaction)}">${privacyFields}<button class="primary" data-testid="oauth-mock-allow" name="action" value="allow">Allow &amp; continue</button><button class="secondary" data-testid="oauth-mock-deny" name="action" value="deny">Cancel</button></form>`,
3918
+ )}</ul><p>You can cancel now without sharing anything.</p><form method="post" action="${escapeHtml2(base)}/interaction"><input type="hidden" name="transaction" value="${escapeHtml2(transaction)}">${privacyFields}<button class="primary" data-testid="oauth-mock-allow" name="action" value="allow">Allow &amp; continue</button><button class="secondary" data-testid="oauth-mock-deny" name="action" value="deny">Cancel</button></form>`,
2529
3919
  200,
2530
3920
  action,
2531
3921
  nonce,
@@ -2686,7 +4076,7 @@ function createRuntime2(options = {}) {
2686
4076
  // src/multi.ts
2687
4077
  var MOUNT_PATTERN = /^\/[A-Za-z0-9](?:[A-Za-z0-9._~-]*)(?:\/[A-Za-z0-9](?:[A-Za-z0-9._~-]*))*$/;
2688
4078
  var NS_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
2689
- var json3 = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } });
4079
+ var json5 = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } });
2690
4080
  var validateMounts = (mounts) => {
2691
4081
  if (mounts.length === 0) throw new Error("at least one OAuth mount is required");
2692
4082
  const paths = /* @__PURE__ */ new Set();
@@ -2757,24 +4147,24 @@ function createMultiRuntime(options) {
2757
4147
  await (await runtime.fetch(new Request(new URL("/health", url), request))).json()
2758
4148
  ])
2759
4149
  );
2760
- return json3({ status: "ok", service: "oauth", mounts: Object.fromEntries(health) });
4150
+ return json5({ status: "ok", service: "oauth", mounts: Object.fromEntries(health) });
2761
4151
  }
2762
4152
  if (url.pathname.startsWith("/__admin") && options.adminKey !== void 0 && request.headers.get("x-mockingbird-admin-key") !== options.adminKey)
2763
- return json3({ error: { type: "mockingbird_admin", message: "invalid admin key" } }, 401);
4153
+ return json5({ error: { type: "mockingbird_admin", message: "invalid admin key" } }, 401);
2764
4154
  if (url.pathname === "/__admin/mounts" && request.method === "GET")
2765
- return json3({
4155
+ return json5({
2766
4156
  mounts: options.mounts.map(({ path: path2, provider, issuer }) => ({ path: path2, provider, issuer }))
2767
4157
  });
2768
4158
  if (url.pathname === "/__admin/reset" && request.method === "POST") {
2769
4159
  const namespace2 = url.searchParams.get("all") === "1" ? "*" : url.searchParams.get("namespace") ?? request.headers.get("x-mockingbird-namespace") ?? "default";
2770
4160
  await reset(namespace2);
2771
- return json3({ status: "ok", mounts: [...runtimes.keys()], namespace: namespace2 });
4161
+ return json5({ status: "ok", mounts: [...runtimes.keys()], namespace: namespace2 });
2772
4162
  }
2773
4163
  if (url.pathname.startsWith("/__admin/")) {
2774
4164
  const selected = url.searchParams.get("mount");
2775
4165
  const runtime = selected && runtimes.get(selected);
2776
4166
  if (!runtime)
2777
- return json3({ error: { type: "mockingbird_admin", message: "mount is required" } }, 400);
4167
+ return json5({ error: { type: "mockingbird_admin", message: "mount is required" } }, 400);
2778
4168
  url.searchParams.delete("mount");
2779
4169
  return runtime.fetch(new Request(url, request));
2780
4170
  }
@@ -2785,14 +4175,14 @@ function createMultiRuntime(options) {
2785
4175
  if (path !== mount && !path.startsWith(`${mount}/`)) continue;
2786
4176
  return runtime.fetch(withoutMount(request, namespacePrefix, path.slice(mount.length)));
2787
4177
  }
2788
- return json3({ error: { type: "mockingbird_not_found", message: "unknown OAuth mount" } }, 404);
4178
+ return json5({ error: { type: "mockingbird_not_found", message: "unknown OAuth mount" } }, 404);
2789
4179
  }
2790
4180
  };
2791
4181
  }
2792
4182
 
2793
4183
  // src/index.ts
2794
- var json4 = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store", pragma: "no-cache" } });
2795
- var fail = (error, description, status = 400) => json4({ error, error_description: description }, status);
4184
+ var json6 = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store", pragma: "no-cache" } });
4185
+ var fail2 = (error, description, status = 400) => json6({ error, error_description: description }, status);
2796
4186
  var scopes = (value) => new Set(value.split(/\s+/).filter(Boolean));
2797
4187
  var validEmail = (s) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s) && s.length <= 254;
2798
4188
  var WEB_SCHEMES = /* @__PURE__ */ new Set(["http:", "https:"]);
@@ -3247,7 +4637,7 @@ var OAuthAPI = class {
3247
4637
  async route(request, url, issuer, path) {
3248
4638
  const paths = this.paths();
3249
4639
  if (request.method === "GET" && path === "/.well-known/openid-configuration" && this.provider !== "github")
3250
- return json4({
4640
+ return json6({
3251
4641
  issuer,
3252
4642
  authorization_endpoint: issuer + paths.authorize,
3253
4643
  token_endpoint: issuer + paths.token,
@@ -3311,7 +4701,7 @@ var OAuthAPI = class {
3311
4701
  ]
3312
4702
  });
3313
4703
  if (request.method === "GET" && [paths.jwks, "/jwks"].includes(path))
3314
- return json4({
4704
+ return json6({
3315
4705
  keys: (await Promise.all([this.signer, ...this.previousSigners].map((s) => s.jwks()))).flatMap((j) => j.keys)
3316
4706
  });
3317
4707
  if (request.method === "GET" && [
@@ -3337,10 +4727,10 @@ var OAuthAPI = class {
3337
4727
  );
3338
4728
  const account = token && this.accounts.get(token.accountId);
3339
4729
  if (token?.kind !== "access" || token.expires <= this.now() || !account || account.disabled) {
3340
- const res = this.provider === "github" ? json4(
4730
+ const res = this.provider === "github" ? json6(
3341
4731
  { message: "Bad credentials", documentation_url: "https://docs.github.com/rest" },
3342
4732
  401
3343
- ) : fail("invalid_token", "Invalid or expired access token", 401);
4733
+ ) : fail2("invalid_token", "Invalid or expired access token", 401);
3344
4734
  res.headers.set("www-authenticate", 'Bearer error="invalid_token"');
3345
4735
  return res;
3346
4736
  }
@@ -3367,11 +4757,11 @@ var OAuthAPI = class {
3367
4757
  visibility: "private"
3368
4758
  }
3369
4759
  ];
3370
- const response2 = json4(emails);
4760
+ const response2 = json6(emails);
3371
4761
  for (const [key, value] of Object.entries(scopeHeaders)) response2.headers.set(key, value);
3372
4762
  return response2;
3373
4763
  }
3374
- const response = json4({
4764
+ const response = json6({
3375
4765
  login: account.github?.login ?? account.id,
3376
4766
  id: account.github?.id ?? seedFrom(account.id) + 1,
3377
4767
  node_id: btoa(`User:${account.github?.id ?? seedFrom(account.id) + 1}`),
@@ -3383,18 +4773,18 @@ var OAuthAPI = class {
3383
4773
  for (const [key, value] of Object.entries(scopeHeaders)) response.headers.set(key, value);
3384
4774
  return response;
3385
4775
  }
3386
- return json4(this.profile(account, token));
4776
+ return json6(this.profile(account, token));
3387
4777
  }
3388
4778
  if (request.method === "POST" && [paths.revoke, "/revoke"].includes(path)) {
3389
4779
  const data = await this.form(request);
3390
- if (!data) return fail("invalid_request", "Expected form-encoded body");
4780
+ if (!data) return fail2("invalid_request", "Expected form-encoded body");
3391
4781
  const client = await this.authenticate(request, data);
3392
4782
  if (client instanceof Response) return client;
3393
4783
  const token = this.tokens.get(data.get("token") ?? "");
3394
4784
  if (token && token.clientId === client.id)
3395
4785
  for (const row of this.tokens.list({ where: (t) => t.family === token.family }))
3396
4786
  this.tokens.delete(row.id);
3397
- return json4({});
4787
+ return json6({});
3398
4788
  }
3399
4789
  if (request.method === "GET" && path === "/")
3400
4790
  return page(
@@ -3404,7 +4794,7 @@ var OAuthAPI = class {
3404
4794
  void 0,
3405
4795
  this.credentials.nonce()
3406
4796
  );
3407
- return fail("not_found", "Unknown endpoint", 404);
4797
+ return fail2("not_found", "Unknown endpoint", 404);
3408
4798
  }
3409
4799
  async form(request) {
3410
4800
  if (!request.headers.get("content-type")?.startsWith("application/x-www-form-urlencoded"))
@@ -3420,9 +4810,9 @@ var OAuthAPI = class {
3420
4810
  const auth = request.headers.get("authorization");
3421
4811
  if (auth) {
3422
4812
  if (this.provider === "apple")
3423
- return fail("invalid_client", "Apple requires client_secret_post", 401);
4813
+ return fail2("invalid_client", "Apple requires client_secret_post", 401);
3424
4814
  if (!auth.startsWith("Basic ") || data.has("client_secret"))
3425
- return fail("invalid_client", "Invalid client authentication", 401);
4815
+ return fail2("invalid_client", "Invalid client authentication", 401);
3426
4816
  try {
3427
4817
  const decoded = atob(auth.slice(6));
3428
4818
  const colon = decoded.indexOf(":");
@@ -3430,25 +4820,25 @@ var OAuthAPI = class {
3430
4820
  id = decodeURIComponent(decoded.slice(0, colon).replace(/\+/g, " "));
3431
4821
  secret = decodeURIComponent(decoded.slice(colon + 1).replace(/\+/g, " "));
3432
4822
  } catch {
3433
- return fail("invalid_client", "Malformed client authentication", 401);
4823
+ return fail2("invalid_client", "Malformed client authentication", 401);
3434
4824
  }
3435
4825
  if (data.has("client_id") && data.get("client_id") !== id)
3436
- return fail("invalid_client", "Conflicting client identities", 401);
4826
+ return fail2("invalid_client", "Conflicting client identities", 401);
3437
4827
  }
3438
4828
  const client = this.clients.get(id);
3439
4829
  if (!client || client.secret !== void 0 && client.secret !== secret || client.secret === void 0 && !client.apple && secret)
3440
- return fail("invalid_client", "Client authentication failed", 401);
4830
+ return fail2("invalid_client", "Client authentication failed", 401);
3441
4831
  if (client.apple && !await verifyAppleSecret(secret, client.id, client.apple, this.now()))
3442
- return fail("invalid_client", "Invalid Apple client-secret JWT", 401);
4832
+ return fail2("invalid_client", "Invalid Apple client-secret JWT", 401);
3443
4833
  return client;
3444
4834
  }
3445
4835
  async authorize(request, p, issuer) {
3446
4836
  if ([...p.keys()].some((k) => p.getAll(k).length !== 1))
3447
- return fail("invalid_request", "Duplicate parameters");
4837
+ return fail2("invalid_request", "Duplicate parameters");
3448
4838
  const client = this.clients.get(p.get("client_id") ?? "");
3449
4839
  const redirectUri = p.get("redirect_uri") ?? (this.provider === "github" ? client?.redirectUris[0] ?? "" : "");
3450
4840
  if (!client?.redirectUris.includes(redirectUri))
3451
- return fail("invalid_request", "Unknown client or redirect_uri mismatch");
4841
+ return fail2("invalid_request", "Unknown client or redirect_uri mismatch");
3452
4842
  const mode = p.get("response_mode") ?? "query";
3453
4843
  const auth = {
3454
4844
  clientId: client.id,
@@ -3544,9 +4934,9 @@ var OAuthAPI = class {
3544
4934
  }
3545
4935
  async interact(request, issuer) {
3546
4936
  const p = request.method === "GET" ? new URL(request.url).searchParams : await this.form(request);
3547
- if (!p) return fail("invalid_request", "Expected form-encoded body");
4937
+ if (!p) return fail2("invalid_request", "Expected form-encoded body");
3548
4938
  if (request.method === "POST" && request.headers.get("origin") && request.headers.get("origin") !== new URL(issuer).origin)
3549
- return fail("invalid_request", "Cross-origin interaction rejected", 403);
4939
+ return fail2("invalid_request", "Cross-origin interaction rejected", 403);
3550
4940
  const id = p.get("transaction") ?? "";
3551
4941
  const auth = this.transactions.get(id);
3552
4942
  const client = auth && this.clients.get(auth.clientId);
@@ -3644,10 +5034,10 @@ var OAuthAPI = class {
3644
5034
  }
3645
5035
  if (action === "allow" && auth.accountId) {
3646
5036
  const account = this.accounts.get(auth.accountId);
3647
- if (!account || account.disabled) return fail("access_denied", "Account is unavailable");
5037
+ if (!account || account.disabled) return fail2("access_denied", "Account is unavailable");
3648
5038
  const choice = p.get("email_choice");
3649
5039
  if (choice !== null && choice !== "hide" && choice !== "share")
3650
- return fail("invalid_request", "Invalid email choice");
5040
+ return fail2("invalid_request", "Invalid email choice");
3651
5041
  if (choice && this.provider === "apple" && (this.behavior.config.apple?.emailMode ?? "choose") === "choose" && !this.identities.has(this.identityKey(client, account.id)))
3652
5042
  auth.emailChoice = choice;
3653
5043
  this.transactions.delete(id);
@@ -3658,7 +5048,7 @@ var OAuthAPI = class {
3658
5048
  issuer
3659
5049
  );
3660
5050
  }
3661
- return fail("invalid_request", "Invalid interaction action");
5051
+ return fail2("invalid_request", "Invalid interaction action");
3662
5052
  }
3663
5053
  startSession(result, accountId, authTime, issuer) {
3664
5054
  const session = this.credentials.token();
@@ -3737,9 +5127,9 @@ var OAuthAPI = class {
3737
5127
  const nonce = this.options.nonce?.() ?? this.credentials.nonce();
3738
5128
  const result = page(
3739
5129
  "Continue to your app",
3740
- `<span class="eyebrow">All set</span><h1 id="title">Back to your app</h1><p>Your sign-in response is ready.</p><form id="callback" method="post" action="${escapeHtml(auth.redirectUri)}">${Object.entries(
5130
+ `<span class="eyebrow">All set</span><h1 id="title">Back to your app</h1><p>Your sign-in response is ready.</p><form id="callback" method="post" action="${escapeHtml2(auth.redirectUri)}">${Object.entries(
3741
5131
  values
3742
- ).map(([k, v]) => `<input type="hidden" name="${escapeHtml(k)}" value="${escapeHtml(v)}">`).join(
5132
+ ).map(([k, v]) => `<input type="hidden" name="${escapeHtml2(k)}" value="${escapeHtml2(v)}">`).join(
3743
5133
  ""
3744
5134
  )}<button class="primary" data-testid="oauth-mock-form-post-continue">Continue</button></form><script nonce="${nonce}">document.getElementById('callback').submit()</script>`,
3745
5135
  200,
@@ -3776,7 +5166,7 @@ var OAuthAPI = class {
3776
5166
  if (body.error && response.status < 500)
3777
5167
  body.error_uri = `https://docs.github.com/en/apps/oauth-apps/maintaining-oauth-apps/troubleshooting-oauth-app-access-token-request-errors#${String(body.error).replace(/_/g, "-")}`;
3778
5168
  const status = body.error && response.status < 500 ? 200 : response.status;
3779
- if (request.headers.get("accept")?.includes("application/json")) return json4(body, status);
5169
+ if (request.headers.get("accept")?.includes("application/json")) return json6(body, status);
3780
5170
  return new Response(
3781
5171
  new URLSearchParams(Object.fromEntries(Object.entries(body).map(([k, v]) => [k, String(v)]))),
3782
5172
  {
@@ -3803,31 +5193,31 @@ var OAuthAPI = class {
3803
5193
  }
3804
5194
  } else p = await this.form(request);
3805
5195
  if (!p)
3806
- return fail("invalid_request", "Expected form-encoded body without duplicate parameters");
5196
+ return fail2("invalid_request", "Expected form-encoded body without duplicate parameters");
3807
5197
  const client = await this.authenticate(request, p);
3808
5198
  if (client instanceof Response) return client;
3809
5199
  const type = p.get("grant_type") ?? (this.provider === "github" ? "authorization_code" : null);
3810
5200
  if (type !== "authorization_code" && type !== "refresh_token")
3811
- return fail("unsupported_grant_type", "Unsupported grant_type");
5201
+ return fail2("unsupported_grant_type", "Unsupported grant_type");
3812
5202
  const key = p.get(type === "authorization_code" ? "code" : "refresh_token") ?? "";
3813
5203
  const stored = type === "authorization_code" ? this.codes.get(key) : this.tokens.get(key);
3814
5204
  const account = stored && this.accounts.get(stored.accountId);
3815
5205
  if (!stored || stored.clientId !== client.id || stored.expires <= this.now() || !account || account.disabled || type === "refresh_token" && (!("kind" in stored) || stored.kind !== "refresh"))
3816
- return fail("invalid_grant", "Invalid, expired or consumed grant");
5206
+ return fail2("invalid_grant", "Invalid, expired or consumed grant");
3817
5207
  if (type === "refresh_token" && this.provider === "google" && "lastUsed" in stored && typeof stored.lastUsed === "number") {
3818
5208
  const inactiveUntil = new Date(stored.lastUsed);
3819
5209
  inactiveUntil.setUTCMonth(inactiveUntil.getUTCMonth() + 6);
3820
5210
  if (this.now() >= inactiveUntil.getTime()) {
3821
5211
  this.tokens.delete(key);
3822
- return fail("invalid_grant", "Refresh token expired after six months of inactivity");
5212
+ return fail2("invalid_grant", "Refresh token expired after six months of inactivity");
3823
5213
  }
3824
5214
  }
3825
5215
  if (this.provider === "github" && (account.emailVerified === false || account.github?.emails?.find((e) => e.primary)?.verified === false || stored.decisions.unverifiedEmail))
3826
- return fail("unverified_user_email", "The user must have a verified primary email.");
5216
+ return fail2("unverified_user_email", "The user must have a verified primary email.");
3827
5217
  const behavior = this.behavior.config;
3828
5218
  const effects2 = this.behavior.sample("token", ["tokenUnavailable", "invalidGrant"]);
3829
5219
  if (effects2.tokenUnavailable) {
3830
- const response = fail(
5220
+ const response = fail2(
3831
5221
  "temporarily_unavailable",
3832
5222
  "Authorization server temporarily unavailable",
3833
5223
  503
@@ -3839,7 +5229,7 @@ var OAuthAPI = class {
3839
5229
  if (behavior.tokens?.refreshError === "invalid_grant" || effects2.invalidGrant)
3840
5230
  for (const row of this.tokens.list({ where: (t) => t.family === stored.family }))
3841
5231
  this.tokens.delete(row.id);
3842
- return json4(
5232
+ return json6(
3843
5233
  {
3844
5234
  error: "invalid_grant",
3845
5235
  error_description: "Token has been expired or revoked.",
@@ -3850,29 +5240,29 @@ var OAuthAPI = class {
3850
5240
  }
3851
5241
  if (effects2.invalidGrant) {
3852
5242
  this.codes.delete(key);
3853
- return fail("invalid_grant", "Token has been expired or revoked.");
5243
+ return fail2("invalid_grant", "Token has been expired or revoked.");
3854
5244
  }
3855
5245
  if (type === "refresh_token" && "consumed" in stored && stored.consumed) {
3856
5246
  for (const row of this.tokens.list({ where: (t) => t.family === stored.family }))
3857
5247
  this.tokens.delete(row.id);
3858
- return fail("invalid_grant", "Refresh token reuse detected; token family revoked");
5248
+ return fail2("invalid_grant", "Refresh token reuse detected; token family revoked");
3859
5249
  }
3860
5250
  if (type === "authorization_code") {
3861
5251
  if ((this.provider !== "github" || p.has("redirect_uri")) && p.get("redirect_uri") !== stored.redirectUri)
3862
- return fail("invalid_grant", "redirect_uri mismatch");
5252
+ return fail2("invalid_grant", "redirect_uri mismatch");
3863
5253
  if (stored.challenge) {
3864
5254
  const verifier = p.get("code_verifier") ?? "";
3865
5255
  if (!/^[A-Za-z0-9._~-]{43,128}$/.test(verifier) || await hash(verifier) !== stored.challenge)
3866
- return fail("invalid_grant", "PKCE verification failed");
5256
+ return fail2("invalid_grant", "PKCE verification failed");
3867
5257
  }
3868
5258
  if (!this.codes.delete(key))
3869
- return fail("invalid_grant", "Authorization code already consumed");
5259
+ return fail2("invalid_grant", "Authorization code already consumed");
3870
5260
  }
3871
5261
  const grant = { ...stored };
3872
5262
  if (type === "refresh_token" && p.has("scope")) {
3873
5263
  const requested = p.get("scope") ?? "";
3874
5264
  if ([...scopes(requested)].some((s) => !scopes(stored.scope).has(s)))
3875
- return fail("invalid_scope", "Cannot expand granted scope");
5265
+ return fail2("invalid_scope", "Cannot expand granted scope");
3876
5266
  grant.scope = requested;
3877
5267
  }
3878
5268
  if (type === "refresh_token")
@@ -3954,7 +5344,7 @@ var OAuthAPI = class {
3954
5344
  }
3955
5345
  }
3956
5346
  );
3957
- return json4(result);
5347
+ return json6(result);
3958
5348
  }
3959
5349
  };
3960
5350
 
@@ -3968,4 +5358,4 @@ export {
3968
5358
  createMultiRuntime,
3969
5359
  OAuthAPI
3970
5360
  };
3971
- //# sourceMappingURL=chunk-SYFF4UFD.js.map
5361
+ //# sourceMappingURL=chunk-6J2COVKO.js.map