@crvouga/mockingbird-service-prism 0.1.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.
@@ -0,0 +1,2766 @@
1
+ // ../core/dist/clock.js
2
+ var createClock = (source = Date.now) => {
3
+ let offsetMs = 0;
4
+ let frozenAt;
5
+ const now = () => frozenAt ?? source() + offsetMs;
6
+ return {
7
+ now,
8
+ set: (epochMs) => {
9
+ if (frozenAt !== void 0)
10
+ frozenAt = epochMs;
11
+ else
12
+ offsetMs = epochMs - source();
13
+ },
14
+ advance: (deltaMs) => {
15
+ if (frozenAt !== void 0)
16
+ frozenAt += deltaMs;
17
+ else
18
+ offsetMs += deltaMs;
19
+ },
20
+ freeze: () => {
21
+ frozenAt = now();
22
+ },
23
+ unfreeze: () => {
24
+ if (frozenAt === void 0)
25
+ return;
26
+ offsetMs = frozenAt - source();
27
+ frozenAt = void 0;
28
+ },
29
+ reset: () => {
30
+ offsetMs = 0;
31
+ frozenAt = void 0;
32
+ },
33
+ state: () => ({ now: now(), frozen: frozenAt !== void 0, offsetMs })
34
+ };
35
+ };
36
+
37
+ // ../core/dist/collection.js
38
+ var Collection = class {
39
+ sqlite;
40
+ namespace;
41
+ name;
42
+ constructor(sqlite, namespace, name) {
43
+ this.sqlite = sqlite;
44
+ this.namespace = namespace;
45
+ this.name = name;
46
+ }
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);
49
+ const next = (row?.value ?? 0) + 1;
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);
52
+ return next;
53
+ }
54
+ nextSequence() {
55
+ return this.sqlite.transaction(() => this.bumpCollectionSeq());
56
+ }
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);
59
+ if (!row)
60
+ return void 0;
61
+ return JSON.parse(row.value).value;
62
+ }
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);
65
+ return row !== void 0;
66
+ }
67
+ /** Insert a new record, assigning it the next sequence number. */
68
+ insert(id, value) {
69
+ return this.sqlite.transaction(() => {
70
+ const seq = this.bumpCollectionSeq();
71
+ const stored = { seq, value };
72
+ this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
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));
75
+ return stored;
76
+ });
77
+ }
78
+ /** Replace an existing record's value, keeping its position. */
79
+ update(id, value) {
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);
82
+ if (!row)
83
+ return void 0;
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);
86
+ return stored;
87
+ });
88
+ }
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);
91
+ return result.changes > 0;
92
+ }
93
+ /** How many records the collection holds, without reading them. */
94
+ count() {
95
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
96
+ return Number(row?.n ?? 0);
97
+ }
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);
100
+ const out = [];
101
+ for (const row of rows) {
102
+ const stored = JSON.parse(row.value);
103
+ if (options.where && !options.where(stored.value, stored.seq))
104
+ continue;
105
+ out.push({ id: row.id, seq: stored.seq, value: stored.value });
106
+ }
107
+ out.sort((a, b) => options.order === "oldest" ? a.seq - b.seq : b.seq - a.seq);
108
+ return out;
109
+ }
110
+ };
111
+
112
+ // ../core/dist/control.js
113
+ var HEALTH_PATH = "/health";
114
+ var ADMIN_PREFIX = "/__admin";
115
+ var ADMIN_KEY_HEADER = "x-mockingbird-admin-key";
116
+ var NAMESPACE_HEADER = "x-mockingbird-namespace";
117
+ var json = (status, body) => new Response(JSON.stringify(body), {
118
+ status,
119
+ headers: { "content-type": "application/json" }
120
+ });
121
+ var adminError = (status, message) => json(status, { error: { type: "mockingbird_admin", message } });
122
+ var UNITS = {
123
+ ms: 1,
124
+ s: 1e3,
125
+ m: 6e4,
126
+ h: 36e5,
127
+ d: 864e5
128
+ };
129
+ var parseDuration = (value) => {
130
+ if (typeof value === "number" && Number.isFinite(value))
131
+ return value;
132
+ if (typeof value !== "string")
133
+ return void 0;
134
+ const match = /^(-?\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(value.trim());
135
+ if (!match)
136
+ return void 0;
137
+ return Number(match[1]) * UNITS[match[2]];
138
+ };
139
+ var parseInstant = (value) => {
140
+ if (typeof value === "number" && Number.isFinite(value))
141
+ return value;
142
+ if (typeof value !== "string")
143
+ return void 0;
144
+ const parsed = Date.parse(value);
145
+ return Number.isNaN(parsed) ? void 0 : parsed;
146
+ };
147
+ var matchRoute = (pattern, path) => {
148
+ const want = pattern.split("/").filter(Boolean);
149
+ const have = path.split("/").filter(Boolean);
150
+ if (want.length !== have.length)
151
+ return void 0;
152
+ const params = {};
153
+ for (let i = 0; i < want.length; i++) {
154
+ const segment = want[i];
155
+ const actual = have[i];
156
+ if (segment.startsWith(":"))
157
+ params[segment.slice(1)] = decodeURIComponent(actual);
158
+ else if (segment !== actual)
159
+ return void 0;
160
+ }
161
+ return params;
162
+ };
163
+ var readJson = async (request) => {
164
+ const text = await request.text();
165
+ if (text.trim() === "")
166
+ return void 0;
167
+ return JSON.parse(text);
168
+ };
169
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
170
+ var createControlPlane = (context) => {
171
+ const snapshots = /* @__PURE__ */ new Map();
172
+ let snapshotCounter = 0;
173
+ const headerNamespace = (request) => request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace;
174
+ const adminNamespace = (request, url) => url.searchParams.get("namespace") ?? headerNamespace(request);
175
+ const builtin = {
176
+ "GET /": () => json(200, {
177
+ service: context.name,
178
+ routes: [...Object.keys(builtin), ...Object.keys(context.routes)].sort()
179
+ }),
180
+ "POST /reset": async ({ url, namespace }) => {
181
+ const target = url.searchParams.get("all") === "1" ? "*" : namespace;
182
+ await context.reset(target);
183
+ return json(200, { status: "ok", reset: target === "*" ? context.namespaces() : [target] });
184
+ },
185
+ "GET /namespaces": () => json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),
186
+ "GET /clock": () => json(200, context.clock.state()),
187
+ "POST /clock": ({ body }) => {
188
+ if (!isRecord(body))
189
+ return adminError(400, "expected a JSON object");
190
+ if (body.reset === true)
191
+ context.clock.reset();
192
+ if (body.set !== void 0) {
193
+ const instant = parseInstant(body.set);
194
+ if (instant === void 0)
195
+ return adminError(400, "set: expected epoch ms or ISO-8601");
196
+ context.clock.set(instant);
197
+ }
198
+ if (body.advance !== void 0) {
199
+ const delta = parseDuration(body.advance);
200
+ if (delta === void 0)
201
+ return adminError(400, 'advance: expected ms or "15m"-style');
202
+ context.clock.advance(delta);
203
+ }
204
+ if (body.freeze === true)
205
+ context.clock.freeze();
206
+ if (body.freeze === false)
207
+ context.clock.unfreeze();
208
+ return json(200, context.clock.state());
209
+ },
210
+ "GET /faults": () => json(200, { faults: context.faults.list() }),
211
+ "POST /faults": ({ body, namespace }) => {
212
+ if (isRecord(body) && typeof body.preset === "string") {
213
+ if (!context.applyPreset)
214
+ return adminError(400, `${context.name} has no fault presets`);
215
+ const { preset, ...overrides } = body;
216
+ try {
217
+ return json(201, {
218
+ preset,
219
+ rules: context.applyPreset(preset, namespace, overrides)
220
+ });
221
+ } catch (error) {
222
+ return adminError(404, error instanceof Error ? error.message : String(error));
223
+ }
224
+ }
225
+ if (!isRecord(body) || typeof body.status !== "number" && typeof body.delayMs !== "number" && typeof body.latencyMs !== "number" && body.drop !== true && typeof body.effect !== "string") {
226
+ return adminError(400, "a fault needs a numeric status, a delayMs/latencyMs, drop: true, an effect, or a preset");
227
+ }
228
+ const rule = {
229
+ // Scoped to the caller's namespace unless it asks for every one, so one worker's
230
+ // injected failure never lands on another's request.
231
+ namespace,
232
+ ...body,
233
+ id: typeof body.id === "string" ? body.id : `fault_${context.faults.list().length + 1}`
234
+ };
235
+ return json(201, context.faults.add(rule));
236
+ },
237
+ "DELETE /faults": ({ url }) => {
238
+ const id = url.searchParams.get("id");
239
+ if (id === null) {
240
+ context.faults.clear();
241
+ return json(200, { status: "ok" });
242
+ }
243
+ return context.faults.remove(id) ? json(200, { status: "ok" }) : adminError(404, `no fault ${id}`);
244
+ },
245
+ "POST /snapshots": ({ namespace }) => {
246
+ const point = context.timeTravel.checkpoint(namespace, "main");
247
+ context.timeTravel.retain(namespace, point.id);
248
+ snapshotCounter++;
249
+ const id = `snap_${snapshotCounter}`;
250
+ snapshots.set(id, { namespace, checkpoint: point.id });
251
+ return json(201, { id, namespace, records: point.records ?? 0 });
252
+ },
253
+ "POST /snapshots/:id/restore": ({ params, namespace }) => {
254
+ const alias = snapshots.get(params.id);
255
+ if (!alias)
256
+ return adminError(404, `no snapshot ${params.id}`);
257
+ if (alias.namespace !== namespace) {
258
+ return adminError(409, `snapshot ${params.id} belongs to namespace ${alias.namespace}`);
259
+ }
260
+ context.timeTravel.checkout(alias.checkpoint, { namespace, branch: "main" });
261
+ return json(200, { status: "ok", id: params.id, namespace });
262
+ },
263
+ "DELETE /snapshots/:id": ({ params }) => {
264
+ const id = params.id;
265
+ const alias = snapshots.get(id);
266
+ if (!alias)
267
+ return adminError(404, `no snapshot ${id}`);
268
+ snapshots.delete(id);
269
+ context.timeTravel.release(alias.namespace, alias.checkpoint);
270
+ return json(200, { status: "ok" });
271
+ },
272
+ "GET /timeline": ({ namespace }) => json(200, context.timeTravel.inspect(namespace)),
273
+ "POST /checkpoints": ({ body, namespace }) => {
274
+ const branch = isRecord(body) && typeof body.branch === "string" ? body.branch : "main";
275
+ try {
276
+ return json(201, context.timeTravel.checkpoint(namespace, branch));
277
+ } catch (error) {
278
+ return adminError(409, error instanceof Error ? error.message : String(error));
279
+ }
280
+ },
281
+ "POST /branches/:name": ({ params, body, namespace }) => {
282
+ const at = isRecord(body) && typeof body.at === "string" ? body.at : void 0;
283
+ try {
284
+ return json(201, context.timeTravel.branch(params.name, {
285
+ namespace,
286
+ ...at !== void 0 ? { at } : {}
287
+ }));
288
+ } catch (error) {
289
+ return adminError(409, error instanceof Error ? error.message : String(error));
290
+ }
291
+ },
292
+ "POST /branches/:name/checkout": ({ params, body, namespace }) => {
293
+ if (!isRecord(body) || typeof body.checkpoint !== "string") {
294
+ return adminError(400, 'expected {"checkpoint":"cp_..."}');
295
+ }
296
+ try {
297
+ context.timeTravel.checkout(body.checkpoint, {
298
+ namespace,
299
+ branch: params.name
300
+ });
301
+ return json(200, { status: "ok", branch: params.name, checkpoint: body.checkpoint });
302
+ } catch (error) {
303
+ return adminError(409, error instanceof Error ? error.message : String(error));
304
+ }
305
+ },
306
+ "GET /requests": ({ url, namespace }) => {
307
+ const status = url.searchParams.get("status");
308
+ const since = url.searchParams.get("since");
309
+ const limit = url.searchParams.get("limit");
310
+ const sinceMs = since === null ? void 0 : parseInstant(/^\d+$/.test(since) ? Number(since) : since);
311
+ if (since !== null && sinceMs === void 0) {
312
+ return adminError(400, "since: expected epoch ms or ISO-8601");
313
+ }
314
+ if (status !== null && !/^\d{3}$/.test(status))
315
+ return adminError(400, "status: expected an HTTP status");
316
+ if (limit !== null && !/^\d+$/.test(limit))
317
+ return adminError(400, "limit: expected a count");
318
+ const operationId = url.searchParams.get("operationId");
319
+ const everyNamespace = url.searchParams.get("all") === "1";
320
+ return json(200, {
321
+ size: context.journal.size,
322
+ requests: context.journal.list({
323
+ ...everyNamespace ? {} : { namespace },
324
+ ...operationId !== null ? { operationId } : {},
325
+ ...status !== null ? { status: Number(status) } : {},
326
+ ...sinceMs !== void 0 ? { since: sinceMs } : {},
327
+ ...limit !== null ? { limit: Number(limit) } : {}
328
+ })
329
+ });
330
+ },
331
+ "DELETE /requests": ({ url, namespace }) => {
332
+ context.journal.clear(url.searchParams.get("all") === "1" ? void 0 : namespace);
333
+ return json(200, { status: "ok" });
334
+ },
335
+ "GET /metrics": () => json(200, context.metrics.report()),
336
+ "DELETE /metrics": () => {
337
+ context.metrics.reset();
338
+ return json(200, { status: "ok" });
339
+ }
340
+ };
341
+ const routes = [...Object.entries(context.routes), ...Object.entries(builtin)].map(([key, handler]) => {
342
+ const space = key.indexOf(" ");
343
+ return { method: key.slice(0, space), pattern: key.slice(space + 1), handler };
344
+ });
345
+ return {
346
+ namespaceOf: headerNamespace,
347
+ async handle(request) {
348
+ const url = new URL(request.url);
349
+ if (url.pathname === HEALTH_PATH && request.method === "GET") {
350
+ return json(200, {
351
+ status: "ok",
352
+ service: context.name,
353
+ uptimeMs: context.wallNow() - context.startedAt,
354
+ clock: context.clock.state(),
355
+ namespaces: context.namespaces().length,
356
+ ...context.describe()
357
+ });
358
+ }
359
+ if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
360
+ return void 0;
361
+ }
362
+ if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
+ return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
364
+ }
365
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
366
+ for (const route of routes) {
367
+ if (route.method !== request.method)
368
+ continue;
369
+ const params = matchRoute(route.pattern, path);
370
+ if (!params)
371
+ continue;
372
+ let body;
373
+ try {
374
+ body = await readJson(request);
375
+ } catch {
376
+ return adminError(400, "request body is not valid JSON");
377
+ }
378
+ return route.handler({
379
+ request,
380
+ url,
381
+ params,
382
+ namespace: adminNamespace(request, url),
383
+ body
384
+ });
385
+ }
386
+ return adminError(404, `no admin route ${request.method} ${path}; GET ${ADMIN_PREFIX} lists them`);
387
+ }
388
+ };
389
+ };
390
+
391
+ // ../core/dist/credentials.js
392
+ var bearerToken = (request) => {
393
+ const header = request.headers.get("authorization");
394
+ if (!header)
395
+ return void 0;
396
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim());
397
+ return match?.[1]?.trim() || void 0;
398
+ };
399
+ var createCredentialRegistry = () => {
400
+ const map = /* @__PURE__ */ new Map();
401
+ return {
402
+ set: (credential, namespace) => {
403
+ map.set(credential, namespace);
404
+ },
405
+ get: (credential) => map.get(credential),
406
+ remove: (credential) => map.delete(credential),
407
+ clear: () => map.clear(),
408
+ entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
409
+ };
410
+ };
411
+ var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
412
+
413
+ // ../core/dist/rng.js
414
+ var seedFrom = (value) => {
415
+ let hash = 2166136261;
416
+ for (let i = 0; i < value.length; i++) {
417
+ hash ^= value.charCodeAt(i);
418
+ hash = Math.imul(hash, 16777619);
419
+ }
420
+ return hash >>> 0;
421
+ };
422
+ var createRng = (seed = 0) => {
423
+ const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
424
+ let state = numeric;
425
+ const next = () => {
426
+ state = state + 1831565813 >>> 0;
427
+ let t = state;
428
+ t = Math.imul(t ^ t >>> 15, t | 1);
429
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
430
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
431
+ };
432
+ return {
433
+ next,
434
+ int: (min, max) => min + Math.floor(next() * (max - min + 1)),
435
+ reset: () => {
436
+ state = numeric;
437
+ },
438
+ state: () => state,
439
+ setState: (next2) => {
440
+ if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
441
+ throw new RangeError("rng state must be an unsigned 32-bit integer");
442
+ }
443
+ state = next2 >>> 0;
444
+ },
445
+ seed: numeric
446
+ };
447
+ };
448
+
449
+ // ../core/dist/faults.js
450
+ var matches = (rule, candidate) => {
451
+ if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
452
+ return false;
453
+ }
454
+ if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
455
+ return false;
456
+ if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
457
+ return false;
458
+ }
459
+ if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
460
+ return false;
461
+ return true;
462
+ };
463
+ var faultResponse = (rule) => {
464
+ const status = rule.status ?? 500;
465
+ const headers = { "content-type": "application/json", ...rule.headers };
466
+ if (typeof rule.body === "string")
467
+ return new Response(rule.body, { status, headers });
468
+ if (rule.body === null)
469
+ return new Response(null, { status, headers: rule.headers ?? {} });
470
+ const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
471
+ return new Response(JSON.stringify(body), { status, headers });
472
+ };
473
+ var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
474
+ const entries = [];
475
+ return {
476
+ add(rule) {
477
+ const existing = entries.findIndex((e) => e.rule.id === rule.id);
478
+ const entry = { rule, remaining: rule.count ?? null, hits: 0 };
479
+ if (existing >= 0)
480
+ entries[existing] = entry;
481
+ else
482
+ entries.push(entry);
483
+ return rule;
484
+ },
485
+ list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
486
+ remove(id) {
487
+ const index = entries.findIndex((e) => e.rule.id === id);
488
+ if (index < 0)
489
+ return false;
490
+ entries.splice(index, 1);
491
+ return true;
492
+ },
493
+ clear() {
494
+ entries.length = 0;
495
+ },
496
+ async take(candidate) {
497
+ const hits = [];
498
+ for (const entry of entries) {
499
+ if (entry.remaining === 0)
500
+ continue;
501
+ if (!matches(entry.rule, candidate))
502
+ continue;
503
+ const rate = entry.rule.rate ?? 1;
504
+ if (rng.next() >= rate)
505
+ continue;
506
+ entry.hits++;
507
+ if (entry.remaining !== null)
508
+ entry.remaining--;
509
+ const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
510
+ if (delay !== void 0 && delay > 0) {
511
+ await sleep(delay);
512
+ }
513
+ const hit = { id: entry.rule.id };
514
+ if (entry.rule.effect !== void 0) {
515
+ hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
516
+ }
517
+ if (entry.rule.drop === true)
518
+ hit.drop = true;
519
+ else if (entry.rule.status !== void 0)
520
+ hit.response = faultResponse(entry.rule);
521
+ hits.push(hit);
522
+ if (hit.drop || hit.response)
523
+ break;
524
+ }
525
+ return hits;
526
+ }
527
+ };
528
+ };
529
+
530
+ // ../../openapi/core/dist/refs.js
531
+ var OpenAPIReferenceError = class extends Error {
532
+ ref;
533
+ constructor(ref) {
534
+ super(`unresolvable $ref: ${ref}`);
535
+ this.ref = ref;
536
+ this.name = "OpenAPIReferenceError";
537
+ }
538
+ };
539
+ var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
540
+ var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
541
+ var resolveRef = (document2, ref) => {
542
+ if (!ref.startsWith("#/"))
543
+ throw new OpenAPIReferenceError(ref);
544
+ let cursor = document2;
545
+ for (const raw of ref.slice(2).split("/")) {
546
+ const segment = unescapePointer(raw);
547
+ if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
548
+ throw new OpenAPIReferenceError(ref);
549
+ }
550
+ cursor = cursor[segment];
551
+ }
552
+ if (cursor === void 0)
553
+ throw new OpenAPIReferenceError(ref);
554
+ return cursor;
555
+ };
556
+ var deref = (document2, value) => {
557
+ let current = value;
558
+ const seen = /* @__PURE__ */ new Set();
559
+ while (isReference(current)) {
560
+ if (seen.has(current.$ref))
561
+ throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
562
+ seen.add(current.$ref);
563
+ current = resolveRef(document2, current.$ref);
564
+ }
565
+ return current;
566
+ };
567
+
568
+ // ../../openapi/core/dist/types.js
569
+ var HTTP_METHODS = [
570
+ "get",
571
+ "put",
572
+ "post",
573
+ "delete",
574
+ "options",
575
+ "head",
576
+ "patch",
577
+ "trace"
578
+ ];
579
+
580
+ // ../../openapi/core/dist/document.js
581
+ var mergeParameters = (document2, item, own) => {
582
+ const merged = /* @__PURE__ */ new Map();
583
+ for (const raw of item.parameters ?? []) {
584
+ const parameter = deref(document2, raw);
585
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
586
+ }
587
+ for (const raw of own ?? []) {
588
+ const parameter = deref(document2, raw);
589
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
590
+ }
591
+ return [...merged.values()];
592
+ };
593
+ var listOperations = (document2) => {
594
+ const operations = [];
595
+ for (const [path, item] of Object.entries(document2.paths)) {
596
+ for (const method of HTTP_METHODS) {
597
+ const operation = item[method];
598
+ if (operation?.operationId === void 0)
599
+ continue;
600
+ const responses = {};
601
+ for (const [status, response] of Object.entries(operation.responses)) {
602
+ responses[status] = deref(document2, response);
603
+ }
604
+ operations.push({
605
+ operationId: operation.operationId,
606
+ method,
607
+ path,
608
+ operation,
609
+ parameters: mergeParameters(document2, item, operation.parameters),
610
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
611
+ responses
612
+ });
613
+ }
614
+ }
615
+ return operations;
616
+ };
617
+
618
+ // ../../openapi/core/dist/schema.js
619
+ var resolveSchema = (document2, schema) => {
620
+ let current = schema;
621
+ const seen = /* @__PURE__ */ new Set();
622
+ while (typeof current.$ref === "string") {
623
+ const ref = current.$ref;
624
+ if (seen.has(ref))
625
+ break;
626
+ seen.add(ref);
627
+ const { $ref: _ignored, ...siblings } = current;
628
+ const target = resolveRef(document2, ref);
629
+ current = { ...target, ...siblings };
630
+ }
631
+ if (current.nullable === true) {
632
+ const { nullable: _nullable, ...rest } = current;
633
+ const types = schemaTypes(rest);
634
+ if (types.length > 0 && !types.includes("null"))
635
+ current = { ...rest, type: [...types, "null"] };
636
+ else
637
+ current = rest;
638
+ }
639
+ return current;
640
+ };
641
+ var schemaTypes = (schema) => {
642
+ if (Array.isArray(schema.type))
643
+ return schema.type;
644
+ if (schema.type !== void 0)
645
+ return [schema.type];
646
+ const inferred = [];
647
+ if (schema.properties || schema.required || schema.additionalProperties !== void 0)
648
+ inferred.push("object");
649
+ if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
650
+ inferred.push("array");
651
+ if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
652
+ inferred.push("string");
653
+ if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
654
+ inferred.push("number");
655
+ return inferred;
656
+ };
657
+ var jsonTypeOf = (value) => {
658
+ if (value === null)
659
+ return "null";
660
+ if (Array.isArray(value))
661
+ return "array";
662
+ switch (typeof value) {
663
+ case "string":
664
+ return "string";
665
+ case "boolean":
666
+ return "boolean";
667
+ case "number":
668
+ return Number.isInteger(value) ? "integer" : "number";
669
+ case "object":
670
+ return "object";
671
+ default:
672
+ return "undefined";
673
+ }
674
+ };
675
+ var deepEqual = (a, b) => {
676
+ if (a === b)
677
+ return true;
678
+ if (typeof a !== typeof b || a === null || b === null)
679
+ return false;
680
+ if (Array.isArray(a)) {
681
+ return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
682
+ }
683
+ if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
684
+ const ka = Object.keys(a);
685
+ const kb = Object.keys(b);
686
+ return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
687
+ }
688
+ return false;
689
+ };
690
+ var FORMAT_PATTERNS = {
691
+ uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
692
+ date: /^\d{4}-\d{2}-\d{2}$/,
693
+ "date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
694
+ email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
695
+ uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
696
+ ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
697
+ };
698
+ var graphemeLength = (value) => [...value].length;
699
+ var validateValue = (document2, schema, value, path = []) => {
700
+ const errors = [];
701
+ const s = resolveSchema(document2, schema);
702
+ const fail = (message) => errors.push({ path, message });
703
+ const actual = jsonTypeOf(value);
704
+ if (actual === "undefined") {
705
+ fail("value is undefined");
706
+ return errors;
707
+ }
708
+ const types = schemaTypes(s);
709
+ if (types.length > 0) {
710
+ const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
711
+ if (!ok) {
712
+ fail(`expected type ${types.join("|")}, got ${actual}`);
713
+ return errors;
714
+ }
715
+ }
716
+ if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
717
+ fail("value not in enum");
718
+ }
719
+ if (s.const !== void 0 && !deepEqual(s.const, value))
720
+ fail("value does not equal const");
721
+ if (typeof value === "string") {
722
+ const length = graphemeLength(value);
723
+ if (s.minLength !== void 0 && length < s.minLength)
724
+ fail(`length ${length} < minLength ${s.minLength}`);
725
+ if (s.maxLength !== void 0 && length > s.maxLength)
726
+ fail(`length ${length} > maxLength ${s.maxLength}`);
727
+ if (s.pattern !== void 0) {
728
+ try {
729
+ if (!new RegExp(s.pattern, "u").test(value))
730
+ fail(`does not match pattern ${s.pattern}`);
731
+ } catch {
732
+ }
733
+ }
734
+ if (s.format !== void 0) {
735
+ const pattern = FORMAT_PATTERNS[s.format];
736
+ if (pattern && !pattern.test(value))
737
+ fail(`does not match format ${s.format}`);
738
+ }
739
+ }
740
+ if (typeof value === "number") {
741
+ if (s.minimum !== void 0 && value < s.minimum)
742
+ fail(`${value} < minimum ${s.minimum}`);
743
+ if (s.maximum !== void 0 && value > s.maximum)
744
+ fail(`${value} > maximum ${s.maximum}`);
745
+ if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
746
+ fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
747
+ if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
748
+ fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
749
+ if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
750
+ fail(`${value} is not a multiple of ${s.multipleOf}`);
751
+ }
752
+ }
753
+ if (Array.isArray(value)) {
754
+ if (s.minItems !== void 0 && value.length < s.minItems)
755
+ fail(`${value.length} items < minItems ${s.minItems}`);
756
+ if (s.maxItems !== void 0 && value.length > s.maxItems)
757
+ fail(`${value.length} items > maxItems ${s.maxItems}`);
758
+ if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
759
+ fail("items are not unique");
760
+ value.forEach((item, i) => {
761
+ const itemSchema = s.prefixItems?.[i] ?? s.items;
762
+ if (itemSchema)
763
+ errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
764
+ });
765
+ }
766
+ if (actual === "object") {
767
+ const record = value;
768
+ const keys = Object.keys(record);
769
+ for (const name of s.required ?? [])
770
+ if (!(name in record))
771
+ fail(`missing required property ${name}`);
772
+ if (s.minProperties !== void 0 && keys.length < s.minProperties)
773
+ fail(`${keys.length} properties < minProperties ${s.minProperties}`);
774
+ if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
775
+ fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
776
+ for (const key of keys) {
777
+ const property = s.properties?.[key];
778
+ if (property) {
779
+ errors.push(...validateValue(document2, property, record[key], [...path, key]));
780
+ continue;
781
+ }
782
+ if (s.additionalProperties === false)
783
+ fail(`unexpected property ${key}`);
784
+ else if (typeof s.additionalProperties === "object") {
785
+ errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
786
+ }
787
+ if (s.propertyNames) {
788
+ const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
789
+ if (nameErrors.length > 0)
790
+ fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
791
+ }
792
+ }
793
+ }
794
+ if (s.allOf)
795
+ for (const branch of s.allOf)
796
+ errors.push(...validateValue(document2, branch, value, path));
797
+ if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
798
+ fail("matches no anyOf branch");
799
+ if (s.oneOf) {
800
+ const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
801
+ if (matches2 !== 1)
802
+ fail(`matches ${matches2} oneOf branches, expected exactly 1`);
803
+ }
804
+ if (s.not && validateValue(document2, s.not, value).length === 0)
805
+ fail("matches forbidden `not` schema");
806
+ return errors;
807
+ };
808
+
809
+ // ../../http/codec/dist/form.js
810
+ var parsePath = (rawKey) => {
811
+ const open = rawKey.indexOf("[");
812
+ if (open === -1)
813
+ return [rawKey];
814
+ const path = [rawKey.slice(0, open)];
815
+ const rest = rawKey.slice(open);
816
+ const pattern = /\[([^\]]*)\]/g;
817
+ let match = pattern.exec(rest);
818
+ let consumed = 0;
819
+ while (match !== null) {
820
+ if (match.index !== consumed)
821
+ return [rawKey];
822
+ path.push(match[1] ?? "");
823
+ consumed = match.index + match[0].length;
824
+ match = pattern.exec(rest);
825
+ }
826
+ if (consumed !== rest.length)
827
+ return [rawKey];
828
+ return path;
829
+ };
830
+ var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
831
+ var put = (target, key, value) => {
832
+ if (key === "__proto__") {
833
+ Object.defineProperty(target, key, {
834
+ value,
835
+ enumerable: true,
836
+ writable: true,
837
+ configurable: true
838
+ });
839
+ return;
840
+ }
841
+ ;
842
+ target[key] = value;
843
+ };
844
+ var assign = (target, path, value) => {
845
+ let cursor = target;
846
+ for (let i = 0; i < path.length; i++) {
847
+ const segment = path[i];
848
+ const last = i === path.length - 1;
849
+ if (Array.isArray(cursor)) {
850
+ const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
851
+ if (index === void 0)
852
+ return;
853
+ if (last) {
854
+ put(cursor, index, value);
855
+ return;
856
+ }
857
+ const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
858
+ if (next === void 0 || typeof next === "string") {
859
+ const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
860
+ put(cursor, index, created);
861
+ cursor = created;
862
+ } else {
863
+ cursor = next;
864
+ }
865
+ continue;
866
+ }
867
+ if (typeof cursor === "string")
868
+ return;
869
+ if (last) {
870
+ put(cursor, segment, value);
871
+ return;
872
+ }
873
+ const nextSegment = path[i + 1];
874
+ const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
875
+ if (existing === void 0 || typeof existing === "string") {
876
+ const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
877
+ put(cursor, segment, created);
878
+ cursor = created;
879
+ } else {
880
+ cursor = existing;
881
+ }
882
+ }
883
+ };
884
+ var decodeFormPairs = (pairs) => {
885
+ const out = {};
886
+ for (const [rawKey, value] of pairs)
887
+ assign(out, parsePath(rawKey), value);
888
+ return densify(out);
889
+ };
890
+ var densify = (value) => {
891
+ if (typeof value === "string")
892
+ return value;
893
+ if (Array.isArray(value))
894
+ return value.filter((item) => item !== void 0).map(densify);
895
+ const out = {};
896
+ for (const [key, item] of Object.entries(value))
897
+ put(out, key, densify(item));
898
+ return out;
899
+ };
900
+ var decodeForm = (text) => {
901
+ const source = text.startsWith("?") ? text.slice(1) : text;
902
+ return decodeFormPairs(new URLSearchParams(source).entries());
903
+ };
904
+
905
+ // ../../http/codec/dist/content.js
906
+ var JSON_MEDIA_TYPE = "application/json";
907
+ var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
908
+ var mediaTypeOf = (contentType) => {
909
+ if (!contentType)
910
+ return void 0;
911
+ const essence = contentType.split(";")[0]?.trim().toLowerCase();
912
+ return essence ? essence : void 0;
913
+ };
914
+ var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
915
+ var utf8 = new TextDecoder("utf-8", { fatal: false });
916
+ var decodeBody = (contentType, bytes) => {
917
+ if (bytes.byteLength === 0)
918
+ return { kind: "empty" };
919
+ const mediaType = mediaTypeOf(contentType);
920
+ if (mediaType === void 0)
921
+ return { kind: "bytes", value: bytes };
922
+ if (isJsonMediaType(mediaType)) {
923
+ const text = utf8.decode(bytes);
924
+ try {
925
+ return { kind: "json", value: JSON.parse(text) };
926
+ } catch (error) {
927
+ return {
928
+ kind: "invalid",
929
+ mediaType,
930
+ text,
931
+ error: error instanceof Error ? error.message : String(error)
932
+ };
933
+ }
934
+ }
935
+ if (mediaType === FORM_MEDIA_TYPE) {
936
+ return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
937
+ }
938
+ if (mediaType.startsWith("text/"))
939
+ return { kind: "text", value: utf8.decode(bytes) };
940
+ return { kind: "bytes", value: bytes };
941
+ };
942
+ var readBody = async (message) => {
943
+ const bytes = new Uint8Array(await message.arrayBuffer());
944
+ return decodeBody(message.headers.get("content-type"), bytes);
945
+ };
946
+
947
+ // ../core/dist/http.js
948
+ var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
949
+ status,
950
+ headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
951
+ });
952
+ var HttpError = class extends Error {
953
+ status;
954
+ body;
955
+ headers;
956
+ constructor(status, body, headers = {}) {
957
+ super(`HTTP ${status}`);
958
+ this.status = status;
959
+ this.body = body;
960
+ this.headers = headers;
961
+ this.name = "HttpError";
962
+ }
963
+ toResponse() {
964
+ const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
965
+ if (contentType === "text/plain") {
966
+ return new Response(String(this.body), {
967
+ status: this.status,
968
+ headers: this.headers
969
+ });
970
+ }
971
+ return jsonRes(this.status, this.body, this.headers);
972
+ }
973
+ };
974
+
975
+ // ../core/dist/ids.js
976
+ var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
977
+ var mix = (input) => {
978
+ let hash = 2166136261;
979
+ for (let i = 0; i < input.length; i++) {
980
+ hash ^= input.charCodeAt(i);
981
+ hash = Math.imul(hash, 16777619) >>> 0;
982
+ }
983
+ hash ^= hash >>> 16;
984
+ hash = Math.imul(hash, 2246822507) >>> 0;
985
+ hash ^= hash >>> 13;
986
+ return hash >>> 0;
987
+ };
988
+ var opaqueToken = (input, length) => {
989
+ let out = "";
990
+ let round2 = 0;
991
+ while (out.length < length) {
992
+ let hash = mix(`${input}:${round2++}`);
993
+ for (let i = 0; i < 5 && out.length < length; i++) {
994
+ out += ALPHABET.charAt(hash % ALPHABET.length);
995
+ hash = Math.floor(hash / ALPHABET.length);
996
+ }
997
+ }
998
+ return out;
999
+ };
1000
+ var IdSequence = class {
1001
+ sqlite;
1002
+ namespace;
1003
+ salt;
1004
+ constructor(sqlite, namespace, salt = "mockingbird") {
1005
+ this.sqlite = sqlite;
1006
+ this.namespace = namespace;
1007
+ this.salt = salt;
1008
+ }
1009
+ next(prefix, length = 14) {
1010
+ return this.sqlite.transaction(() => {
1011
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'").get(this.namespace, prefix);
1012
+ const value = (row?.value ?? 0) + 1;
1013
+ this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)
1014
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, prefix, value);
1015
+ return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`;
1016
+ });
1017
+ }
1018
+ };
1019
+
1020
+ // ../core/dist/journal.js
1021
+ var DEFAULT_JOURNAL_SIZE = 1e3;
1022
+ var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
1023
+ const capacity = Math.max(0, Math.floor(size));
1024
+ const rings = /* @__PURE__ */ new Map();
1025
+ let sequence = 0;
1026
+ const order = /* @__PURE__ */ new WeakMap();
1027
+ const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
1028
+ return {
1029
+ size: capacity,
1030
+ record(entry) {
1031
+ if (capacity === 0)
1032
+ return;
1033
+ order.set(entry, sequence++);
1034
+ let ring = rings.get(entry.namespace);
1035
+ if (!ring) {
1036
+ ring = { entries: [], next: 0 };
1037
+ rings.set(entry.namespace, ring);
1038
+ }
1039
+ if (ring.entries.length < capacity)
1040
+ ring.entries.push(entry);
1041
+ else {
1042
+ ring.entries[ring.next] = entry;
1043
+ ring.next = (ring.next + 1) % capacity;
1044
+ }
1045
+ },
1046
+ list(query = {}) {
1047
+ const source = query.namespace !== void 0 ? inOrder(rings.get(query.namespace) ?? { entries: [], next: 0 }) : [...rings.values()].flatMap(inOrder).sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0));
1048
+ const matched = source.filter((entry) => (query.operationId === void 0 || entry.operationId === query.operationId) && (query.status === void 0 || entry.status === query.status) && (query.since === void 0 || Date.parse(entry.at) >= query.since));
1049
+ return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
1050
+ },
1051
+ clear(namespace) {
1052
+ if (namespace === void 0)
1053
+ rings.clear();
1054
+ else
1055
+ rings.delete(namespace);
1056
+ }
1057
+ };
1058
+ };
1059
+ var notes = /* @__PURE__ */ new WeakMap();
1060
+ var annotateResponse = (response, extra) => {
1061
+ const existing = notes.get(response);
1062
+ notes.set(response, {
1063
+ ...existing,
1064
+ ...extra,
1065
+ ...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
1066
+ });
1067
+ return response;
1068
+ };
1069
+ var responseNotes = (response) => notes.get(response);
1070
+
1071
+ // ../core/dist/metrics.js
1072
+ var createMetrics = () => {
1073
+ let requests = 0;
1074
+ let faults = 0;
1075
+ let totalDurationMs = 0;
1076
+ const byOperation = /* @__PURE__ */ new Map();
1077
+ const unmatched = /* @__PURE__ */ new Map();
1078
+ return {
1079
+ record(entry) {
1080
+ requests++;
1081
+ totalDurationMs += entry.durationMs;
1082
+ if (entry.faultId !== void 0)
1083
+ faults++;
1084
+ const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
1085
+ byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
1086
+ if (entry.unmatched) {
1087
+ const route = `${entry.method} ${entry.path}`;
1088
+ unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
1089
+ }
1090
+ },
1091
+ report: () => ({
1092
+ requests,
1093
+ byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
1094
+ unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
1095
+ const space = route.indexOf(" ");
1096
+ return { method: route.slice(0, space), path: route.slice(space + 1), count };
1097
+ }),
1098
+ faults,
1099
+ totalDurationMs
1100
+ }),
1101
+ reset() {
1102
+ requests = 0;
1103
+ faults = 0;
1104
+ totalDurationMs = 0;
1105
+ byOperation.clear();
1106
+ unmatched.clear();
1107
+ }
1108
+ };
1109
+ };
1110
+
1111
+ // ../../core/dist/timeline.js
1112
+ var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1113
+ var Timeline = class {
1114
+ maxCheckpoints;
1115
+ now;
1116
+ makeId;
1117
+ nodes = /* @__PURE__ */ new Map();
1118
+ heads = /* @__PURE__ */ new Map();
1119
+ /** Unreferenced nodes in the exact order they became collectible. */
1120
+ evictable = /* @__PURE__ */ new Set();
1121
+ /** Branch heads plus explicit retainers. Absent means zero. */
1122
+ references = /* @__PURE__ */ new Map();
1123
+ explicitPins = /* @__PURE__ */ new Map();
1124
+ sequence = 0;
1125
+ constructor(options = {}) {
1126
+ const max = options.maxCheckpoints ?? 1e3;
1127
+ if (!Number.isSafeInteger(max) || max < 1)
1128
+ throw new RangeError("maxCheckpoints must be a positive integer");
1129
+ this.maxCheckpoints = max;
1130
+ this.now = options.now ?? (() => this.sequence);
1131
+ this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
1132
+ }
1133
+ /** Capture a new immutable value and move `branch` to it. */
1134
+ commit(value, options = {}) {
1135
+ const branch = options.branch ?? "main";
1136
+ this.assertBranch(branch);
1137
+ const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
1138
+ if (parent !== null && !this.nodes.has(parent))
1139
+ throw new RangeError(`no checkpoint ${parent}`);
1140
+ const id = this.makeId(++this.sequence);
1141
+ if (this.nodes.has(id))
1142
+ throw new RangeError(`duplicate checkpoint id ${id}`);
1143
+ const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
1144
+ this.nodes.set(id, checkpoint);
1145
+ this.moveHead(branch, id);
1146
+ this.collect(this.maxCheckpoints);
1147
+ return checkpoint;
1148
+ }
1149
+ /** Create a branch pointer without copying its checkpoint value. */
1150
+ fork(branch, options = {}) {
1151
+ this.assertBranch(branch);
1152
+ if (this.heads.has(branch))
1153
+ throw new RangeError(`branch already exists: ${branch}`);
1154
+ const from = options.from ?? this.heads.get("main");
1155
+ if (from === void 0)
1156
+ return void 0;
1157
+ const checkpoint = this.get(from);
1158
+ this.moveHead(branch, checkpoint.id);
1159
+ return checkpoint;
1160
+ }
1161
+ /** Move a branch pointer to an existing checkpoint. */
1162
+ checkout(branch, id) {
1163
+ this.assertBranch(branch);
1164
+ const checkpoint = this.get(id);
1165
+ this.moveHead(branch, checkpoint.id);
1166
+ return checkpoint;
1167
+ }
1168
+ get(id) {
1169
+ const checkpoint = this.nodes.get(id);
1170
+ if (!checkpoint)
1171
+ throw new RangeError(`no checkpoint ${id}`);
1172
+ return checkpoint;
1173
+ }
1174
+ head(branch = "main") {
1175
+ const id = this.heads.get(branch);
1176
+ return id === void 0 ? void 0 : this.get(id);
1177
+ }
1178
+ hasBranch(branch) {
1179
+ return this.heads.has(branch);
1180
+ }
1181
+ branches() {
1182
+ return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
1183
+ }
1184
+ checkpoints() {
1185
+ return [...this.nodes.values()];
1186
+ }
1187
+ /** Number of retained checkpoints without allocating an array. */
1188
+ get size() {
1189
+ return this.nodes.size;
1190
+ }
1191
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
1192
+ retain(id) {
1193
+ const checkpoint = this.get(id);
1194
+ this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
1195
+ this.addReference(id);
1196
+ return checkpoint;
1197
+ }
1198
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
1199
+ release(id) {
1200
+ if (!this.nodes.has(id))
1201
+ return false;
1202
+ const pins = this.explicitPins.get(id) ?? 0;
1203
+ if (pins === 0)
1204
+ return false;
1205
+ if (pins === 1)
1206
+ this.explicitPins.delete(id);
1207
+ else
1208
+ this.explicitPins.set(id, pins - 1);
1209
+ this.removeReference(id);
1210
+ this.collect(this.maxCheckpoints);
1211
+ return true;
1212
+ }
1213
+ deleteBranch(branch) {
1214
+ if (branch === "main")
1215
+ throw new RangeError("cannot delete main branch");
1216
+ const previous = this.heads.get(branch);
1217
+ const deleted = this.heads.delete(branch);
1218
+ if (previous !== void 0)
1219
+ this.removeReference(previous);
1220
+ this.collect(this.maxCheckpoints);
1221
+ return deleted;
1222
+ }
1223
+ /**
1224
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
1225
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
1226
+ * storage dependency, so a retained node remains usable after pruning.
1227
+ */
1228
+ gc(max = this.maxCheckpoints) {
1229
+ if (!Number.isSafeInteger(max) || max < 1)
1230
+ throw new RangeError("max must be a positive integer");
1231
+ const removed = [];
1232
+ this.collect(max, removed);
1233
+ return removed;
1234
+ }
1235
+ collect(max, removed) {
1236
+ while (this.nodes.size > max && this.evictable.size > 0) {
1237
+ const id = this.evictable.values().next().value;
1238
+ this.evictable.delete(id);
1239
+ this.nodes.delete(id);
1240
+ removed?.push(id);
1241
+ }
1242
+ }
1243
+ moveHead(branch, id) {
1244
+ const previous = this.heads.get(branch);
1245
+ if (previous === id)
1246
+ return;
1247
+ if (previous !== void 0)
1248
+ this.removeReference(previous);
1249
+ this.heads.set(branch, id);
1250
+ this.addReference(id);
1251
+ }
1252
+ addReference(id) {
1253
+ this.references.set(id, (this.references.get(id) ?? 0) + 1);
1254
+ this.evictable.delete(id);
1255
+ }
1256
+ removeReference(id) {
1257
+ const next = (this.references.get(id) ?? 0) - 1;
1258
+ if (next > 0)
1259
+ this.references.set(id, next);
1260
+ else {
1261
+ this.references.delete(id);
1262
+ if (this.nodes.has(id))
1263
+ this.evictable.add(id);
1264
+ }
1265
+ }
1266
+ assertBranch(branch) {
1267
+ if (!BRANCH_PATTERN.test(branch))
1268
+ throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
1269
+ }
1270
+ };
1271
+
1272
+ // ../../sqlite/dist/default.js
1273
+ import { Database } from "@crvouga/mockingbird-service-sqlite";
1274
+ var createDefaultSqlite = () => new Database();
1275
+ var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
1276
+
1277
+ // ../../sqlite/dist/migrate.js
1278
+ var ensureMigrationsTable = (sqlite) => {
1279
+ sqlite.exec(`
1280
+ CREATE TABLE IF NOT EXISTS schema_migrations (
1281
+ id TEXT PRIMARY KEY NOT NULL,
1282
+ applied_at INTEGER NOT NULL
1283
+ )
1284
+ `);
1285
+ };
1286
+ var migrate = (sqlite, migrations) => {
1287
+ ensureMigrationsTable(sqlite);
1288
+ const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
1289
+ const pending = migrations.filter((migration) => !applied.has(migration.id));
1290
+ if (pending.length === 0)
1291
+ return;
1292
+ const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
1293
+ const now = Math.floor(Date.now() / 1e3);
1294
+ sqlite.transaction(() => {
1295
+ for (const migration of pending) {
1296
+ sqlite.exec(migration.sql);
1297
+ insert.run(migration.id, now);
1298
+ }
1299
+ });
1300
+ };
1301
+
1302
+ // ../../sqlite/dist/schema.js
1303
+ var CORE_MIGRATIONS = [
1304
+ {
1305
+ id: "20260322_core_records_sequences",
1306
+ sql: `
1307
+ CREATE TABLE IF NOT EXISTS mockingbird_records (
1308
+ namespace TEXT NOT NULL,
1309
+ collection TEXT NOT NULL,
1310
+ id TEXT NOT NULL,
1311
+ seq INTEGER NOT NULL,
1312
+ value TEXT NOT NULL,
1313
+ PRIMARY KEY (namespace, collection, id)
1314
+ );
1315
+ CREATE INDEX IF NOT EXISTS mockingbird_records_seq
1316
+ ON mockingbird_records (namespace, collection, seq);
1317
+ CREATE TABLE IF NOT EXISTS mockingbird_sequences (
1318
+ namespace TEXT NOT NULL,
1319
+ name TEXT NOT NULL,
1320
+ kind TEXT NOT NULL,
1321
+ value INTEGER NOT NULL,
1322
+ PRIMARY KEY (namespace, name, kind)
1323
+ );
1324
+ `
1325
+ }
1326
+ ];
1327
+ var migrateCore = (sqlite) => {
1328
+ migrate(sqlite, CORE_MIGRATIONS);
1329
+ };
1330
+ var clearNamespace = (sqlite, namespace) => {
1331
+ sqlite.transaction(() => {
1332
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1333
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1334
+ });
1335
+ };
1336
+
1337
+ // ../../openapi/metadata/dist/types.js
1338
+ var EXTENSION_KEYS = {
1339
+ operation: "x-mockingbird",
1340
+ resource: "x-mockingbird-resource",
1341
+ resourceRef: "x-mockingbird-resource-ref",
1342
+ volatile: "x-mockingbird-volatile",
1343
+ scope: "x-mockingbird-scope",
1344
+ unsupported: "x-mockingbird-unsupported",
1345
+ parityHeader: "x-mockingbird-parity-header"
1346
+ };
1347
+
1348
+ // ../../openapi/metadata/dist/read.js
1349
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1350
+ var extensionOf = (holder, key) => holder[key];
1351
+ var operationMetadata = (operation) => {
1352
+ const raw = extensionOf(operation, EXTENSION_KEYS.operation);
1353
+ const ext = isRecord2(raw) ? raw : {};
1354
+ const supported = ext.supported ?? true;
1355
+ const parity = ext.parity ?? {};
1356
+ return {
1357
+ supported,
1358
+ reason: typeof ext.reason === "string" ? ext.reason : void 0,
1359
+ parity: {
1360
+ enabled: supported && (parity.enabled ?? true),
1361
+ safe: parity.safe ?? true,
1362
+ reason: typeof parity.reason === "string" ? parity.reason : void 0
1363
+ }
1364
+ };
1365
+ };
1366
+
1367
+ // ../core/dist/service.js
1368
+ import { Hono } from "hono";
1369
+ var defineOperations = (handlers) => handlers;
1370
+ var OperationRegistryError = class extends Error {
1371
+ problems;
1372
+ constructor(problems) {
1373
+ super(`operation registry is inconsistent:
1374
+ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1375
+ this.problems = problems;
1376
+ this.name = "OperationRegistryError";
1377
+ }
1378
+ };
1379
+ var verifyOperations = (document2, handlers) => {
1380
+ const problems = [];
1381
+ const operations = listOperations(document2);
1382
+ const seen = /* @__PURE__ */ new Set();
1383
+ for (const operation of operations) {
1384
+ if (seen.has(operation.operationId))
1385
+ problems.push(`duplicate operationId ${operation.operationId}`);
1386
+ seen.add(operation.operationId);
1387
+ const supported = operationMetadata(operation.operation).supported;
1388
+ const handler = handlers[operation.operationId];
1389
+ if (supported && !handler)
1390
+ problems.push(`supported operation ${operation.operationId} has no handler`);
1391
+ if (!supported && handler)
1392
+ problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
1393
+ }
1394
+ for (const id of Object.keys(handlers)) {
1395
+ if (!seen.has(id))
1396
+ problems.push(`handler ${id} has no OpenAPI operation`);
1397
+ }
1398
+ return problems;
1399
+ };
1400
+ var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
1401
+ var routeOrder = (a, b) => {
1402
+ const sa = a.path.split("/");
1403
+ const sb = b.path.split("/");
1404
+ for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
1405
+ const x = sa[i] ?? "";
1406
+ const y = sb[i] ?? "";
1407
+ const px = x.startsWith("{");
1408
+ const py = y.startsWith("{");
1409
+ if (px !== py)
1410
+ return px ? 1 : -1;
1411
+ if (x !== y)
1412
+ return x < y ? -1 : 1;
1413
+ }
1414
+ return 0;
1415
+ };
1416
+ var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
1417
+ var bootSqlite = (sqlite) => {
1418
+ const client = resolveSqlite(sqlite);
1419
+ migrateCore(client);
1420
+ return client;
1421
+ };
1422
+ var createService = (options) => {
1423
+ const problems = verifyOperations(options.document, options.handlers);
1424
+ if (problems.length > 0)
1425
+ throw new OperationRegistryError(problems);
1426
+ migrateCore(options.sqlite);
1427
+ const now = options.now ?? (() => Date.now());
1428
+ const app = new Hono();
1429
+ app.notFound((c) => options.notFound(c.req.raw));
1430
+ app.onError((error, c) => options.onError(error, c.req.raw));
1431
+ const operations = [...listOperations(options.document)].sort(routeOrder);
1432
+ for (const operation of operations) {
1433
+ const metadata = operationMetadata(operation.operation);
1434
+ const handler = options.handlers[operation.operationId];
1435
+ const route = async (c) => {
1436
+ const request = c.req.raw;
1437
+ if (!metadata.supported || !handler) {
1438
+ return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
1439
+ }
1440
+ const url = new URL(request.url);
1441
+ const context = {
1442
+ request,
1443
+ url,
1444
+ params: c.req.param(),
1445
+ query: queryOf(url),
1446
+ body: await readBody(request),
1447
+ sqlite: options.sqlite,
1448
+ namespace: options.namespace,
1449
+ operation,
1450
+ document: options.document,
1451
+ now
1452
+ };
1453
+ const short = await options.before?.(context);
1454
+ if (short)
1455
+ return short;
1456
+ return handler(context);
1457
+ };
1458
+ app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
1459
+ }
1460
+ return {
1461
+ app,
1462
+ sqlite: options.sqlite,
1463
+ namespace: options.namespace,
1464
+ fetch: async (request) => app.fetch(request),
1465
+ reset: async () => {
1466
+ clearNamespace(options.sqlite, options.namespace);
1467
+ }
1468
+ };
1469
+ };
1470
+
1471
+ // ../core/dist/snapshot.js
1472
+ var snapshotNamespace = (sqlite, namespace) => ({
1473
+ namespace,
1474
+ records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
1475
+ sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
1476
+ });
1477
+ var restoreNamespace = (sqlite, namespace, snapshot) => {
1478
+ sqlite.transaction(() => {
1479
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1480
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1481
+ const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
1482
+ for (const row of snapshot.records) {
1483
+ record.run(namespace, row.collection, row.id, row.seq, row.value);
1484
+ }
1485
+ const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
1486
+ for (const row of snapshot.sequences) {
1487
+ sequence.run(namespace, row.name, row.kind, row.value);
1488
+ }
1489
+ });
1490
+ };
1491
+
1492
+ // ../core/dist/version.js
1493
+ var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
1494
+
1495
+ // ../core/dist/webhooks.js
1496
+ var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1497
+ var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1498
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1499
+ var parseEndpoint = (value) => {
1500
+ if (!isRecord3(value) || typeof value.url !== "string")
1501
+ return "each endpoint needs a url";
1502
+ try {
1503
+ new URL(value.url);
1504
+ } catch {
1505
+ return `not a URL: ${value.url}`;
1506
+ }
1507
+ const endpoint = { url: value.url };
1508
+ if (typeof value.id === "string")
1509
+ endpoint.id = value.id;
1510
+ if (typeof value.secret === "string")
1511
+ endpoint.secret = value.secret;
1512
+ if (typeof value.signUrl === "string")
1513
+ endpoint.signUrl = value.signUrl;
1514
+ const events = value.events ?? value.enabledEvents;
1515
+ if (Array.isArray(events))
1516
+ endpoint.events = events.map(String);
1517
+ if (isRecord3(value.tags)) {
1518
+ endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1519
+ }
1520
+ if (typeof value.account === "string")
1521
+ endpoint.tags = { ...endpoint.tags, account: value.account };
1522
+ if (isRecord3(value.headers)) {
1523
+ endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1524
+ }
1525
+ return endpoint;
1526
+ };
1527
+ var webhookAdminRoutes = (hub) => ({
1528
+ "GET /webhooks": ({ url, namespace }) => json2(200, {
1529
+ deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1530
+ const type = url.searchParams.get("type");
1531
+ return type === null || d.type === type;
1532
+ })
1533
+ }),
1534
+ "GET /webhooks/events": ({ url, namespace }) => {
1535
+ const type = url.searchParams.get("type");
1536
+ return json2(200, {
1537
+ events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1538
+ });
1539
+ },
1540
+ "POST /webhooks/:id/replay": async ({ params }) => {
1541
+ const replayed = await hub.replay(params.id);
1542
+ return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
1543
+ },
1544
+ "POST /webhooks/flush": async () => {
1545
+ await hub.flush();
1546
+ return json2(200, { status: "ok" });
1547
+ },
1548
+ "POST /webhooks/faults": ({ body, namespace }) => {
1549
+ if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1550
+ return adminError2(400, "mode must be duplicate, reorder or drop");
1551
+ }
1552
+ const fault = { mode: body.mode };
1553
+ if (typeof body.count === "number")
1554
+ fault.count = body.count;
1555
+ hub.fault(namespace, fault);
1556
+ return json2(201, { namespace, ...fault });
1557
+ },
1558
+ "GET /webhook-endpoints": ({ namespace }) => json2(200, {
1559
+ endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1560
+ ...rest,
1561
+ secret: secret ? "(set)" : null
1562
+ }))
1563
+ }),
1564
+ "PUT /webhook-endpoints": ({ body, namespace }) => {
1565
+ const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
1566
+ if (!Array.isArray(list))
1567
+ return adminError2(400, "expected [{url, secret?, events?}]");
1568
+ const parsed = [];
1569
+ for (const each of list) {
1570
+ const endpoint = parseEndpoint(each);
1571
+ if (typeof endpoint === "string")
1572
+ return adminError2(400, endpoint);
1573
+ parsed.push(endpoint);
1574
+ }
1575
+ const set = hub.setEndpoints(namespace, parsed);
1576
+ return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1577
+ },
1578
+ "DELETE /webhook-endpoints": ({ namespace }) => {
1579
+ hub.setEndpoints(namespace, []);
1580
+ return json2(200, { status: "ok" });
1581
+ }
1582
+ });
1583
+ var parsePayload = (message) => {
1584
+ if (message.contentType.startsWith("application/json")) {
1585
+ try {
1586
+ return JSON.parse(message.body);
1587
+ } catch {
1588
+ return message.body;
1589
+ }
1590
+ }
1591
+ if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
1592
+ return Object.fromEntries(new URLSearchParams(message.body));
1593
+ }
1594
+ return message.body;
1595
+ };
1596
+
1597
+ // ../core/dist/runtime.js
1598
+ var MOCKINGBIRD_HEADER = "x-mockingbird";
1599
+ var BRANCH_HEADER = "x-mockingbird-branch";
1600
+ var AT_HEADER = "x-mockingbird-at";
1601
+ var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
1602
+ var DEFAULT_NAMESPACE = "default";
1603
+ var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1604
+ var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
1605
+ var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
1606
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
1607
+ var effects = /* @__PURE__ */ new WeakMap();
1608
+ var reuseSorted = (fresh, previous, compare, equal) => {
1609
+ if (!previous || previous.length === 0)
1610
+ return fresh.map((row) => Object.freeze(row));
1611
+ const result = new Array(fresh.length);
1612
+ let unchanged = fresh.length === previous.length;
1613
+ let oldIndex = 0;
1614
+ for (let index = 0; index < fresh.length; index++) {
1615
+ const row = fresh[index];
1616
+ while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
1617
+ oldIndex++;
1618
+ }
1619
+ const old = previous[oldIndex];
1620
+ result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
1621
+ if (result[index] !== previous[index])
1622
+ unchanged = false;
1623
+ }
1624
+ return unchanged ? previous : result;
1625
+ };
1626
+ var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
1627
+ var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
1628
+ var DroppedConnectionError = class extends TypeError {
1629
+ code = "MOCKINGBIRD_DROP";
1630
+ constructor() {
1631
+ super("fetch failed: connection dropped by Mockingbird fault");
1632
+ this.name = "TypeError";
1633
+ }
1634
+ };
1635
+ var operationMatcher = (document2) => {
1636
+ const matchers = listOperations(document2).map((operation) => ({
1637
+ operationId: operation.operationId,
1638
+ method: operation.method.toUpperCase(),
1639
+ pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
1640
+ params: (operation.path.match(/\{/g) ?? []).length
1641
+ })).sort((a, b) => a.params - b.params);
1642
+ return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1643
+ };
1644
+ var createRuntime = (options) => {
1645
+ const sqlite = bootSqlite(options.sqlite);
1646
+ const clock = options.clock ?? createClock();
1647
+ const rng = createRng(options.seed ?? 0);
1648
+ const wallNow = options.io?.wallNow ?? Date.now;
1649
+ const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
1650
+ const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1651
+ const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
1652
+ const metrics = createMetrics();
1653
+ const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
1654
+ const version = options.version ?? PACKAGE_VERSION;
1655
+ const instances = /* @__PURE__ */ new Map();
1656
+ const publicNamespaces = /* @__PURE__ */ new Set();
1657
+ const branchRngs = /* @__PURE__ */ new Map();
1658
+ const timelines = /* @__PURE__ */ new Map();
1659
+ const branchStorage = /* @__PURE__ */ new Map();
1660
+ const captured = /* @__PURE__ */ new Map();
1661
+ const credentials = createCredentialRegistry();
1662
+ const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
1663
+ const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
1664
+ const instanceFor = (key, publicNamespace = key, isolatedRng) => {
1665
+ const existing = instances.get(key);
1666
+ if (existing)
1667
+ return existing;
1668
+ if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
1669
+ throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
1670
+ }
1671
+ const created = options.create({
1672
+ namespace: storageNamespace(key),
1673
+ publicNamespace,
1674
+ sqlite,
1675
+ clock,
1676
+ rng: isolatedRng ?? rng
1677
+ });
1678
+ instances.set(key, created);
1679
+ publicNamespaces.add(publicNamespace);
1680
+ if (isolatedRng)
1681
+ branchRngs.set(key, isolatedRng);
1682
+ return created;
1683
+ };
1684
+ const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
1685
+ const capture = (storage) => {
1686
+ const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
1687
+ const previous = captured.get(storage);
1688
+ const snapshot2 = {
1689
+ namespace: fresh.namespace,
1690
+ records: reuseSorted(fresh.records, previous?.records, (left, right) => left.collection < right.collection ? -1 : left.collection > right.collection ? 1 : left.seq - right.seq, (left, right) => left.id === right.id && left.value === right.value),
1691
+ sequences: reuseSorted(fresh.sequences, previous?.sequences, (left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : left.kind < right.kind ? -1 : left.kind > right.kind ? 1 : 0, (left, right) => left.value === right.value)
1692
+ };
1693
+ Object.freeze(snapshot2.records);
1694
+ Object.freeze(snapshot2.sequences);
1695
+ Object.freeze(snapshot2);
1696
+ captured.set(storage, snapshot2);
1697
+ return Object.freeze({
1698
+ snapshot: snapshot2,
1699
+ clock: Object.freeze(clock.state()),
1700
+ rngState: (branchRngs.get(storage) ?? rng).state()
1701
+ });
1702
+ };
1703
+ const timeline = (name = DEFAULT_NAMESPACE) => {
1704
+ let found = timelines.get(name);
1705
+ if (found)
1706
+ return found;
1707
+ instance(name);
1708
+ found = new Timeline({
1709
+ now: clock.now,
1710
+ ...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
1711
+ });
1712
+ found.commit(capture(name));
1713
+ timelines.set(name, found);
1714
+ return found;
1715
+ };
1716
+ const physicalBranch = (namespace, branch2) => {
1717
+ if (branch2 === "main")
1718
+ return namespace;
1719
+ const mapKey = `${namespace}\0${branch2}`;
1720
+ const existing = branchStorage.get(mapKey);
1721
+ if (existing)
1722
+ return existing;
1723
+ const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
1724
+ branchStorage.set(mapKey, key);
1725
+ return key;
1726
+ };
1727
+ const ensureBranch = (namespace, branch2, at) => {
1728
+ if (!BRANCH_PATTERN2.test(branch2))
1729
+ throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
1730
+ const history = timeline(namespace);
1731
+ if (branch2 === "main") {
1732
+ if (at !== void 0) {
1733
+ const point = history.checkout("main", at);
1734
+ restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
1735
+ captured.set(namespace, point.value.snapshot);
1736
+ rng.setState(point.value.rngState);
1737
+ clock.set(point.value.clock.now);
1738
+ if (point.value.clock.frozen)
1739
+ clock.freeze();
1740
+ else
1741
+ clock.unfreeze();
1742
+ }
1743
+ return namespace;
1744
+ }
1745
+ const storage = physicalBranch(namespace, branch2);
1746
+ if (!history.hasBranch(branch2)) {
1747
+ if (at === void 0)
1748
+ history.commit(capture(namespace));
1749
+ const point = history.fork(branch2, at === void 0 ? {} : { from: at });
1750
+ const branchRng = createRng(options.seed ?? 0);
1751
+ if (point)
1752
+ branchRng.setState(point.value.rngState);
1753
+ instanceFor(storage, namespace, branchRng);
1754
+ if (point)
1755
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1756
+ if (point)
1757
+ captured.set(storage, point.value.snapshot);
1758
+ } else if (at !== void 0 && history.head(branch2)?.id !== at) {
1759
+ const point = history.checkout(branch2, at);
1760
+ if (!instances.has(storage)) {
1761
+ const branchRng = createRng(options.seed ?? 0);
1762
+ branchRng.setState(point.value.rngState);
1763
+ instanceFor(storage, namespace, branchRng);
1764
+ }
1765
+ branchRngs.get(storage)?.setState(point.value.rngState);
1766
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1767
+ captured.set(storage, point.value.snapshot);
1768
+ } else {
1769
+ if (!instances.has(storage)) {
1770
+ const point = history.head(branch2);
1771
+ const branchRng = createRng(options.seed ?? 0);
1772
+ if (point)
1773
+ branchRng.setState(point.value.rngState);
1774
+ instanceFor(storage, namespace, branchRng);
1775
+ }
1776
+ }
1777
+ return storage;
1778
+ };
1779
+ const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
1780
+ const storage = ensureBranch(namespace, branch2);
1781
+ return timeline(namespace).commit(capture(storage), { branch: branch2 });
1782
+ };
1783
+ const branch = (name, branchOptions = {}) => {
1784
+ const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
1785
+ ensureBranch(namespace, name, branchOptions.at);
1786
+ const head = timeline(namespace).head(name);
1787
+ if (!head)
1788
+ throw new RangeError(`branch ${name} has no checkpoint`);
1789
+ return head;
1790
+ };
1791
+ const checkout = (checkpointId, checkoutOptions = {}) => {
1792
+ const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
1793
+ const branchName = checkoutOptions.branch ?? "main";
1794
+ const history = timeline(namespace);
1795
+ const point = history.checkout(branchName, checkpointId);
1796
+ const storage = ensureBranch(namespace, branchName);
1797
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1798
+ captured.set(storage, point.value.snapshot);
1799
+ clock.set(point.value.clock.now);
1800
+ if (point.value.clock.frozen)
1801
+ clock.freeze();
1802
+ else
1803
+ clock.unfreeze();
1804
+ (branchRngs.get(storage) ?? rng).setState(point.value.rngState);
1805
+ };
1806
+ const reset = async (name = DEFAULT_NAMESPACE) => {
1807
+ if (name === "*") {
1808
+ options.webhooks?.clear();
1809
+ for (const each of instances.values())
1810
+ await each.reset();
1811
+ timelines.clear();
1812
+ branchStorage.clear();
1813
+ branchRngs.clear();
1814
+ captured.clear();
1815
+ return;
1816
+ }
1817
+ options.webhooks?.clear(name);
1818
+ const target = instances.get(name);
1819
+ if (target)
1820
+ await target.reset();
1821
+ else
1822
+ clearNamespace(sqlite, storageNamespace(name));
1823
+ for (const [mapping, storage] of branchStorage) {
1824
+ if (!mapping.startsWith(`${name}\0`))
1825
+ continue;
1826
+ const branchInstance = instances.get(storage);
1827
+ if (branchInstance)
1828
+ await branchInstance.reset();
1829
+ else
1830
+ clearNamespace(sqlite, storageNamespace(storage));
1831
+ branchStorage.delete(mapping);
1832
+ branchRngs.delete(storage);
1833
+ captured.delete(storage);
1834
+ }
1835
+ timelines.delete(name);
1836
+ captured.delete(name);
1837
+ };
1838
+ const snapshot = (name = DEFAULT_NAMESPACE) => {
1839
+ return checkpoint(name, "main").value.snapshot;
1840
+ };
1841
+ const restore = (from, name = DEFAULT_NAMESPACE) => {
1842
+ instance(name);
1843
+ restoreNamespace(sqlite, storageNamespace(name), from);
1844
+ captured.set(name, from);
1845
+ const history = timelines.get(name);
1846
+ if (history)
1847
+ history.commit(capture(name), { branch: "main" });
1848
+ else
1849
+ timeline(name);
1850
+ };
1851
+ const runtime = {
1852
+ name: options.name,
1853
+ sqlite,
1854
+ clock,
1855
+ faults,
1856
+ metrics,
1857
+ journal,
1858
+ rng,
1859
+ credentials,
1860
+ webhooks: options.webhooks,
1861
+ applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
1862
+ const preset = options.presets?.[name];
1863
+ if (!preset)
1864
+ throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
1865
+ const added = (preset.rules ?? []).map((rule, index) => faults.add({
1866
+ namespace,
1867
+ ...rule,
1868
+ ...overrides,
1869
+ preset: name,
1870
+ id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
1871
+ }));
1872
+ if (preset.webhook && options.webhooks) {
1873
+ options.webhooks.fault(namespace, {
1874
+ ...preset.webhook,
1875
+ ...overrides.count !== void 0 ? { count: overrides.count } : {}
1876
+ });
1877
+ }
1878
+ return added;
1879
+ },
1880
+ instance,
1881
+ namespaces: () => [...publicNamespaces].sort(),
1882
+ reset,
1883
+ snapshot,
1884
+ restore,
1885
+ checkpoint,
1886
+ branch,
1887
+ checkout,
1888
+ timeline,
1889
+ fetch: async (incoming) => {
1890
+ let request = incoming;
1891
+ const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
1892
+ if (prefixed) {
1893
+ const url2 = new URL(request.url);
1894
+ url2.pathname = prefixed[2] ?? "/";
1895
+ const headers = new Headers(request.headers);
1896
+ if (!headers.has(NAMESPACE_HEADER)) {
1897
+ headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
1898
+ }
1899
+ const hasBody = request.method !== "GET" && request.method !== "HEAD";
1900
+ request = new Request(url2, {
1901
+ method: request.method,
1902
+ headers,
1903
+ ...hasBody ? { body: await request.arrayBuffer() } : {},
1904
+ signal: request.signal
1905
+ });
1906
+ }
1907
+ let namespace = control.namespaceOf(request);
1908
+ if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
1909
+ const credential = options.credential(request);
1910
+ const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
1911
+ if (mapped !== void 0)
1912
+ namespace = mapped;
1913
+ }
1914
+ const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
1915
+ const at = request.headers.get(AT_HEADER) ?? void 0;
1916
+ const stamp = (response2) => {
1917
+ const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
1918
+ try {
1919
+ response2.headers.set(MOCKINGBIRD_HEADER, value);
1920
+ return response2;
1921
+ } catch {
1922
+ const copy = new Response(response2.body, response2);
1923
+ copy.headers.set(MOCKINGBIRD_HEADER, value);
1924
+ return copy;
1925
+ }
1926
+ };
1927
+ const handled = await control.handle(request);
1928
+ if (handled)
1929
+ return stamp(handled);
1930
+ const started = monotonicNow();
1931
+ const url = new URL(request.url);
1932
+ const operationId = operationIdFor(request, url.pathname);
1933
+ const log = (status, faultId, response2) => {
1934
+ const noted = response2 ? responseNotes(response2) : void 0;
1935
+ const entry = {
1936
+ service: options.name,
1937
+ namespace,
1938
+ operationId,
1939
+ method: request.method,
1940
+ path: url.pathname,
1941
+ status,
1942
+ durationMs: Math.round((monotonicNow() - started) * 100) / 100,
1943
+ unmatched: options.document !== void 0 && operationId === void 0,
1944
+ ...faultId !== void 0 ? { faultId } : {},
1945
+ ...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
1946
+ ...noted?.adopted ? { adopted: true } : {}
1947
+ };
1948
+ metrics.record(entry);
1949
+ journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
1950
+ options.onLog?.(entry);
1951
+ };
1952
+ if (!NAMESPACE_PATTERN.test(namespace)) {
1953
+ log(400);
1954
+ return stamp(new Response(JSON.stringify({
1955
+ error: {
1956
+ type: "mockingbird_admin",
1957
+ message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
1958
+ }
1959
+ }), { status: 400, headers: { "content-type": "application/json" } }));
1960
+ }
1961
+ if (!BRANCH_PATTERN2.test(selectedBranch)) {
1962
+ log(400);
1963
+ return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
1964
+ }
1965
+ let storage;
1966
+ try {
1967
+ if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
1968
+ const point = timeline(namespace).get(at);
1969
+ storage = physicalBranch(namespace, `at_${at}`);
1970
+ let viewRng = branchRngs.get(storage);
1971
+ if (!viewRng) {
1972
+ viewRng = createRng(options.seed ?? 0);
1973
+ instanceFor(storage, namespace, viewRng);
1974
+ }
1975
+ viewRng.setState(point.value.rngState);
1976
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1977
+ captured.set(storage, point.value.snapshot);
1978
+ } else {
1979
+ storage = ensureBranch(namespace, selectedBranch, at);
1980
+ }
1981
+ } catch (error) {
1982
+ log(409);
1983
+ return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
1984
+ }
1985
+ const hits = await faults.take({
1986
+ operationId,
1987
+ method: request.method,
1988
+ path: url.pathname,
1989
+ namespace
1990
+ });
1991
+ const final = hits.find((hit) => hit.drop || hit.response);
1992
+ if (final?.drop) {
1993
+ log(0, final.id);
1994
+ throw new DroppedConnectionError();
1995
+ }
1996
+ if (final?.response) {
1997
+ log(final.response.status, final.id);
1998
+ return stamp(final.response);
1999
+ }
2000
+ const fired = hits.filter((hit) => hit.effect !== void 0);
2001
+ if (fired.length > 0)
2002
+ effects.set(request, fired.map((hit) => hit.effect));
2003
+ let response = await instanceFor(storage, namespace).fetch(request);
2004
+ if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
2005
+ const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
2006
+ response = mutableResponse(response);
2007
+ response.headers.set(CHECKPOINT_HEADER, point.id);
2008
+ }
2009
+ if (selectedBranch !== "main") {
2010
+ response = mutableResponse(response);
2011
+ response.headers.set(BRANCH_HEADER, selectedBranch);
2012
+ }
2013
+ if (at !== void 0) {
2014
+ response = mutableResponse(response);
2015
+ response.headers.set(AT_HEADER, at);
2016
+ }
2017
+ log(response.status, fired[0]?.id, response);
2018
+ return stamp(response);
2019
+ }
2020
+ };
2021
+ const control = createControlPlane({
2022
+ name: options.name,
2023
+ startedAt: wallNow(),
2024
+ wallNow,
2025
+ clock,
2026
+ faults,
2027
+ metrics,
2028
+ journal,
2029
+ defaultNamespace: DEFAULT_NAMESPACE,
2030
+ namespaces: runtime.namespaces,
2031
+ reset,
2032
+ timeTravel: {
2033
+ checkpoint: (name, branchName) => {
2034
+ const point = checkpoint(name, branchName);
2035
+ return {
2036
+ id: point.id,
2037
+ branch: point.branch,
2038
+ parent: point.parent,
2039
+ at: point.at,
2040
+ records: point.value.snapshot.records.length
2041
+ };
2042
+ },
2043
+ branch: (branchName, branchOptions) => {
2044
+ const point = branch(branchName, branchOptions);
2045
+ return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
2046
+ },
2047
+ checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
2048
+ retain: (name, checkpointId) => {
2049
+ timeline(name).retain(checkpointId);
2050
+ },
2051
+ release: (name, checkpointId) => timeline(name).release(checkpointId),
2052
+ inspect: (name) => {
2053
+ const history = timeline(name);
2054
+ return {
2055
+ branches: history.branches(),
2056
+ checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
2057
+ id,
2058
+ branch: branchName,
2059
+ parent,
2060
+ at
2061
+ }))
2062
+ };
2063
+ }
2064
+ },
2065
+ describe: options.describe ?? (() => ({})),
2066
+ ...options.presets ? {
2067
+ applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
2068
+ } : {},
2069
+ routes: {
2070
+ ...credentialRoutes(credentials),
2071
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
2072
+ ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2073
+ ...options.admin?.(runtime) ?? {}
2074
+ },
2075
+ adminKey: options.adminKey
2076
+ });
2077
+ return runtime;
2078
+ };
2079
+ var mutableResponse = (response) => {
2080
+ try {
2081
+ response.headers.set("x-mockingbird-mutable-probe", "1");
2082
+ response.headers.delete("x-mockingbird-mutable-probe");
2083
+ return response;
2084
+ } catch {
2085
+ return new Response(response.body, response);
2086
+ }
2087
+ };
2088
+ var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2089
+ var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
2090
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2091
+ var credentialRoutes = (registry) => ({
2092
+ "GET /credentials": () => adminJson(200, {
2093
+ credentials: registry.entries().map(({ credential, namespace }) => ({
2094
+ credential: maskCredential(credential),
2095
+ namespace
2096
+ }))
2097
+ }),
2098
+ "PUT /credentials": ({ body, namespace }) => {
2099
+ const pairs = [];
2100
+ const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
2101
+ if (Array.isArray(list)) {
2102
+ for (const each of list) {
2103
+ if (typeof each === "string")
2104
+ pairs.push([each, namespace]);
2105
+ else if (isObject(each) && typeof each.credential === "string") {
2106
+ pairs.push([
2107
+ each.credential,
2108
+ typeof each.namespace === "string" ? each.namespace : namespace
2109
+ ]);
2110
+ } else
2111
+ return adminFail(400, "each entry is a credential string or {credential, namespace}");
2112
+ }
2113
+ } else if (isObject(list)) {
2114
+ for (const [credential, target] of Object.entries(list)) {
2115
+ if (typeof target !== "string")
2116
+ return adminFail(400, `namespace for ${credential} must be a string`);
2117
+ pairs.push([credential, target]);
2118
+ }
2119
+ } else if (isObject(body) && typeof body.credential === "string") {
2120
+ pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
2121
+ } else {
2122
+ return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
2123
+ }
2124
+ for (const [credential, target] of pairs) {
2125
+ if (!NAMESPACE_PATTERN.test(target))
2126
+ return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
2127
+ registry.set(credential, target);
2128
+ }
2129
+ return adminJson(200, { mapped: pairs.length });
2130
+ },
2131
+ "DELETE /credentials": ({ url }) => {
2132
+ const credential = url.searchParams.get("credential");
2133
+ if (credential === null)
2134
+ registry.clear();
2135
+ else
2136
+ registry.remove(credential);
2137
+ return adminJson(200, { status: "ok" });
2138
+ }
2139
+ });
2140
+ var presetRoutes = (presets, runtime) => ({
2141
+ "GET /faults/presets": () => adminJson(200, {
2142
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
2143
+ }),
2144
+ "POST /faults/presets/:name": ({ params, body, namespace }) => {
2145
+ const name = params.name;
2146
+ if (!presets[name])
2147
+ return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
2148
+ const overrides = isObject(body) ? body : {};
2149
+ return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
2150
+ }
2151
+ });
2152
+
2153
+ // ../core/dist/validation.js
2154
+ var bodyIssues = (context, contentType = "application/json") => {
2155
+ const requestBody = context.operation.operation.requestBody;
2156
+ if (!requestBody)
2157
+ return [];
2158
+ const resolved = deref(context.document, requestBody);
2159
+ const schema = resolved.content?.[contentType]?.schema;
2160
+ if (!schema)
2161
+ return [];
2162
+ const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
2163
+ if (context.body.kind === "invalid") {
2164
+ return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
2165
+ }
2166
+ if (value === void 0) {
2167
+ return resolved.required ? [{ path: "", message: "request body is required" }] : [];
2168
+ }
2169
+ return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
2170
+ };
2171
+
2172
+ // src/generated/openapi.ts
2173
+ var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Prism Labs body-scan API (Mockingbird subset)","description":"Stateful mock subset of the Prism Labs API (\`Accept: application/json;v=1\`): subject upsert, scans, the presigned capture upload, per-stage processing states, and the READY-scan results (body composition, measurements, health report, asset URLs). Hand-authored from the consumer's zod schemas (prism-scan.adapter.ts).\\n","version":"1","x-mockingbird-upstream":{"note":"Wire shapes from apps/backend/src/modules/body-scan/adapters/outbound/prism-scan.adapter.ts and packages/body-scan-capture-page/src/main.ts (the PUT upload)."}},"servers":[{"url":"https://sandbox-api.hosted.prismlabs.tech"}],"security":[{"bearerAuth":[]}],"paths":{"/users":{"post":{"operationId":"UpsertUser","description":"Create or update the scan subject identified by \`token\`.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"200":{"description":"Updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/User"}}}},"201":{"description":"Created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/User"}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Missing or unknown API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserBody"}}}}}},"/scans":{"post":{"operationId":"CreateScan","description":"Start a scan for a subject.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"201":{"description":"Created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Scan"}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Missing or unknown API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown user token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ScanBody"}}}}}},"/scans/{scanId}":{"get":{"operationId":"GetScan","description":"A scan's status and weight.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The scan","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Scan"}}}},"401":{"description":"Missing or unknown API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown scan, or results not ready yet","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"parameters":[{"name":"scanId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"scan","missing":"00000000-0000-4000-8000-000000000000"}}},{"name":"unit-system","in":"query","required":false,"schema":{"type":"string","enum":["metric","imperial"]}}]}},"/scans/{scanId}/upload-url":{"post":{"operationId":"CreateUploadUrl","description":"A presigned PUT URL for the capture video (15 minutes).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"200":{"description":"Upload target","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UploadTarget"}}}},"401":{"description":"Missing or unknown API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown scan, or results not ready yet","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The scan already has its capture","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"parameters":[{"name":"scanId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"scan","missing":"00000000-0000-4000-8000-000000000000"}}}]}},"/scans/{scanId}/scan-assets":{"get":{"operationId":"GetScanAssets","description":"Per-stage processing states.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Stage states","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ScanAssets"}}}},"401":{"description":"Missing or unknown API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown scan, or results not ready yet","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"parameters":[{"name":"scanId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"scan","missing":"00000000-0000-4000-8000-000000000000"}}}]}},"/scans/{scanId}/bodyfat":{"get":{"operationId":"GetBodyfat","description":"Body composition (READY scans).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Body composition","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Bodyfat"}}}},"401":{"description":"Missing or unknown API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown scan, or results not ready yet","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"parameters":[{"name":"scanId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"scan","missing":"00000000-0000-4000-8000-000000000000"}}}]}},"/scans/{scanId}/measurements":{"get":{"operationId":"GetMeasurements","description":"Circumferences and indices (READY scans).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Measurements","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Measurements"}}}},"401":{"description":"Missing or unknown API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown scan, or results not ready yet","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"parameters":[{"name":"scanId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"scan","missing":"00000000-0000-4000-8000-000000000000"}}},{"name":"unit-system","in":"query","required":false,"schema":{"type":"string","enum":["metric","imperial"]}}]}},"/scans/{scanId}/health-report":{"get":{"operationId":"GetHealthReport","description":"Health report incl. metabolic age (READY scans).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Report","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HealthReport"}}}},"401":{"description":"Missing or unknown API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown scan, or results not ready yet","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"parameters":[{"name":"scanId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"scan","missing":"00000000-0000-4000-8000-000000000000"}}}]}},"/scans/{scanId}/asset-urls":{"get":{"operationId":"GetAssetUrls","description":"Signed URLs for the scan's 3D assets (READY scans).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"URLs","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AssetUrls"}}}},"401":{"description":"Missing or unknown API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown scan, or results not ready yet","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"parameters":[{"name":"scanId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"scan","missing":"00000000-0000-4000-8000-000000000000"}}}]}},"/uploads/{scanId}":{"put":{"operationId":"UploadCapture","description":"The presigned upload target (what the capture page PUTs the video to). Moves the scan to PROCESSING.","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"reason":"Binary video upload through a presigned URL; covered by acceptance tests."}},"parameters":[{"name":"scanId","in":"path","required":true,"schema":{"type":"string"}},{"name":"expires","in":"query","required":true,"schema":{"type":"string"}},{"name":"signature","in":"query","required":true,"schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/octet-stream":{"schema":{"type":"string","format":"binary"}},"video/mp4":{"schema":{"type":"string","format":"binary"}}}},"responses":{"200":{"description":"Stored"},"403":{"description":"Expired or bad signature (S3-style XML)","content":{"application/xml":{"schema":{"type":"string"}}}},"404":{"description":"Unknown scan"}}}},"/assets/{scanId}/{file}":{"get":{"operationId":"GetAsset","description":"A signed 3D asset (tiny placeholder bytes).","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":false,"reason":"Binary asset bytes; covered by acceptance tests."}},"parameters":[{"name":"scanId","in":"path","required":true,"schema":{"type":"string"}},{"name":"file","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Asset bytes","content":{"application/octet-stream":{"schema":{"type":"string","format":"binary"}}}},"404":{"description":"Unknown asset"}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer"}},"schemas":{"UserBody":{"type":"object","required":["token","sex","region","birthDate","weight","height","researchConsent","termsOfService"],"properties":{"token":{"type":"string","minLength":1,"maxLength":64,"examples":["user-token-1","user-token-2"]},"sex":{"type":"string","enum":["male","female","neutral","undefined"]},"region":{"type":"string","enum":["africa","asia","caribbean","central_america","europe","north_america","oceania","south_america"]},"birthDate":{"type":"string","pattern":"^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-8])$"},"weight":{"type":"object","required":["value","unit"],"properties":{"value":{"type":"number","exclusiveMinimum":0,"maximum":400},"unit":{"type":"string","enum":["kg","lb"]}}},"height":{"type":"object","required":["value","unit"],"properties":{"value":{"type":"number","exclusiveMinimum":0,"maximum":400},"unit":{"type":"string","enum":["m","in"]}}},"researchConsent":{"type":"boolean"},"termsOfService":{"type":"object","required":["accepted","version"],"properties":{"accepted":{"type":"boolean"},"version":{"type":"string","minLength":1,"maxLength":20}}}}},"User":{"type":"object","required":["id","token","sex","region","birthDate","weight","height","createdAt"],"properties":{"id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"token":{"type":"string"},"sex":{"type":"string"},"region":{"type":"string"},"birthDate":{"type":"string"},"weight":{"type":"object"},"height":{"type":"object"},"researchConsent":{"type":"boolean"},"termsOfService":{"type":"object"},"createdAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updatedAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"ScanBody":{"type":"object","required":["userToken","deviceConfigName","bodyfatMethod"],"properties":{"userToken":{"type":"string","minLength":1,"maxLength":64,"examples":["user-token-1","user-token-2"]},"deviceConfigName":{"type":"string","enum":["IPHONE_SCANNER","ANDROID_SCANNER"]},"bodyfatMethod":{"type":"string","enum":["coco2","coco","army","extended_navy_thinboost"]},"assetConfigId":{"type":"string","enum":["25f6d3a6-a634-40c3-8452-0342bee242d0","ee651a9e-6de1-4621-a5c9-5d31ca874718"]}}},"Scan":{"type":"object","required":["id","status","userToken","createdAt","updatedAt"],"properties":{"id":{"type":"string","x-mockingbird-resource":{"type":"scan","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"status":{"type":"string","enum":["CREATED","PROCESSING","READY","FAILED"]},"userToken":{"type":"string"},"deviceConfigName":{"type":"string"},"bodyfatMethod":{"type":"string"},"assetConfigId":{"type":["string","null"]},"weight":{"type":["object","null"],"properties":{"value":{"type":"number"},"unit":{"type":"string"}}},"height":{"type":["object","null"]},"createdAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updatedAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"UploadTarget":{"type":"object","required":["url","expirationTime"],"properties":{"url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"expirationTime":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"ScanAssets":{"type":"object","properties":{"captureData":{"type":["string","null"],"enum":["started","succeeded","failed",null]},"captureDataUpdatedAt":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"timestamp"}},"body":{"type":["string","null"],"enum":["started","succeeded","failed",null]},"bodyUpdatedAt":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"timestamp"}},"fittedBody":{"type":["string","null"],"enum":["started","succeeded","failed",null]},"fittedBodyUpdatedAt":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"timestamp"}},"measurement":{"type":["string","null"],"enum":["started","succeeded","failed",null]},"measurementUpdatedAt":{"type":["string","null"],"x-mockingbird-volatile":{"kind":"timestamp"}}}},"Bodyfat":{"type":"object","required":["bodyfatMethod","bodyfatPercentage","leanMass","fatMass"],"properties":{"bodyfatMethod":{"type":"string"},"bodyfatPercentage":{"type":"number"},"leanMass":{"type":"number"},"fatMass":{"type":"number"},"skeletalMuscleMass":{"type":"number"},"unit":{"type":"string"}}},"Measurements":{"type":"object","required":["waistFit","hipsFit","chestFit","waistToHipRatio"],"properties":{"waistFit":{"type":"number"},"hipsFit":{"type":"number"},"chestFit":{"type":"number"},"waistToHipRatio":{"type":"number"},"bodyRoundnessIndex":{"type":"number"},"bmiPredicted":{"type":"number"},"unit":{"type":"string"}}},"HealthReport":{"type":"object","properties":{"metabolicAgeReport":{"type":["object","null"],"properties":{"metabolicAgeYears":{"type":["number","null"]},"chronologicalAgeYears":{"type":["number","null"]},"ageDeltaYears":{"type":["number","null"]},"percentile":{"type":["number","null"]}}},"bodyShapeReport":{"type":"object"}}},"AssetUrls":{"type":"object","properties":{"previewImage":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"model":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"canonicalBody":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"texture":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"material":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"stripes":{"type":"string","x-mockingbird-volatile":{"kind":"url"}}}},"Error":{"type":"object","required":["message"],"properties":{"message":{"type":"string"},"errors":{"type":"array","items":{"type":"object"}}}}}}}`);
2174
+ var operationIds = ["UpsertUser", "CreateScan", "GetScan", "CreateUploadUrl", "GetScanAssets", "GetBodyfat", "GetMeasurements", "GetHealthReport", "GetAssetUrls", "UploadCapture", "GetAsset"];
2175
+ var supportedOperationIds = ["UpsertUser", "CreateScan", "GetScan", "CreateUploadUrl", "GetScanAssets", "GetBodyfat", "GetMeasurements", "GetHealthReport", "GetAssetUrls", "UploadCapture", "GetAsset"];
2176
+
2177
+ // src/state.ts
2178
+ var STAGES = ["captureData", "body", "fittedBody", "measurement"];
2179
+ var DEFAULT_SETTINGS = {
2180
+ apiKeys: [],
2181
+ autoAdvance: null,
2182
+ uploadUrlTtlMs: 15 * 6e4
2183
+ };
2184
+ var PrismState = class {
2185
+ constructor(sqlite, namespace, seed) {
2186
+ this.seed = seed;
2187
+ this.users = new Collection(sqlite, namespace, "users");
2188
+ this.scans = new Collection(sqlite, namespace, "scans");
2189
+ this.settings = new Collection(sqlite, namespace, "settings");
2190
+ this.ids = new IdSequence(sqlite, namespace, "prism");
2191
+ this.ensureSeeded();
2192
+ }
2193
+ seed;
2194
+ users;
2195
+ scans;
2196
+ settings;
2197
+ ids;
2198
+ ensureSeeded() {
2199
+ if (!this.settings.has("settings")) {
2200
+ this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed });
2201
+ }
2202
+ }
2203
+ current() {
2204
+ return this.settings.get("settings") ?? DEFAULT_SETTINGS;
2205
+ }
2206
+ update(patch) {
2207
+ const next = { ...this.current(), ...patch };
2208
+ this.settings.insert("settings", next);
2209
+ return next;
2210
+ }
2211
+ user(token) {
2212
+ return this.users.get(token);
2213
+ }
2214
+ };
2215
+
2216
+ // src/runtime.ts
2217
+ var PRISM_PRESETS = {
2218
+ unauthorized: {
2219
+ description: "Every call answers 401 (PRISM_API_KEY revoked)",
2220
+ rules: [
2221
+ { pathPrefix: "/users", status: 401, body: { message: "Unauthorized" } },
2222
+ { pathPrefix: "/scans", status: 401, body: { message: "Unauthorized" } }
2223
+ ]
2224
+ },
2225
+ server_error: {
2226
+ description: "Every API call answers 500",
2227
+ rules: [
2228
+ { pathPrefix: "/users", status: 500, body: { message: "Internal Server Error" } },
2229
+ { pathPrefix: "/scans", status: 500, body: { message: "Internal Server Error" } }
2230
+ ]
2231
+ },
2232
+ scan_not_found: {
2233
+ description: "Scan reads answer 404 (our adapter reports not_found)",
2234
+ rules: [{ operationId: "GetScan", status: 404, body: { message: "Scan not found" } }]
2235
+ },
2236
+ schema_drift: {
2237
+ description: "GetScan answers an unknown status (QUEUED): our zod enum rejects it",
2238
+ rules: [{ operationId: "GetScan", effect: "schema_drift" }]
2239
+ },
2240
+ stage_states_slow: {
2241
+ description: "scan-assets answers after 6 s, past our adapter's 5 s timeout",
2242
+ rules: [{ operationId: "GetScanAssets", latencyMs: 6e3 }]
2243
+ },
2244
+ metabolic_age_missing: {
2245
+ description: "The health report carries metabolicAgeReport: null",
2246
+ rules: [{ operationId: "GetHealthReport", effect: "metabolic_age_missing" }]
2247
+ },
2248
+ metabolic_age_implausible: {
2249
+ description: "The health report's metabolic age is 150 years",
2250
+ rules: [{ operationId: "GetHealthReport", effect: "metabolic_age_implausible" }]
2251
+ },
2252
+ upload_forbidden: {
2253
+ description: "The presigned PUT answers 403 (as S3 does for an expired URL)",
2254
+ rules: [
2255
+ {
2256
+ operationId: "UploadCapture",
2257
+ status: 403,
2258
+ body: "<Error><Code>AccessDenied</Code><Message>Request has expired</Message></Error>",
2259
+ headers: { "content-type": "application/xml" }
2260
+ }
2261
+ ]
2262
+ },
2263
+ connection_drop: {
2264
+ description: "The connection drops before any answer (fetch rejects)",
2265
+ rules: [{ pathPrefix: "/scans", drop: true }]
2266
+ }
2267
+ };
2268
+ var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2269
+ var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2270
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2271
+ var parseAutoAdvance = (value) => {
2272
+ if (value === null) return null;
2273
+ if (!isRecord4(value) || typeof value.afterMs !== "number" || value.afterMs < 0) {
2274
+ return "autoAdvance must be {afterMs, failAt?} or null";
2275
+ }
2276
+ if (value.failAt !== void 0 && !STAGES.includes(value.failAt)) {
2277
+ return `autoAdvance.failAt must be one of ${STAGES.join(", ")}`;
2278
+ }
2279
+ return { afterMs: value.afterMs, ...value.failAt ? { failAt: value.failAt } : {} };
2280
+ };
2281
+ var adminRoutes = (runtime) => ({
2282
+ "GET /scans": ({ namespace }) => json3(200, { scans: runtime.instance(namespace).scans() }),
2283
+ "POST /scans/:id/advance": ({ params, body, namespace }) => {
2284
+ const api = runtime.instance(namespace);
2285
+ const steps = isRecord4(body) && body.to === "READY" ? STAGES.length : 1;
2286
+ let scan = api.state.scans.get(params.id);
2287
+ if (!scan) return adminError3(404, `no scan ${params.id}`);
2288
+ if (scan.status !== "PROCESSING") {
2289
+ return adminError3(409, `scan ${params.id} is ${scan.status}; upload its capture first`);
2290
+ }
2291
+ for (let i = 0; i < steps && scan?.status === "PROCESSING"; i++) scan = api.advance(scan.id);
2292
+ return json3(200, scan);
2293
+ },
2294
+ "POST /scans/:id/fail": ({ params, namespace }) => {
2295
+ const scan = runtime.instance(namespace).advance(params.id, true);
2296
+ return scan ? json3(200, scan) : adminError3(404, `no scan ${params.id}`);
2297
+ },
2298
+ "GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
2299
+ "PUT /settings": ({ body, namespace }) => {
2300
+ if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
2301
+ const patch = {};
2302
+ if (body.apiKeys !== void 0) {
2303
+ if (!Array.isArray(body.apiKeys)) return adminError3(400, "apiKeys: string[]");
2304
+ patch.apiKeys = body.apiKeys.map(String);
2305
+ }
2306
+ if (body.uploadUrlTtlMs !== void 0) {
2307
+ if (typeof body.uploadUrlTtlMs !== "number") return adminError3(400, "uploadUrlTtlMs: number");
2308
+ patch.uploadUrlTtlMs = body.uploadUrlTtlMs;
2309
+ }
2310
+ if (body.autoAdvance !== void 0) {
2311
+ const parsed = parseAutoAdvance(body.autoAdvance);
2312
+ if (typeof parsed === "string") return adminError3(400, parsed);
2313
+ patch.autoAdvance = parsed;
2314
+ }
2315
+ return json3(200, runtime.instance(namespace).state.update(patch));
2316
+ },
2317
+ "POST /tick": ({ namespace }) => json3(200, { applied: runtime.instance(namespace).tick() })
2318
+ });
2319
+ var createRuntime2 = (options = {}) => {
2320
+ const runtime = createRuntime({
2321
+ name: PRISM_NAMESPACE,
2322
+ document,
2323
+ ...options.sqlite ? { sqlite: options.sqlite } : {},
2324
+ ...options.clock ? { clock: options.clock } : {},
2325
+ ...options.seed !== void 0 ? { seed: options.seed } : {},
2326
+ ...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
2327
+ ...options.onLog ? { onLog: options.onLog } : {},
2328
+ credential: bearerToken,
2329
+ presets: PRISM_PRESETS,
2330
+ create: ({ sqlite, namespace, publicNamespace, clock }) => new PrismAPI({
2331
+ sqlite,
2332
+ namespace,
2333
+ publicNamespace,
2334
+ now: clock.now,
2335
+ ...options.settings ? { settings: options.settings } : {}
2336
+ }),
2337
+ admin: adminRoutes
2338
+ });
2339
+ let timer;
2340
+ if (options.tickMs !== void 0 && options.tickMs > 0) {
2341
+ timer = setInterval(() => {
2342
+ for (const name of runtime.namespaces()) runtime.instance(name).tick();
2343
+ }, options.tickMs);
2344
+ timer.unref?.();
2345
+ }
2346
+ return Object.assign(runtime, {
2347
+ stop: () => {
2348
+ if (timer !== void 0) clearInterval(timer);
2349
+ }
2350
+ });
2351
+ };
2352
+
2353
+ // src/index.ts
2354
+ var PRISM_NAMESPACE = "prism";
2355
+ var POUNDS_TO_KILOGRAMS = 0.45359237;
2356
+ var INCHES_TO_METERS = 0.0254;
2357
+ var ASSET_FILES = {
2358
+ previewImage: "preview.png",
2359
+ model: "model.obj",
2360
+ canonicalBody: "canonical-body.obj",
2361
+ texture: "texture.png",
2362
+ material: "material.mtl",
2363
+ stripes: "stripes.png"
2364
+ };
2365
+ var round = (value, digits = 2) => Math.round(value * 10 ** digits) / 10 ** digits;
2366
+ var clamp = (value, min, max) => Math.min(max, Math.max(min, value));
2367
+ var prismError = (status, message, errors) => jsonRes(status, { message, ...errors ? { errors } : {} });
2368
+ var kilograms = (q) => q.unit === "lb" ? q.value * POUNDS_TO_KILOGRAMS : q.value;
2369
+ var meters = (q) => q.unit === "in" ? q.value * INCHES_TO_METERS : q.value;
2370
+ var scanResults = (scan, user, nowMs) => {
2371
+ const kg = kilograms(scan.weight);
2372
+ const m = meters(scan.height);
2373
+ const bmi = kg / (m * m);
2374
+ const birth = Date.parse(user?.birthDate ?? "1990-01-01");
2375
+ const age = Math.max(0, (nowMs - birth) / (365.25 * 864e5));
2376
+ const male = user?.sex === "male" ? 1 : 0;
2377
+ const bodyfat = clamp(1.2 * bmi + 0.23 * age - 10.8 * male - 5.4, 3, 60);
2378
+ const fatMass = kg * bodyfat / 100;
2379
+ const leanMass = kg - fatMass;
2380
+ const waistM = m * 0.43 * (bmi / 22) ** 0.6;
2381
+ const hipsM = waistM * (male ? 1.05 : 1.2);
2382
+ const chestM = waistM * 1.1;
2383
+ const bri = 364.2 - 365.5 * Math.sqrt(Math.max(0, 1 - (waistM / (2 * Math.PI)) ** 2 / (0.5 * m) ** 2));
2384
+ const metabolicAge = clamp(Math.round(age + (bodyfat - (male ? 18 : 25)) / 2), 10, 120);
2385
+ const chronological = Math.floor(age);
2386
+ return {
2387
+ kg,
2388
+ m,
2389
+ bmi,
2390
+ bodyfat: {
2391
+ bodyfatMethod: scan.bodyfatMethod,
2392
+ bodyfatPercentage: round(bodyfat, 1),
2393
+ leanMass: round(leanMass),
2394
+ fatMass: round(fatMass),
2395
+ skeletalMuscleMass: round(leanMass * 0.5),
2396
+ unit: "kg"
2397
+ },
2398
+ measurementsMetric: {
2399
+ waistFit: round(waistM * 100),
2400
+ hipsFit: round(hipsM * 100),
2401
+ chestFit: round(chestM * 100),
2402
+ waistToHipRatio: round(waistM / hipsM, 3),
2403
+ bodyRoundnessIndex: round(bri, 2),
2404
+ bmiPredicted: round(bmi, 1),
2405
+ unit: "cm"
2406
+ },
2407
+ measurementsImperial: {
2408
+ waistFit: round(waistM / INCHES_TO_METERS * 1),
2409
+ hipsFit: round(hipsM / INCHES_TO_METERS),
2410
+ chestFit: round(chestM / INCHES_TO_METERS),
2411
+ waistToHipRatio: round(waistM / hipsM, 3),
2412
+ bodyRoundnessIndex: round(bri, 2),
2413
+ bmiPredicted: round(bmi, 1),
2414
+ unit: "in"
2415
+ },
2416
+ healthReport: {
2417
+ metabolicAgeReport: {
2418
+ metabolicAgeYears: metabolicAge,
2419
+ chronologicalAgeYears: chronological,
2420
+ ageDeltaYears: metabolicAge - chronological,
2421
+ percentile: clamp(50 - (metabolicAge - chronological) * 3, 1, 99)
2422
+ },
2423
+ bodyShapeReport: { bmi: round(bmi, 1), category: bmi < 25 ? "healthy" : "elevated" }
2424
+ }
2425
+ };
2426
+ };
2427
+ var PrismAPI = class {
2428
+ app;
2429
+ sqlite;
2430
+ state;
2431
+ service;
2432
+ now;
2433
+ prefix;
2434
+ constructor(options = {}) {
2435
+ const sqlite = bootSqlite(options.sqlite);
2436
+ const namespace = options.namespace ?? PRISM_NAMESPACE;
2437
+ this.now = options.now ?? (() => Date.now());
2438
+ this.prefix = options.publicNamespace && options.publicNamespace !== "default" ? `/ns/${encodeURIComponent(options.publicNamespace)}` : "";
2439
+ this.state = new PrismState(sqlite, namespace, options.settings ?? {});
2440
+ const handlers = defineOperations({
2441
+ UpsertUser: (context) => this.upsertUser(context),
2442
+ CreateScan: (context) => this.createScan(context),
2443
+ GetScan: (context) => {
2444
+ const scan = this.scan(context);
2445
+ const body = this.scanBody(scan, context.query["unit-system"] === "imperial");
2446
+ if (faultEffect(context.request, "schema_drift") !== void 0) {
2447
+ Object.assign(body, { status: "QUEUED" });
2448
+ }
2449
+ return annotateResponse(jsonRes(200, body), { ids: { scanId: scan.id } });
2450
+ },
2451
+ CreateUploadUrl: (context) => this.uploadUrl(context),
2452
+ GetScanAssets: (context) => {
2453
+ const scan = this.scan(context);
2454
+ const out = {};
2455
+ for (const stage of STAGES) {
2456
+ out[stage] = scan.stages[stage]?.status ?? null;
2457
+ out[`${stage}UpdatedAt`] = scan.stages[stage]?.updatedAt ?? null;
2458
+ }
2459
+ return jsonRes(200, out);
2460
+ },
2461
+ GetBodyfat: (context) => {
2462
+ const { results } = this.ready(context);
2463
+ return jsonRes(200, results.bodyfat);
2464
+ },
2465
+ GetMeasurements: (context) => {
2466
+ const { results } = this.ready(context);
2467
+ return jsonRes(
2468
+ 200,
2469
+ context.query["unit-system"] === "imperial" ? results.measurementsImperial : results.measurementsMetric
2470
+ );
2471
+ },
2472
+ GetHealthReport: (context) => {
2473
+ const { results } = this.ready(context);
2474
+ if (faultEffect(context.request, "metabolic_age_missing") !== void 0) {
2475
+ return jsonRes(200, { ...results.healthReport, metabolicAgeReport: null });
2476
+ }
2477
+ if (faultEffect(context.request, "metabolic_age_implausible") !== void 0) {
2478
+ return jsonRes(200, {
2479
+ ...results.healthReport,
2480
+ metabolicAgeReport: {
2481
+ metabolicAgeYears: 150,
2482
+ chronologicalAgeYears: results.healthReport.metabolicAgeReport.chronologicalAgeYears,
2483
+ ageDeltaYears: null,
2484
+ percentile: null
2485
+ }
2486
+ });
2487
+ }
2488
+ return jsonRes(200, results.healthReport);
2489
+ },
2490
+ GetAssetUrls: (context) => {
2491
+ const { scan } = this.ready(context);
2492
+ const origin = new URL(context.request.url).origin;
2493
+ const expires = this.now() + 36e5;
2494
+ return jsonRes(
2495
+ 200,
2496
+ Object.fromEntries(
2497
+ Object.entries(ASSET_FILES).map(([key, file]) => [
2498
+ key,
2499
+ `${origin}${this.prefix}/assets/${scan.id}/${file}?expires=${expires}&signature=${opaqueToken(`${scan.id}:${file}:${expires}`, 24)}`
2500
+ ])
2501
+ )
2502
+ );
2503
+ },
2504
+ UploadCapture: (context) => this.upload(context),
2505
+ GetAsset: (context) => {
2506
+ const scan = this.state.scans.get(context.params.scanId ?? "");
2507
+ const file = context.params.file ?? "";
2508
+ if (scan?.status !== "READY" || !Object.values(ASSET_FILES).includes(file)) {
2509
+ return new Response(null, { status: 404 });
2510
+ }
2511
+ return new Response(new TextEncoder().encode(`prism-mock:${scan.id}:${file}`), {
2512
+ status: 200,
2513
+ headers: { "content-type": "application/octet-stream" }
2514
+ });
2515
+ }
2516
+ });
2517
+ this.service = createService({
2518
+ document,
2519
+ handlers,
2520
+ sqlite,
2521
+ namespace,
2522
+ now: this.now,
2523
+ notFound: () => prismError(404, "Not Found"),
2524
+ onError: (error) => {
2525
+ if (error instanceof HttpError) return error.toResponse();
2526
+ throw error;
2527
+ },
2528
+ before: (context) => {
2529
+ this.tick();
2530
+ const id = context.operation.operationId;
2531
+ if (id === "UploadCapture" || id === "GetAsset") return void 0;
2532
+ const key = bearerToken(context.request);
2533
+ const allowed = this.state.current().apiKeys;
2534
+ if (!key || allowed.length > 0 && !allowed.includes(key)) {
2535
+ return prismError(401, "Unauthorized");
2536
+ }
2537
+ return void 0;
2538
+ }
2539
+ });
2540
+ this.app = this.service.app;
2541
+ this.sqlite = this.service.sqlite;
2542
+ }
2543
+ fetch(request) {
2544
+ return this.service.fetch(request);
2545
+ }
2546
+ async reset() {
2547
+ await this.service.reset();
2548
+ this.state.ensureSeeded();
2549
+ }
2550
+ iso() {
2551
+ return new Date(this.now()).toISOString();
2552
+ }
2553
+ body(context) {
2554
+ const issues = bodyIssues(context);
2555
+ if (issues.length > 0) {
2556
+ throw new HttpError(400, {
2557
+ message: "Validation failed",
2558
+ errors: issues.map((issue) => ({ field: issue.path || "body", message: issue.message }))
2559
+ });
2560
+ }
2561
+ return context.body.kind === "json" ? context.body.value : {};
2562
+ }
2563
+ scan(context) {
2564
+ const scan = this.state.scans.get(context.params.scanId ?? "");
2565
+ if (!scan) throw new HttpError(404, { message: "Scan not found" });
2566
+ return scan;
2567
+ }
2568
+ ready(context) {
2569
+ const scan = this.scan(context);
2570
+ if (scan.status !== "READY") {
2571
+ throw new HttpError(404, { message: "Scan results are not available" });
2572
+ }
2573
+ return { scan, results: scanResults(scan, this.state.user(scan.userToken), this.now()) };
2574
+ }
2575
+ scanBody(scan, imperial) {
2576
+ const kg = kilograms(scan.weight);
2577
+ const m = meters(scan.height);
2578
+ return {
2579
+ id: scan.id,
2580
+ status: scan.status,
2581
+ userToken: scan.userToken,
2582
+ deviceConfigName: scan.deviceConfigName,
2583
+ bodyfatMethod: scan.bodyfatMethod,
2584
+ assetConfigId: scan.assetConfigId,
2585
+ weight: imperial ? { value: round(kg / POUNDS_TO_KILOGRAMS), unit: "lb" } : { value: round(kg), unit: "kg" },
2586
+ height: imperial ? { value: round(m / INCHES_TO_METERS), unit: "in" } : { value: round(m, 3), unit: "m" },
2587
+ createdAt: scan.createdAt,
2588
+ updatedAt: scan.updatedAt
2589
+ };
2590
+ }
2591
+ upsertUser(context) {
2592
+ const body = this.body(context);
2593
+ const token = String(body.token);
2594
+ const existing = this.state.user(token);
2595
+ const now = this.iso();
2596
+ const user = {
2597
+ id: existing?.id ?? this.state.ids.next("usr_", 20),
2598
+ token,
2599
+ sex: body.sex,
2600
+ region: String(body.region),
2601
+ birthDate: String(body.birthDate),
2602
+ weight: body.weight,
2603
+ height: body.height,
2604
+ researchConsent: Boolean(body.researchConsent),
2605
+ termsOfService: body.termsOfService,
2606
+ createdAt: existing?.createdAt ?? now,
2607
+ updatedAt: now
2608
+ };
2609
+ this.state.users.insert(token, user);
2610
+ return annotateResponse(jsonRes(existing ? 200 : 201, user), { ids: { userId: user.id } });
2611
+ }
2612
+ createScan(context) {
2613
+ const body = this.body(context);
2614
+ const user = this.state.user(String(body.userToken));
2615
+ if (!user) return prismError(404, "User not found");
2616
+ const now = this.iso();
2617
+ const token = this.state.ids.next("scan", 32).toLowerCase();
2618
+ const id = `${token.slice(0, 8)}-${token.slice(8, 12)}-4${token.slice(13, 16)}-a${token.slice(17, 20)}-${token.slice(20, 32)}`;
2619
+ const scan = {
2620
+ id,
2621
+ status: "CREATED",
2622
+ userToken: user.token,
2623
+ deviceConfigName: String(body.deviceConfigName),
2624
+ bodyfatMethod: String(body.bodyfatMethod),
2625
+ assetConfigId: typeof body.assetConfigId === "string" ? body.assetConfigId : null,
2626
+ weight: user.weight,
2627
+ height: user.height,
2628
+ stages: {},
2629
+ upload: null,
2630
+ uploadedBytes: null,
2631
+ uploadedAtMs: null,
2632
+ createdAt: now,
2633
+ updatedAt: now
2634
+ };
2635
+ this.state.scans.insert(id, scan);
2636
+ return annotateResponse(jsonRes(201, this.scanBody(scan, false)), { ids: { scanId: id } });
2637
+ }
2638
+ uploadUrl(context) {
2639
+ const scan = this.scan(context);
2640
+ if (scan.status !== "CREATED") return prismError(409, "Scan capture already uploaded");
2641
+ const expiresAtMs = this.now() + this.state.current().uploadUrlTtlMs;
2642
+ const signature = opaqueToken(`${scan.id}:${expiresAtMs}`, 24);
2643
+ this.state.scans.update(scan.id, { ...scan, upload: { signature, expiresAtMs } });
2644
+ const origin = new URL(context.request.url).origin;
2645
+ return annotateResponse(
2646
+ jsonRes(200, {
2647
+ url: `${origin}${this.prefix}/uploads/${scan.id}?expires=${expiresAtMs}&signature=${signature}`,
2648
+ expirationTime: new Date(expiresAtMs).toISOString()
2649
+ }),
2650
+ { ids: { scanId: scan.id } }
2651
+ );
2652
+ }
2653
+ upload(context) {
2654
+ const s3Error = (code, message) => new Response(
2655
+ `<?xml version="1.0" encoding="UTF-8"?><Error><Code>${code}</Code><Message>${message}</Message></Error>`,
2656
+ {
2657
+ status: 403,
2658
+ headers: { "content-type": "application/xml" }
2659
+ }
2660
+ );
2661
+ const scan = this.state.scans.get(context.params.scanId ?? "");
2662
+ if (!scan) return new Response(null, { status: 404 });
2663
+ const expires = Number(context.query.expires);
2664
+ if (!scan.upload || String(context.query.signature) !== scan.upload.signature || expires !== scan.upload.expiresAtMs) {
2665
+ return s3Error(
2666
+ "SignatureDoesNotMatch",
2667
+ "The request signature we calculated does not match the signature you provided."
2668
+ );
2669
+ }
2670
+ if (this.now() > expires) return s3Error("AccessDenied", "Request has expired");
2671
+ const body = context.body;
2672
+ const bytes = body.kind === "bytes" ? body.value.byteLength : body.kind === "text" ? new TextEncoder().encode(body.value).byteLength : body.kind === "empty" ? 0 : 1;
2673
+ if (scan.status === "CREATED") {
2674
+ const now = this.iso();
2675
+ const next = bytes === 0 ? {
2676
+ ...scan,
2677
+ status: "FAILED",
2678
+ stages: { captureData: { status: "failed", updatedAt: now } },
2679
+ uploadedBytes: 0,
2680
+ updatedAt: now
2681
+ } : {
2682
+ ...scan,
2683
+ status: "PROCESSING",
2684
+ stages: {
2685
+ captureData: { status: "succeeded", updatedAt: now },
2686
+ body: { status: "started", updatedAt: now }
2687
+ },
2688
+ uploadedBytes: bytes,
2689
+ uploadedAtMs: this.now(),
2690
+ updatedAt: now
2691
+ };
2692
+ this.state.scans.update(scan.id, next);
2693
+ }
2694
+ return annotateResponse(
2695
+ new Response(null, {
2696
+ status: 200,
2697
+ headers: { etag: `"${opaqueToken(`${scan.id}:${bytes}`, 32)}"` }
2698
+ }),
2699
+ {
2700
+ ids: { scanId: scan.id }
2701
+ }
2702
+ );
2703
+ }
2704
+ /**
2705
+ * Move a PROCESSING scan one stage on: the started stage succeeds (or fails, when `fail` is
2706
+ * set) and the next one starts; after `measurement` the scan is READY.
2707
+ */
2708
+ advance(scanId, fail = false) {
2709
+ const scan = this.state.scans.get(scanId);
2710
+ if (scan?.status !== "PROCESSING") return scan;
2711
+ const now = this.iso();
2712
+ const current = STAGES.find((stage) => scan.stages[stage]?.status === "started");
2713
+ if (!current) return scan;
2714
+ const stages = {
2715
+ ...scan.stages,
2716
+ [current]: { status: fail ? "failed" : "succeeded", updatedAt: now }
2717
+ };
2718
+ const nextStage = STAGES[STAGES.indexOf(current) + 1];
2719
+ if (!fail && nextStage) stages[nextStage] = { status: "started", updatedAt: now };
2720
+ const next = {
2721
+ ...scan,
2722
+ stages,
2723
+ status: fail ? "FAILED" : nextStage ? "PROCESSING" : "READY",
2724
+ updatedAt: now
2725
+ };
2726
+ this.state.scans.update(scanId, next);
2727
+ return next;
2728
+ }
2729
+ /** Walk every uploaded scan along the auto-advance plan, as far as the mock clock allows. */
2730
+ tick() {
2731
+ const plan = this.state.current().autoAdvance;
2732
+ if (!plan) return 0;
2733
+ let applied = 0;
2734
+ for (const { value } of this.state.scans.list({
2735
+ order: "oldest",
2736
+ where: (s) => s.status === "PROCESSING"
2737
+ })) {
2738
+ let scan = value;
2739
+ while (scan && scan.status === "PROCESSING" && scan.uploadedAtMs !== null) {
2740
+ const done = STAGES.filter((stage) => scan?.stages[stage]?.status === "succeeded").length;
2741
+ if (this.now() < scan.uploadedAtMs + plan.afterMs * done) break;
2742
+ const started = STAGES.find((stage) => scan?.stages[stage]?.status === "started");
2743
+ scan = this.advance(scan.id, started !== void 0 && started === plan.failAt);
2744
+ applied++;
2745
+ }
2746
+ }
2747
+ return applied;
2748
+ }
2749
+ scans() {
2750
+ return this.state.scans.list({ order: "oldest" }).map((r) => r.value);
2751
+ }
2752
+ };
2753
+
2754
+ export {
2755
+ document,
2756
+ operationIds,
2757
+ supportedOperationIds,
2758
+ STAGES,
2759
+ PRISM_PRESETS,
2760
+ createRuntime2 as createRuntime,
2761
+ PRISM_NAMESPACE,
2762
+ prismError,
2763
+ scanResults,
2764
+ PrismAPI
2765
+ };
2766
+ //# sourceMappingURL=chunk-P5X7EJGX.js.map