@crvouga/mockingbird-service-wholescripts 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,2785 @@
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 basicAuth = (request) => {
393
+ const header = request.headers.get("authorization");
394
+ if (!header)
395
+ return void 0;
396
+ const match = /^Basic\s+(.+)$/i.exec(header.trim());
397
+ if (!match?.[1])
398
+ return void 0;
399
+ let decoded;
400
+ try {
401
+ decoded = atob(match[1].trim());
402
+ } catch {
403
+ return void 0;
404
+ }
405
+ const colon = decoded.indexOf(":");
406
+ if (colon < 0)
407
+ return { username: decoded, password: "" };
408
+ return { username: decoded.slice(0, colon), password: decoded.slice(colon + 1) };
409
+ };
410
+ var createCredentialRegistry = () => {
411
+ const map = /* @__PURE__ */ new Map();
412
+ return {
413
+ set: (credential, namespace) => {
414
+ map.set(credential, namespace);
415
+ },
416
+ get: (credential) => map.get(credential),
417
+ remove: (credential) => map.delete(credential),
418
+ clear: () => map.clear(),
419
+ entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
420
+ };
421
+ };
422
+ var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
423
+
424
+ // ../core/dist/rng.js
425
+ var seedFrom = (value) => {
426
+ let hash = 2166136261;
427
+ for (let i = 0; i < value.length; i++) {
428
+ hash ^= value.charCodeAt(i);
429
+ hash = Math.imul(hash, 16777619);
430
+ }
431
+ return hash >>> 0;
432
+ };
433
+ var createRng = (seed = 0) => {
434
+ const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
435
+ let state = numeric;
436
+ const next = () => {
437
+ state = state + 1831565813 >>> 0;
438
+ let t = state;
439
+ t = Math.imul(t ^ t >>> 15, t | 1);
440
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
441
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
442
+ };
443
+ return {
444
+ next,
445
+ int: (min, max) => min + Math.floor(next() * (max - min + 1)),
446
+ reset: () => {
447
+ state = numeric;
448
+ },
449
+ state: () => state,
450
+ setState: (next2) => {
451
+ if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
452
+ throw new RangeError("rng state must be an unsigned 32-bit integer");
453
+ }
454
+ state = next2 >>> 0;
455
+ },
456
+ seed: numeric
457
+ };
458
+ };
459
+
460
+ // ../core/dist/faults.js
461
+ var matches = (rule, candidate) => {
462
+ if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
463
+ return false;
464
+ }
465
+ if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
466
+ return false;
467
+ if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
468
+ return false;
469
+ }
470
+ if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
471
+ return false;
472
+ return true;
473
+ };
474
+ var faultResponse = (rule) => {
475
+ const status = rule.status ?? 500;
476
+ const headers = { "content-type": "application/json", ...rule.headers };
477
+ if (typeof rule.body === "string")
478
+ return new Response(rule.body, { status, headers });
479
+ if (rule.body === null)
480
+ return new Response(null, { status, headers: rule.headers ?? {} });
481
+ const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
482
+ return new Response(JSON.stringify(body), { status, headers });
483
+ };
484
+ var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
485
+ const entries = [];
486
+ return {
487
+ add(rule) {
488
+ const existing = entries.findIndex((e) => e.rule.id === rule.id);
489
+ const entry = { rule, remaining: rule.count ?? null, hits: 0 };
490
+ if (existing >= 0)
491
+ entries[existing] = entry;
492
+ else
493
+ entries.push(entry);
494
+ return rule;
495
+ },
496
+ list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
497
+ remove(id) {
498
+ const index = entries.findIndex((e) => e.rule.id === id);
499
+ if (index < 0)
500
+ return false;
501
+ entries.splice(index, 1);
502
+ return true;
503
+ },
504
+ clear() {
505
+ entries.length = 0;
506
+ },
507
+ async take(candidate) {
508
+ const hits = [];
509
+ for (const entry of entries) {
510
+ if (entry.remaining === 0)
511
+ continue;
512
+ if (!matches(entry.rule, candidate))
513
+ continue;
514
+ const rate = entry.rule.rate ?? 1;
515
+ if (rng.next() >= rate)
516
+ continue;
517
+ entry.hits++;
518
+ if (entry.remaining !== null)
519
+ entry.remaining--;
520
+ const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
521
+ if (delay !== void 0 && delay > 0) {
522
+ await sleep(delay);
523
+ }
524
+ const hit = { id: entry.rule.id };
525
+ if (entry.rule.effect !== void 0) {
526
+ hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
527
+ }
528
+ if (entry.rule.drop === true)
529
+ hit.drop = true;
530
+ else if (entry.rule.status !== void 0)
531
+ hit.response = faultResponse(entry.rule);
532
+ hits.push(hit);
533
+ if (hit.drop || hit.response)
534
+ break;
535
+ }
536
+ return hits;
537
+ }
538
+ };
539
+ };
540
+
541
+ // ../../openapi/core/dist/refs.js
542
+ var OpenAPIReferenceError = class extends Error {
543
+ ref;
544
+ constructor(ref) {
545
+ super(`unresolvable $ref: ${ref}`);
546
+ this.ref = ref;
547
+ this.name = "OpenAPIReferenceError";
548
+ }
549
+ };
550
+ var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
551
+ var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
552
+ var resolveRef = (document2, ref) => {
553
+ if (!ref.startsWith("#/"))
554
+ throw new OpenAPIReferenceError(ref);
555
+ let cursor = document2;
556
+ for (const raw of ref.slice(2).split("/")) {
557
+ const segment = unescapePointer(raw);
558
+ if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
559
+ throw new OpenAPIReferenceError(ref);
560
+ }
561
+ cursor = cursor[segment];
562
+ }
563
+ if (cursor === void 0)
564
+ throw new OpenAPIReferenceError(ref);
565
+ return cursor;
566
+ };
567
+ var deref = (document2, value) => {
568
+ let current = value;
569
+ const seen = /* @__PURE__ */ new Set();
570
+ while (isReference(current)) {
571
+ if (seen.has(current.$ref))
572
+ throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
573
+ seen.add(current.$ref);
574
+ current = resolveRef(document2, current.$ref);
575
+ }
576
+ return current;
577
+ };
578
+
579
+ // ../../openapi/core/dist/types.js
580
+ var HTTP_METHODS = [
581
+ "get",
582
+ "put",
583
+ "post",
584
+ "delete",
585
+ "options",
586
+ "head",
587
+ "patch",
588
+ "trace"
589
+ ];
590
+
591
+ // ../../openapi/core/dist/document.js
592
+ var mergeParameters = (document2, item, own) => {
593
+ const merged = /* @__PURE__ */ new Map();
594
+ for (const raw of item.parameters ?? []) {
595
+ const parameter = deref(document2, raw);
596
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
597
+ }
598
+ for (const raw of own ?? []) {
599
+ const parameter = deref(document2, raw);
600
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
601
+ }
602
+ return [...merged.values()];
603
+ };
604
+ var listOperations = (document2) => {
605
+ const operations = [];
606
+ for (const [path, item] of Object.entries(document2.paths)) {
607
+ for (const method of HTTP_METHODS) {
608
+ const operation = item[method];
609
+ if (operation?.operationId === void 0)
610
+ continue;
611
+ const responses = {};
612
+ for (const [status, response] of Object.entries(operation.responses)) {
613
+ responses[status] = deref(document2, response);
614
+ }
615
+ operations.push({
616
+ operationId: operation.operationId,
617
+ method,
618
+ path,
619
+ operation,
620
+ parameters: mergeParameters(document2, item, operation.parameters),
621
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
622
+ responses
623
+ });
624
+ }
625
+ }
626
+ return operations;
627
+ };
628
+
629
+ // ../../openapi/core/dist/schema.js
630
+ var resolveSchema = (document2, schema) => {
631
+ let current = schema;
632
+ const seen = /* @__PURE__ */ new Set();
633
+ while (typeof current.$ref === "string") {
634
+ const ref = current.$ref;
635
+ if (seen.has(ref))
636
+ break;
637
+ seen.add(ref);
638
+ const { $ref: _ignored, ...siblings } = current;
639
+ const target = resolveRef(document2, ref);
640
+ current = { ...target, ...siblings };
641
+ }
642
+ if (current.nullable === true) {
643
+ const { nullable: _nullable, ...rest } = current;
644
+ const types = schemaTypes(rest);
645
+ if (types.length > 0 && !types.includes("null"))
646
+ current = { ...rest, type: [...types, "null"] };
647
+ else
648
+ current = rest;
649
+ }
650
+ return current;
651
+ };
652
+ var schemaTypes = (schema) => {
653
+ if (Array.isArray(schema.type))
654
+ return schema.type;
655
+ if (schema.type !== void 0)
656
+ return [schema.type];
657
+ const inferred = [];
658
+ if (schema.properties || schema.required || schema.additionalProperties !== void 0)
659
+ inferred.push("object");
660
+ if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
661
+ inferred.push("array");
662
+ if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
663
+ inferred.push("string");
664
+ if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
665
+ inferred.push("number");
666
+ return inferred;
667
+ };
668
+ var jsonTypeOf = (value) => {
669
+ if (value === null)
670
+ return "null";
671
+ if (Array.isArray(value))
672
+ return "array";
673
+ switch (typeof value) {
674
+ case "string":
675
+ return "string";
676
+ case "boolean":
677
+ return "boolean";
678
+ case "number":
679
+ return Number.isInteger(value) ? "integer" : "number";
680
+ case "object":
681
+ return "object";
682
+ default:
683
+ return "undefined";
684
+ }
685
+ };
686
+ var deepEqual = (a, b) => {
687
+ if (a === b)
688
+ return true;
689
+ if (typeof a !== typeof b || a === null || b === null)
690
+ return false;
691
+ if (Array.isArray(a)) {
692
+ return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
693
+ }
694
+ if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
695
+ const ka = Object.keys(a);
696
+ const kb = Object.keys(b);
697
+ return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
698
+ }
699
+ return false;
700
+ };
701
+ var FORMAT_PATTERNS = {
702
+ 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,
703
+ date: /^\d{4}-\d{2}-\d{2}$/,
704
+ "date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
705
+ email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
706
+ uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
707
+ ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
708
+ };
709
+ var graphemeLength = (value) => [...value].length;
710
+ var validateValue = (document2, schema, value, path = []) => {
711
+ const errors = [];
712
+ const s = resolveSchema(document2, schema);
713
+ const fail = (message) => errors.push({ path, message });
714
+ const actual = jsonTypeOf(value);
715
+ if (actual === "undefined") {
716
+ fail("value is undefined");
717
+ return errors;
718
+ }
719
+ const types = schemaTypes(s);
720
+ if (types.length > 0) {
721
+ const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
722
+ if (!ok) {
723
+ fail(`expected type ${types.join("|")}, got ${actual}`);
724
+ return errors;
725
+ }
726
+ }
727
+ if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
728
+ fail("value not in enum");
729
+ }
730
+ if (s.const !== void 0 && !deepEqual(s.const, value))
731
+ fail("value does not equal const");
732
+ if (typeof value === "string") {
733
+ const length = graphemeLength(value);
734
+ if (s.minLength !== void 0 && length < s.minLength)
735
+ fail(`length ${length} < minLength ${s.minLength}`);
736
+ if (s.maxLength !== void 0 && length > s.maxLength)
737
+ fail(`length ${length} > maxLength ${s.maxLength}`);
738
+ if (s.pattern !== void 0) {
739
+ try {
740
+ if (!new RegExp(s.pattern, "u").test(value))
741
+ fail(`does not match pattern ${s.pattern}`);
742
+ } catch {
743
+ }
744
+ }
745
+ if (s.format !== void 0) {
746
+ const pattern = FORMAT_PATTERNS[s.format];
747
+ if (pattern && !pattern.test(value))
748
+ fail(`does not match format ${s.format}`);
749
+ }
750
+ }
751
+ if (typeof value === "number") {
752
+ if (s.minimum !== void 0 && value < s.minimum)
753
+ fail(`${value} < minimum ${s.minimum}`);
754
+ if (s.maximum !== void 0 && value > s.maximum)
755
+ fail(`${value} > maximum ${s.maximum}`);
756
+ if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
757
+ fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
758
+ if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
759
+ fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
760
+ if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
761
+ fail(`${value} is not a multiple of ${s.multipleOf}`);
762
+ }
763
+ }
764
+ if (Array.isArray(value)) {
765
+ if (s.minItems !== void 0 && value.length < s.minItems)
766
+ fail(`${value.length} items < minItems ${s.minItems}`);
767
+ if (s.maxItems !== void 0 && value.length > s.maxItems)
768
+ fail(`${value.length} items > maxItems ${s.maxItems}`);
769
+ if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
770
+ fail("items are not unique");
771
+ value.forEach((item, i) => {
772
+ const itemSchema = s.prefixItems?.[i] ?? s.items;
773
+ if (itemSchema)
774
+ errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
775
+ });
776
+ }
777
+ if (actual === "object") {
778
+ const record2 = value;
779
+ const keys = Object.keys(record2);
780
+ for (const name of s.required ?? [])
781
+ if (!(name in record2))
782
+ fail(`missing required property ${name}`);
783
+ if (s.minProperties !== void 0 && keys.length < s.minProperties)
784
+ fail(`${keys.length} properties < minProperties ${s.minProperties}`);
785
+ if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
786
+ fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
787
+ for (const key of keys) {
788
+ const property = s.properties?.[key];
789
+ if (property) {
790
+ errors.push(...validateValue(document2, property, record2[key], [...path, key]));
791
+ continue;
792
+ }
793
+ if (s.additionalProperties === false)
794
+ fail(`unexpected property ${key}`);
795
+ else if (typeof s.additionalProperties === "object") {
796
+ errors.push(...validateValue(document2, s.additionalProperties, record2[key], [...path, key]));
797
+ }
798
+ if (s.propertyNames) {
799
+ const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
800
+ if (nameErrors.length > 0)
801
+ fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
802
+ }
803
+ }
804
+ }
805
+ if (s.allOf)
806
+ for (const branch of s.allOf)
807
+ errors.push(...validateValue(document2, branch, value, path));
808
+ if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
809
+ fail("matches no anyOf branch");
810
+ if (s.oneOf) {
811
+ const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
812
+ if (matches2 !== 1)
813
+ fail(`matches ${matches2} oneOf branches, expected exactly 1`);
814
+ }
815
+ if (s.not && validateValue(document2, s.not, value).length === 0)
816
+ fail("matches forbidden `not` schema");
817
+ return errors;
818
+ };
819
+
820
+ // ../../http/codec/dist/form.js
821
+ var parsePath = (rawKey) => {
822
+ const open = rawKey.indexOf("[");
823
+ if (open === -1)
824
+ return [rawKey];
825
+ const path = [rawKey.slice(0, open)];
826
+ const rest = rawKey.slice(open);
827
+ const pattern = /\[([^\]]*)\]/g;
828
+ let match = pattern.exec(rest);
829
+ let consumed = 0;
830
+ while (match !== null) {
831
+ if (match.index !== consumed)
832
+ return [rawKey];
833
+ path.push(match[1] ?? "");
834
+ consumed = match.index + match[0].length;
835
+ match = pattern.exec(rest);
836
+ }
837
+ if (consumed !== rest.length)
838
+ return [rawKey];
839
+ return path;
840
+ };
841
+ var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
842
+ var put = (target, key, value) => {
843
+ if (key === "__proto__") {
844
+ Object.defineProperty(target, key, {
845
+ value,
846
+ enumerable: true,
847
+ writable: true,
848
+ configurable: true
849
+ });
850
+ return;
851
+ }
852
+ ;
853
+ target[key] = value;
854
+ };
855
+ var assign = (target, path, value) => {
856
+ let cursor = target;
857
+ for (let i = 0; i < path.length; i++) {
858
+ const segment = path[i];
859
+ const last = i === path.length - 1;
860
+ if (Array.isArray(cursor)) {
861
+ const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
862
+ if (index === void 0)
863
+ return;
864
+ if (last) {
865
+ put(cursor, index, value);
866
+ return;
867
+ }
868
+ const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
869
+ if (next === void 0 || typeof next === "string") {
870
+ const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
871
+ put(cursor, index, created);
872
+ cursor = created;
873
+ } else {
874
+ cursor = next;
875
+ }
876
+ continue;
877
+ }
878
+ if (typeof cursor === "string")
879
+ return;
880
+ if (last) {
881
+ put(cursor, segment, value);
882
+ return;
883
+ }
884
+ const nextSegment = path[i + 1];
885
+ const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
886
+ if (existing === void 0 || typeof existing === "string") {
887
+ const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
888
+ put(cursor, segment, created);
889
+ cursor = created;
890
+ } else {
891
+ cursor = existing;
892
+ }
893
+ }
894
+ };
895
+ var decodeFormPairs = (pairs) => {
896
+ const out = {};
897
+ for (const [rawKey, value] of pairs)
898
+ assign(out, parsePath(rawKey), value);
899
+ return densify(out);
900
+ };
901
+ var densify = (value) => {
902
+ if (typeof value === "string")
903
+ return value;
904
+ if (Array.isArray(value))
905
+ return value.filter((item) => item !== void 0).map(densify);
906
+ const out = {};
907
+ for (const [key, item] of Object.entries(value))
908
+ put(out, key, densify(item));
909
+ return out;
910
+ };
911
+ var decodeForm = (text) => {
912
+ const source = text.startsWith("?") ? text.slice(1) : text;
913
+ return decodeFormPairs(new URLSearchParams(source).entries());
914
+ };
915
+
916
+ // ../../http/codec/dist/content.js
917
+ var JSON_MEDIA_TYPE = "application/json";
918
+ var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
919
+ var mediaTypeOf = (contentType) => {
920
+ if (!contentType)
921
+ return void 0;
922
+ const essence = contentType.split(";")[0]?.trim().toLowerCase();
923
+ return essence ? essence : void 0;
924
+ };
925
+ var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
926
+ var utf8 = new TextDecoder("utf-8", { fatal: false });
927
+ var decodeBody = (contentType, bytes) => {
928
+ if (bytes.byteLength === 0)
929
+ return { kind: "empty" };
930
+ const mediaType = mediaTypeOf(contentType);
931
+ if (mediaType === void 0)
932
+ return { kind: "bytes", value: bytes };
933
+ if (isJsonMediaType(mediaType)) {
934
+ const text = utf8.decode(bytes);
935
+ try {
936
+ return { kind: "json", value: JSON.parse(text) };
937
+ } catch (error) {
938
+ return {
939
+ kind: "invalid",
940
+ mediaType,
941
+ text,
942
+ error: error instanceof Error ? error.message : String(error)
943
+ };
944
+ }
945
+ }
946
+ if (mediaType === FORM_MEDIA_TYPE) {
947
+ return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
948
+ }
949
+ if (mediaType.startsWith("text/"))
950
+ return { kind: "text", value: utf8.decode(bytes) };
951
+ return { kind: "bytes", value: bytes };
952
+ };
953
+ var readBody = async (message) => {
954
+ const bytes = new Uint8Array(await message.arrayBuffer());
955
+ return decodeBody(message.headers.get("content-type"), bytes);
956
+ };
957
+
958
+ // ../core/dist/http.js
959
+ var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
960
+ status,
961
+ headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
962
+ });
963
+ var HttpError = class extends Error {
964
+ status;
965
+ body;
966
+ headers;
967
+ constructor(status, body, headers = {}) {
968
+ super(`HTTP ${status}`);
969
+ this.status = status;
970
+ this.body = body;
971
+ this.headers = headers;
972
+ this.name = "HttpError";
973
+ }
974
+ toResponse() {
975
+ const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
976
+ if (contentType === "text/plain") {
977
+ return new Response(String(this.body), {
978
+ status: this.status,
979
+ headers: this.headers
980
+ });
981
+ }
982
+ return jsonRes(this.status, this.body, this.headers);
983
+ }
984
+ };
985
+
986
+ // ../core/dist/ids.js
987
+ var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
988
+ var mix = (input) => {
989
+ let hash = 2166136261;
990
+ for (let i = 0; i < input.length; i++) {
991
+ hash ^= input.charCodeAt(i);
992
+ hash = Math.imul(hash, 16777619) >>> 0;
993
+ }
994
+ hash ^= hash >>> 16;
995
+ hash = Math.imul(hash, 2246822507) >>> 0;
996
+ hash ^= hash >>> 13;
997
+ return hash >>> 0;
998
+ };
999
+ var opaqueToken = (input, length) => {
1000
+ let out = "";
1001
+ let round = 0;
1002
+ while (out.length < length) {
1003
+ let hash = mix(`${input}:${round++}`);
1004
+ for (let i = 0; i < 5 && out.length < length; i++) {
1005
+ out += ALPHABET.charAt(hash % ALPHABET.length);
1006
+ hash = Math.floor(hash / ALPHABET.length);
1007
+ }
1008
+ }
1009
+ return out;
1010
+ };
1011
+
1012
+ // ../core/dist/journal.js
1013
+ var DEFAULT_JOURNAL_SIZE = 1e3;
1014
+ var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
1015
+ const capacity = Math.max(0, Math.floor(size));
1016
+ const rings = /* @__PURE__ */ new Map();
1017
+ let sequence = 0;
1018
+ const order = /* @__PURE__ */ new WeakMap();
1019
+ const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
1020
+ return {
1021
+ size: capacity,
1022
+ record(entry) {
1023
+ if (capacity === 0)
1024
+ return;
1025
+ order.set(entry, sequence++);
1026
+ let ring = rings.get(entry.namespace);
1027
+ if (!ring) {
1028
+ ring = { entries: [], next: 0 };
1029
+ rings.set(entry.namespace, ring);
1030
+ }
1031
+ if (ring.entries.length < capacity)
1032
+ ring.entries.push(entry);
1033
+ else {
1034
+ ring.entries[ring.next] = entry;
1035
+ ring.next = (ring.next + 1) % capacity;
1036
+ }
1037
+ },
1038
+ list(query = {}) {
1039
+ 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));
1040
+ 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));
1041
+ return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
1042
+ },
1043
+ clear(namespace) {
1044
+ if (namespace === void 0)
1045
+ rings.clear();
1046
+ else
1047
+ rings.delete(namespace);
1048
+ }
1049
+ };
1050
+ };
1051
+ var notes = /* @__PURE__ */ new WeakMap();
1052
+ var annotateResponse = (response, extra) => {
1053
+ const existing = notes.get(response);
1054
+ notes.set(response, {
1055
+ ...existing,
1056
+ ...extra,
1057
+ ...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
1058
+ });
1059
+ return response;
1060
+ };
1061
+ var responseNotes = (response) => notes.get(response);
1062
+
1063
+ // ../core/dist/metrics.js
1064
+ var createMetrics = () => {
1065
+ let requests = 0;
1066
+ let faults = 0;
1067
+ let totalDurationMs = 0;
1068
+ const byOperation = /* @__PURE__ */ new Map();
1069
+ const unmatched = /* @__PURE__ */ new Map();
1070
+ return {
1071
+ record(entry) {
1072
+ requests++;
1073
+ totalDurationMs += entry.durationMs;
1074
+ if (entry.faultId !== void 0)
1075
+ faults++;
1076
+ const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
1077
+ byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
1078
+ if (entry.unmatched) {
1079
+ const route = `${entry.method} ${entry.path}`;
1080
+ unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
1081
+ }
1082
+ },
1083
+ report: () => ({
1084
+ requests,
1085
+ byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
1086
+ unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
1087
+ const space = route.indexOf(" ");
1088
+ return { method: route.slice(0, space), path: route.slice(space + 1), count };
1089
+ }),
1090
+ faults,
1091
+ totalDurationMs
1092
+ }),
1093
+ reset() {
1094
+ requests = 0;
1095
+ faults = 0;
1096
+ totalDurationMs = 0;
1097
+ byOperation.clear();
1098
+ unmatched.clear();
1099
+ }
1100
+ };
1101
+ };
1102
+
1103
+ // ../../core/dist/timeline.js
1104
+ var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1105
+ var Timeline = class {
1106
+ maxCheckpoints;
1107
+ now;
1108
+ makeId;
1109
+ nodes = /* @__PURE__ */ new Map();
1110
+ heads = /* @__PURE__ */ new Map();
1111
+ /** Unreferenced nodes in the exact order they became collectible. */
1112
+ evictable = /* @__PURE__ */ new Set();
1113
+ /** Branch heads plus explicit retainers. Absent means zero. */
1114
+ references = /* @__PURE__ */ new Map();
1115
+ explicitPins = /* @__PURE__ */ new Map();
1116
+ sequence = 0;
1117
+ constructor(options = {}) {
1118
+ const max = options.maxCheckpoints ?? 1e3;
1119
+ if (!Number.isSafeInteger(max) || max < 1)
1120
+ throw new RangeError("maxCheckpoints must be a positive integer");
1121
+ this.maxCheckpoints = max;
1122
+ this.now = options.now ?? (() => this.sequence);
1123
+ this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
1124
+ }
1125
+ /** Capture a new immutable value and move `branch` to it. */
1126
+ commit(value, options = {}) {
1127
+ const branch = options.branch ?? "main";
1128
+ this.assertBranch(branch);
1129
+ const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
1130
+ if (parent !== null && !this.nodes.has(parent))
1131
+ throw new RangeError(`no checkpoint ${parent}`);
1132
+ const id = this.makeId(++this.sequence);
1133
+ if (this.nodes.has(id))
1134
+ throw new RangeError(`duplicate checkpoint id ${id}`);
1135
+ const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
1136
+ this.nodes.set(id, checkpoint);
1137
+ this.moveHead(branch, id);
1138
+ this.collect(this.maxCheckpoints);
1139
+ return checkpoint;
1140
+ }
1141
+ /** Create a branch pointer without copying its checkpoint value. */
1142
+ fork(branch, options = {}) {
1143
+ this.assertBranch(branch);
1144
+ if (this.heads.has(branch))
1145
+ throw new RangeError(`branch already exists: ${branch}`);
1146
+ const from = options.from ?? this.heads.get("main");
1147
+ if (from === void 0)
1148
+ return void 0;
1149
+ const checkpoint = this.get(from);
1150
+ this.moveHead(branch, checkpoint.id);
1151
+ return checkpoint;
1152
+ }
1153
+ /** Move a branch pointer to an existing checkpoint. */
1154
+ checkout(branch, id) {
1155
+ this.assertBranch(branch);
1156
+ const checkpoint = this.get(id);
1157
+ this.moveHead(branch, checkpoint.id);
1158
+ return checkpoint;
1159
+ }
1160
+ get(id) {
1161
+ const checkpoint = this.nodes.get(id);
1162
+ if (!checkpoint)
1163
+ throw new RangeError(`no checkpoint ${id}`);
1164
+ return checkpoint;
1165
+ }
1166
+ head(branch = "main") {
1167
+ const id = this.heads.get(branch);
1168
+ return id === void 0 ? void 0 : this.get(id);
1169
+ }
1170
+ hasBranch(branch) {
1171
+ return this.heads.has(branch);
1172
+ }
1173
+ branches() {
1174
+ return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
1175
+ }
1176
+ checkpoints() {
1177
+ return [...this.nodes.values()];
1178
+ }
1179
+ /** Number of retained checkpoints without allocating an array. */
1180
+ get size() {
1181
+ return this.nodes.size;
1182
+ }
1183
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
1184
+ retain(id) {
1185
+ const checkpoint = this.get(id);
1186
+ this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
1187
+ this.addReference(id);
1188
+ return checkpoint;
1189
+ }
1190
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
1191
+ release(id) {
1192
+ if (!this.nodes.has(id))
1193
+ return false;
1194
+ const pins = this.explicitPins.get(id) ?? 0;
1195
+ if (pins === 0)
1196
+ return false;
1197
+ if (pins === 1)
1198
+ this.explicitPins.delete(id);
1199
+ else
1200
+ this.explicitPins.set(id, pins - 1);
1201
+ this.removeReference(id);
1202
+ this.collect(this.maxCheckpoints);
1203
+ return true;
1204
+ }
1205
+ deleteBranch(branch) {
1206
+ if (branch === "main")
1207
+ throw new RangeError("cannot delete main branch");
1208
+ const previous = this.heads.get(branch);
1209
+ const deleted = this.heads.delete(branch);
1210
+ if (previous !== void 0)
1211
+ this.removeReference(previous);
1212
+ this.collect(this.maxCheckpoints);
1213
+ return deleted;
1214
+ }
1215
+ /**
1216
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
1217
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
1218
+ * storage dependency, so a retained node remains usable after pruning.
1219
+ */
1220
+ gc(max = this.maxCheckpoints) {
1221
+ if (!Number.isSafeInteger(max) || max < 1)
1222
+ throw new RangeError("max must be a positive integer");
1223
+ const removed = [];
1224
+ this.collect(max, removed);
1225
+ return removed;
1226
+ }
1227
+ collect(max, removed) {
1228
+ while (this.nodes.size > max && this.evictable.size > 0) {
1229
+ const id = this.evictable.values().next().value;
1230
+ this.evictable.delete(id);
1231
+ this.nodes.delete(id);
1232
+ removed?.push(id);
1233
+ }
1234
+ }
1235
+ moveHead(branch, id) {
1236
+ const previous = this.heads.get(branch);
1237
+ if (previous === id)
1238
+ return;
1239
+ if (previous !== void 0)
1240
+ this.removeReference(previous);
1241
+ this.heads.set(branch, id);
1242
+ this.addReference(id);
1243
+ }
1244
+ addReference(id) {
1245
+ this.references.set(id, (this.references.get(id) ?? 0) + 1);
1246
+ this.evictable.delete(id);
1247
+ }
1248
+ removeReference(id) {
1249
+ const next = (this.references.get(id) ?? 0) - 1;
1250
+ if (next > 0)
1251
+ this.references.set(id, next);
1252
+ else {
1253
+ this.references.delete(id);
1254
+ if (this.nodes.has(id))
1255
+ this.evictable.add(id);
1256
+ }
1257
+ }
1258
+ assertBranch(branch) {
1259
+ if (!BRANCH_PATTERN.test(branch))
1260
+ throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
1261
+ }
1262
+ };
1263
+
1264
+ // ../../sqlite/dist/default.js
1265
+ import { Database } from "@crvouga/mockingbird-service-sqlite";
1266
+ var createDefaultSqlite = () => new Database();
1267
+ var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
1268
+
1269
+ // ../../sqlite/dist/migrate.js
1270
+ var ensureMigrationsTable = (sqlite) => {
1271
+ sqlite.exec(`
1272
+ CREATE TABLE IF NOT EXISTS schema_migrations (
1273
+ id TEXT PRIMARY KEY NOT NULL,
1274
+ applied_at INTEGER NOT NULL
1275
+ )
1276
+ `);
1277
+ };
1278
+ var migrate = (sqlite, migrations) => {
1279
+ ensureMigrationsTable(sqlite);
1280
+ const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
1281
+ const pending = migrations.filter((migration) => !applied.has(migration.id));
1282
+ if (pending.length === 0)
1283
+ return;
1284
+ const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
1285
+ const now = Math.floor(Date.now() / 1e3);
1286
+ sqlite.transaction(() => {
1287
+ for (const migration of pending) {
1288
+ sqlite.exec(migration.sql);
1289
+ insert.run(migration.id, now);
1290
+ }
1291
+ });
1292
+ };
1293
+
1294
+ // ../../sqlite/dist/schema.js
1295
+ var CORE_MIGRATIONS = [
1296
+ {
1297
+ id: "20260322_core_records_sequences",
1298
+ sql: `
1299
+ CREATE TABLE IF NOT EXISTS mockingbird_records (
1300
+ namespace TEXT NOT NULL,
1301
+ collection TEXT NOT NULL,
1302
+ id TEXT NOT NULL,
1303
+ seq INTEGER NOT NULL,
1304
+ value TEXT NOT NULL,
1305
+ PRIMARY KEY (namespace, collection, id)
1306
+ );
1307
+ CREATE INDEX IF NOT EXISTS mockingbird_records_seq
1308
+ ON mockingbird_records (namespace, collection, seq);
1309
+ CREATE TABLE IF NOT EXISTS mockingbird_sequences (
1310
+ namespace TEXT NOT NULL,
1311
+ name TEXT NOT NULL,
1312
+ kind TEXT NOT NULL,
1313
+ value INTEGER NOT NULL,
1314
+ PRIMARY KEY (namespace, name, kind)
1315
+ );
1316
+ `
1317
+ }
1318
+ ];
1319
+ var migrateCore = (sqlite) => {
1320
+ migrate(sqlite, CORE_MIGRATIONS);
1321
+ };
1322
+ var clearNamespace = (sqlite, namespace) => {
1323
+ sqlite.transaction(() => {
1324
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1325
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1326
+ });
1327
+ };
1328
+
1329
+ // ../../openapi/metadata/dist/types.js
1330
+ var EXTENSION_KEYS = {
1331
+ operation: "x-mockingbird",
1332
+ resource: "x-mockingbird-resource",
1333
+ resourceRef: "x-mockingbird-resource-ref",
1334
+ volatile: "x-mockingbird-volatile",
1335
+ scope: "x-mockingbird-scope",
1336
+ unsupported: "x-mockingbird-unsupported",
1337
+ parityHeader: "x-mockingbird-parity-header"
1338
+ };
1339
+
1340
+ // ../../openapi/metadata/dist/read.js
1341
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1342
+ var extensionOf = (holder, key) => holder[key];
1343
+ var operationMetadata = (operation) => {
1344
+ const raw = extensionOf(operation, EXTENSION_KEYS.operation);
1345
+ const ext = isRecord2(raw) ? raw : {};
1346
+ const supported = ext.supported ?? true;
1347
+ const parity = ext.parity ?? {};
1348
+ return {
1349
+ supported,
1350
+ reason: typeof ext.reason === "string" ? ext.reason : void 0,
1351
+ parity: {
1352
+ enabled: supported && (parity.enabled ?? true),
1353
+ safe: parity.safe ?? true,
1354
+ reason: typeof parity.reason === "string" ? parity.reason : void 0
1355
+ }
1356
+ };
1357
+ };
1358
+
1359
+ // ../core/dist/service.js
1360
+ import { Hono } from "hono";
1361
+ var defineOperations = (handlers) => handlers;
1362
+ var OperationRegistryError = class extends Error {
1363
+ problems;
1364
+ constructor(problems) {
1365
+ super(`operation registry is inconsistent:
1366
+ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1367
+ this.problems = problems;
1368
+ this.name = "OperationRegistryError";
1369
+ }
1370
+ };
1371
+ var verifyOperations = (document2, handlers) => {
1372
+ const problems = [];
1373
+ const operations = listOperations(document2);
1374
+ const seen = /* @__PURE__ */ new Set();
1375
+ for (const operation of operations) {
1376
+ if (seen.has(operation.operationId))
1377
+ problems.push(`duplicate operationId ${operation.operationId}`);
1378
+ seen.add(operation.operationId);
1379
+ const supported = operationMetadata(operation.operation).supported;
1380
+ const handler = handlers[operation.operationId];
1381
+ if (supported && !handler)
1382
+ problems.push(`supported operation ${operation.operationId} has no handler`);
1383
+ if (!supported && handler)
1384
+ problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
1385
+ }
1386
+ for (const id of Object.keys(handlers)) {
1387
+ if (!seen.has(id))
1388
+ problems.push(`handler ${id} has no OpenAPI operation`);
1389
+ }
1390
+ return problems;
1391
+ };
1392
+ var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
1393
+ var routeOrder = (a, b) => {
1394
+ const sa = a.path.split("/");
1395
+ const sb = b.path.split("/");
1396
+ for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
1397
+ const x = sa[i] ?? "";
1398
+ const y = sb[i] ?? "";
1399
+ const px = x.startsWith("{");
1400
+ const py = y.startsWith("{");
1401
+ if (px !== py)
1402
+ return px ? 1 : -1;
1403
+ if (x !== y)
1404
+ return x < y ? -1 : 1;
1405
+ }
1406
+ return 0;
1407
+ };
1408
+ var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
1409
+ var bootSqlite = (sqlite) => {
1410
+ const client = resolveSqlite(sqlite);
1411
+ migrateCore(client);
1412
+ return client;
1413
+ };
1414
+ var createService = (options) => {
1415
+ const problems = verifyOperations(options.document, options.handlers);
1416
+ if (problems.length > 0)
1417
+ throw new OperationRegistryError(problems);
1418
+ migrateCore(options.sqlite);
1419
+ const now = options.now ?? (() => Date.now());
1420
+ const app = new Hono();
1421
+ app.notFound((c) => options.notFound(c.req.raw));
1422
+ app.onError((error, c) => options.onError(error, c.req.raw));
1423
+ const operations = [...listOperations(options.document)].sort(routeOrder);
1424
+ for (const operation of operations) {
1425
+ const metadata = operationMetadata(operation.operation);
1426
+ const handler = options.handlers[operation.operationId];
1427
+ const route = async (c) => {
1428
+ const request = c.req.raw;
1429
+ if (!metadata.supported || !handler) {
1430
+ return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
1431
+ }
1432
+ const url = new URL(request.url);
1433
+ const context = {
1434
+ request,
1435
+ url,
1436
+ params: c.req.param(),
1437
+ query: queryOf(url),
1438
+ body: await readBody(request),
1439
+ sqlite: options.sqlite,
1440
+ namespace: options.namespace,
1441
+ operation,
1442
+ document: options.document,
1443
+ now
1444
+ };
1445
+ const short = await options.before?.(context);
1446
+ if (short)
1447
+ return short;
1448
+ return handler(context);
1449
+ };
1450
+ app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
1451
+ }
1452
+ return {
1453
+ app,
1454
+ sqlite: options.sqlite,
1455
+ namespace: options.namespace,
1456
+ fetch: async (request) => app.fetch(request),
1457
+ reset: async () => {
1458
+ clearNamespace(options.sqlite, options.namespace);
1459
+ }
1460
+ };
1461
+ };
1462
+
1463
+ // ../core/dist/snapshot.js
1464
+ var snapshotNamespace = (sqlite, namespace) => ({
1465
+ namespace,
1466
+ records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
1467
+ sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
1468
+ });
1469
+ var restoreNamespace = (sqlite, namespace, snapshot) => {
1470
+ sqlite.transaction(() => {
1471
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1472
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1473
+ const record2 = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
1474
+ for (const row of snapshot.records) {
1475
+ record2.run(namespace, row.collection, row.id, row.seq, row.value);
1476
+ }
1477
+ const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
1478
+ for (const row of snapshot.sequences) {
1479
+ sequence.run(namespace, row.name, row.kind, row.value);
1480
+ }
1481
+ });
1482
+ };
1483
+
1484
+ // ../core/dist/version.js
1485
+ var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
1486
+
1487
+ // ../core/dist/webhooks.js
1488
+ var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1489
+ var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
1490
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1491
+ var parseEndpoint = (value) => {
1492
+ if (!isRecord3(value) || typeof value.url !== "string")
1493
+ return "each endpoint needs a url";
1494
+ try {
1495
+ new URL(value.url);
1496
+ } catch {
1497
+ return `not a URL: ${value.url}`;
1498
+ }
1499
+ const endpoint = { url: value.url };
1500
+ if (typeof value.id === "string")
1501
+ endpoint.id = value.id;
1502
+ if (typeof value.secret === "string")
1503
+ endpoint.secret = value.secret;
1504
+ if (typeof value.signUrl === "string")
1505
+ endpoint.signUrl = value.signUrl;
1506
+ const events = value.events ?? value.enabledEvents;
1507
+ if (Array.isArray(events))
1508
+ endpoint.events = events.map(String);
1509
+ if (isRecord3(value.tags)) {
1510
+ endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1511
+ }
1512
+ if (typeof value.account === "string")
1513
+ endpoint.tags = { ...endpoint.tags, account: value.account };
1514
+ if (isRecord3(value.headers)) {
1515
+ endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1516
+ }
1517
+ return endpoint;
1518
+ };
1519
+ var webhookAdminRoutes = (hub) => ({
1520
+ "GET /webhooks": ({ url, namespace }) => json2(200, {
1521
+ deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1522
+ const type = url.searchParams.get("type");
1523
+ return type === null || d.type === type;
1524
+ })
1525
+ }),
1526
+ "GET /webhooks/events": ({ url, namespace }) => {
1527
+ const type = url.searchParams.get("type");
1528
+ return json2(200, {
1529
+ events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1530
+ });
1531
+ },
1532
+ "POST /webhooks/:id/replay": async ({ params }) => {
1533
+ const replayed = await hub.replay(params.id);
1534
+ return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
1535
+ },
1536
+ "POST /webhooks/flush": async () => {
1537
+ await hub.flush();
1538
+ return json2(200, { status: "ok" });
1539
+ },
1540
+ "POST /webhooks/faults": ({ body, namespace }) => {
1541
+ if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1542
+ return adminError2(400, "mode must be duplicate, reorder or drop");
1543
+ }
1544
+ const fault = { mode: body.mode };
1545
+ if (typeof body.count === "number")
1546
+ fault.count = body.count;
1547
+ hub.fault(namespace, fault);
1548
+ return json2(201, { namespace, ...fault });
1549
+ },
1550
+ "GET /webhook-endpoints": ({ namespace }) => json2(200, {
1551
+ endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1552
+ ...rest,
1553
+ secret: secret ? "(set)" : null
1554
+ }))
1555
+ }),
1556
+ "PUT /webhook-endpoints": ({ body, namespace }) => {
1557
+ const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
1558
+ if (!Array.isArray(list))
1559
+ return adminError2(400, "expected [{url, secret?, events?}]");
1560
+ const parsed = [];
1561
+ for (const each of list) {
1562
+ const endpoint = parseEndpoint(each);
1563
+ if (typeof endpoint === "string")
1564
+ return adminError2(400, endpoint);
1565
+ parsed.push(endpoint);
1566
+ }
1567
+ const set = hub.setEndpoints(namespace, parsed);
1568
+ return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1569
+ },
1570
+ "DELETE /webhook-endpoints": ({ namespace }) => {
1571
+ hub.setEndpoints(namespace, []);
1572
+ return json2(200, { status: "ok" });
1573
+ }
1574
+ });
1575
+ var parsePayload = (message) => {
1576
+ if (message.contentType.startsWith("application/json")) {
1577
+ try {
1578
+ return JSON.parse(message.body);
1579
+ } catch {
1580
+ return message.body;
1581
+ }
1582
+ }
1583
+ if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
1584
+ return Object.fromEntries(new URLSearchParams(message.body));
1585
+ }
1586
+ return message.body;
1587
+ };
1588
+
1589
+ // ../core/dist/runtime.js
1590
+ var MOCKINGBIRD_HEADER = "x-mockingbird";
1591
+ var BRANCH_HEADER = "x-mockingbird-branch";
1592
+ var AT_HEADER = "x-mockingbird-at";
1593
+ var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
1594
+ var DEFAULT_NAMESPACE = "default";
1595
+ var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1596
+ var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
1597
+ var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
1598
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
1599
+ var effects = /* @__PURE__ */ new WeakMap();
1600
+ var reuseSorted = (fresh, previous, compare, equal) => {
1601
+ if (!previous || previous.length === 0)
1602
+ return fresh.map((row) => Object.freeze(row));
1603
+ const result = new Array(fresh.length);
1604
+ let unchanged = fresh.length === previous.length;
1605
+ let oldIndex = 0;
1606
+ for (let index = 0; index < fresh.length; index++) {
1607
+ const row = fresh[index];
1608
+ while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
1609
+ oldIndex++;
1610
+ }
1611
+ const old = previous[oldIndex];
1612
+ result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
1613
+ if (result[index] !== previous[index])
1614
+ unchanged = false;
1615
+ }
1616
+ return unchanged ? previous : result;
1617
+ };
1618
+ var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
1619
+ var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
1620
+ var DroppedConnectionError = class extends TypeError {
1621
+ code = "MOCKINGBIRD_DROP";
1622
+ constructor() {
1623
+ super("fetch failed: connection dropped by Mockingbird fault");
1624
+ this.name = "TypeError";
1625
+ }
1626
+ };
1627
+ var operationMatcher = (document2) => {
1628
+ const matchers = listOperations(document2).map((operation) => ({
1629
+ operationId: operation.operationId,
1630
+ method: operation.method.toUpperCase(),
1631
+ pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
1632
+ params: (operation.path.match(/\{/g) ?? []).length
1633
+ })).sort((a, b) => a.params - b.params);
1634
+ return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
1635
+ };
1636
+ var createRuntime = (options) => {
1637
+ const sqlite = bootSqlite(options.sqlite);
1638
+ const clock = options.clock ?? createClock();
1639
+ const rng = createRng(options.seed ?? 0);
1640
+ const wallNow = options.io?.wallNow ?? Date.now;
1641
+ const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
1642
+ const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1643
+ const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
1644
+ const metrics = createMetrics();
1645
+ const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
1646
+ const version = options.version ?? PACKAGE_VERSION;
1647
+ const instances = /* @__PURE__ */ new Map();
1648
+ const publicNamespaces = /* @__PURE__ */ new Set();
1649
+ const branchRngs = /* @__PURE__ */ new Map();
1650
+ const timelines = /* @__PURE__ */ new Map();
1651
+ const branchStorage = /* @__PURE__ */ new Map();
1652
+ const captured = /* @__PURE__ */ new Map();
1653
+ const credentials = createCredentialRegistry();
1654
+ const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
1655
+ const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
1656
+ const instanceFor = (key, publicNamespace = key, isolatedRng) => {
1657
+ const existing = instances.get(key);
1658
+ if (existing)
1659
+ return existing;
1660
+ if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
1661
+ throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
1662
+ }
1663
+ const created = options.create({
1664
+ namespace: storageNamespace(key),
1665
+ publicNamespace,
1666
+ sqlite,
1667
+ clock,
1668
+ rng: isolatedRng ?? rng
1669
+ });
1670
+ instances.set(key, created);
1671
+ publicNamespaces.add(publicNamespace);
1672
+ if (isolatedRng)
1673
+ branchRngs.set(key, isolatedRng);
1674
+ return created;
1675
+ };
1676
+ const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
1677
+ const capture = (storage) => {
1678
+ const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
1679
+ const previous = captured.get(storage);
1680
+ const snapshot2 = {
1681
+ namespace: fresh.namespace,
1682
+ 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),
1683
+ 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)
1684
+ };
1685
+ Object.freeze(snapshot2.records);
1686
+ Object.freeze(snapshot2.sequences);
1687
+ Object.freeze(snapshot2);
1688
+ captured.set(storage, snapshot2);
1689
+ return Object.freeze({
1690
+ snapshot: snapshot2,
1691
+ clock: Object.freeze(clock.state()),
1692
+ rngState: (branchRngs.get(storage) ?? rng).state()
1693
+ });
1694
+ };
1695
+ const timeline = (name = DEFAULT_NAMESPACE) => {
1696
+ let found = timelines.get(name);
1697
+ if (found)
1698
+ return found;
1699
+ instance(name);
1700
+ found = new Timeline({
1701
+ now: clock.now,
1702
+ ...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
1703
+ });
1704
+ found.commit(capture(name));
1705
+ timelines.set(name, found);
1706
+ return found;
1707
+ };
1708
+ const physicalBranch = (namespace, branch2) => {
1709
+ if (branch2 === "main")
1710
+ return namespace;
1711
+ const mapKey = `${namespace}\0${branch2}`;
1712
+ const existing = branchStorage.get(mapKey);
1713
+ if (existing)
1714
+ return existing;
1715
+ const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
1716
+ branchStorage.set(mapKey, key);
1717
+ return key;
1718
+ };
1719
+ const ensureBranch = (namespace, branch2, at) => {
1720
+ if (!BRANCH_PATTERN2.test(branch2))
1721
+ throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
1722
+ const history = timeline(namespace);
1723
+ if (branch2 === "main") {
1724
+ if (at !== void 0) {
1725
+ const point = history.checkout("main", at);
1726
+ restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
1727
+ captured.set(namespace, point.value.snapshot);
1728
+ rng.setState(point.value.rngState);
1729
+ clock.set(point.value.clock.now);
1730
+ if (point.value.clock.frozen)
1731
+ clock.freeze();
1732
+ else
1733
+ clock.unfreeze();
1734
+ }
1735
+ return namespace;
1736
+ }
1737
+ const storage = physicalBranch(namespace, branch2);
1738
+ if (!history.hasBranch(branch2)) {
1739
+ if (at === void 0)
1740
+ history.commit(capture(namespace));
1741
+ const point = history.fork(branch2, at === void 0 ? {} : { from: at });
1742
+ const branchRng = createRng(options.seed ?? 0);
1743
+ if (point)
1744
+ branchRng.setState(point.value.rngState);
1745
+ instanceFor(storage, namespace, branchRng);
1746
+ if (point)
1747
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1748
+ if (point)
1749
+ captured.set(storage, point.value.snapshot);
1750
+ } else if (at !== void 0 && history.head(branch2)?.id !== at) {
1751
+ const point = history.checkout(branch2, at);
1752
+ if (!instances.has(storage)) {
1753
+ const branchRng = createRng(options.seed ?? 0);
1754
+ branchRng.setState(point.value.rngState);
1755
+ instanceFor(storage, namespace, branchRng);
1756
+ }
1757
+ branchRngs.get(storage)?.setState(point.value.rngState);
1758
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1759
+ captured.set(storage, point.value.snapshot);
1760
+ } else {
1761
+ if (!instances.has(storage)) {
1762
+ const point = history.head(branch2);
1763
+ const branchRng = createRng(options.seed ?? 0);
1764
+ if (point)
1765
+ branchRng.setState(point.value.rngState);
1766
+ instanceFor(storage, namespace, branchRng);
1767
+ }
1768
+ }
1769
+ return storage;
1770
+ };
1771
+ const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
1772
+ const storage = ensureBranch(namespace, branch2);
1773
+ return timeline(namespace).commit(capture(storage), { branch: branch2 });
1774
+ };
1775
+ const branch = (name, branchOptions = {}) => {
1776
+ const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
1777
+ ensureBranch(namespace, name, branchOptions.at);
1778
+ const head = timeline(namespace).head(name);
1779
+ if (!head)
1780
+ throw new RangeError(`branch ${name} has no checkpoint`);
1781
+ return head;
1782
+ };
1783
+ const checkout = (checkpointId, checkoutOptions = {}) => {
1784
+ const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
1785
+ const branchName = checkoutOptions.branch ?? "main";
1786
+ const history = timeline(namespace);
1787
+ const point = history.checkout(branchName, checkpointId);
1788
+ const storage = ensureBranch(namespace, branchName);
1789
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1790
+ captured.set(storage, point.value.snapshot);
1791
+ clock.set(point.value.clock.now);
1792
+ if (point.value.clock.frozen)
1793
+ clock.freeze();
1794
+ else
1795
+ clock.unfreeze();
1796
+ (branchRngs.get(storage) ?? rng).setState(point.value.rngState);
1797
+ };
1798
+ const reset = async (name = DEFAULT_NAMESPACE) => {
1799
+ if (name === "*") {
1800
+ options.webhooks?.clear();
1801
+ for (const each of instances.values())
1802
+ await each.reset();
1803
+ timelines.clear();
1804
+ branchStorage.clear();
1805
+ branchRngs.clear();
1806
+ captured.clear();
1807
+ return;
1808
+ }
1809
+ options.webhooks?.clear(name);
1810
+ const target = instances.get(name);
1811
+ if (target)
1812
+ await target.reset();
1813
+ else
1814
+ clearNamespace(sqlite, storageNamespace(name));
1815
+ for (const [mapping, storage] of branchStorage) {
1816
+ if (!mapping.startsWith(`${name}\0`))
1817
+ continue;
1818
+ const branchInstance = instances.get(storage);
1819
+ if (branchInstance)
1820
+ await branchInstance.reset();
1821
+ else
1822
+ clearNamespace(sqlite, storageNamespace(storage));
1823
+ branchStorage.delete(mapping);
1824
+ branchRngs.delete(storage);
1825
+ captured.delete(storage);
1826
+ }
1827
+ timelines.delete(name);
1828
+ captured.delete(name);
1829
+ };
1830
+ const snapshot = (name = DEFAULT_NAMESPACE) => {
1831
+ return checkpoint(name, "main").value.snapshot;
1832
+ };
1833
+ const restore = (from, name = DEFAULT_NAMESPACE) => {
1834
+ instance(name);
1835
+ restoreNamespace(sqlite, storageNamespace(name), from);
1836
+ captured.set(name, from);
1837
+ const history = timelines.get(name);
1838
+ if (history)
1839
+ history.commit(capture(name), { branch: "main" });
1840
+ else
1841
+ timeline(name);
1842
+ };
1843
+ const runtime = {
1844
+ name: options.name,
1845
+ sqlite,
1846
+ clock,
1847
+ faults,
1848
+ metrics,
1849
+ journal,
1850
+ rng,
1851
+ credentials,
1852
+ webhooks: options.webhooks,
1853
+ applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
1854
+ const preset = options.presets?.[name];
1855
+ if (!preset)
1856
+ throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
1857
+ const added = (preset.rules ?? []).map((rule, index) => faults.add({
1858
+ namespace,
1859
+ ...rule,
1860
+ ...overrides,
1861
+ preset: name,
1862
+ id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
1863
+ }));
1864
+ if (preset.webhook && options.webhooks) {
1865
+ options.webhooks.fault(namespace, {
1866
+ ...preset.webhook,
1867
+ ...overrides.count !== void 0 ? { count: overrides.count } : {}
1868
+ });
1869
+ }
1870
+ return added;
1871
+ },
1872
+ instance,
1873
+ namespaces: () => [...publicNamespaces].sort(),
1874
+ reset,
1875
+ snapshot,
1876
+ restore,
1877
+ checkpoint,
1878
+ branch,
1879
+ checkout,
1880
+ timeline,
1881
+ fetch: async (incoming) => {
1882
+ let request = incoming;
1883
+ const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
1884
+ if (prefixed) {
1885
+ const url2 = new URL(request.url);
1886
+ url2.pathname = prefixed[2] ?? "/";
1887
+ const headers = new Headers(request.headers);
1888
+ if (!headers.has(NAMESPACE_HEADER)) {
1889
+ headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
1890
+ }
1891
+ const hasBody = request.method !== "GET" && request.method !== "HEAD";
1892
+ request = new Request(url2, {
1893
+ method: request.method,
1894
+ headers,
1895
+ ...hasBody ? { body: await request.arrayBuffer() } : {},
1896
+ signal: request.signal
1897
+ });
1898
+ }
1899
+ let namespace = control.namespaceOf(request);
1900
+ if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
1901
+ const credential = options.credential(request);
1902
+ const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
1903
+ if (mapped !== void 0)
1904
+ namespace = mapped;
1905
+ }
1906
+ const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
1907
+ const at = request.headers.get(AT_HEADER) ?? void 0;
1908
+ const stamp = (response2) => {
1909
+ const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
1910
+ try {
1911
+ response2.headers.set(MOCKINGBIRD_HEADER, value);
1912
+ return response2;
1913
+ } catch {
1914
+ const copy = new Response(response2.body, response2);
1915
+ copy.headers.set(MOCKINGBIRD_HEADER, value);
1916
+ return copy;
1917
+ }
1918
+ };
1919
+ const handled = await control.handle(request);
1920
+ if (handled)
1921
+ return stamp(handled);
1922
+ const started = monotonicNow();
1923
+ const url = new URL(request.url);
1924
+ const operationId = operationIdFor(request, url.pathname);
1925
+ const log = (status, faultId, response2) => {
1926
+ const noted = response2 ? responseNotes(response2) : void 0;
1927
+ const entry = {
1928
+ service: options.name,
1929
+ namespace,
1930
+ operationId,
1931
+ method: request.method,
1932
+ path: url.pathname,
1933
+ status,
1934
+ durationMs: Math.round((monotonicNow() - started) * 100) / 100,
1935
+ unmatched: options.document !== void 0 && operationId === void 0,
1936
+ ...faultId !== void 0 ? { faultId } : {},
1937
+ ...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
1938
+ ...noted?.adopted ? { adopted: true } : {}
1939
+ };
1940
+ metrics.record(entry);
1941
+ journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
1942
+ options.onLog?.(entry);
1943
+ };
1944
+ if (!NAMESPACE_PATTERN.test(namespace)) {
1945
+ log(400);
1946
+ return stamp(new Response(JSON.stringify({
1947
+ error: {
1948
+ type: "mockingbird_admin",
1949
+ message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
1950
+ }
1951
+ }), { status: 400, headers: { "content-type": "application/json" } }));
1952
+ }
1953
+ if (!BRANCH_PATTERN2.test(selectedBranch)) {
1954
+ log(400);
1955
+ return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
1956
+ }
1957
+ let storage;
1958
+ try {
1959
+ if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
1960
+ const point = timeline(namespace).get(at);
1961
+ storage = physicalBranch(namespace, `at_${at}`);
1962
+ let viewRng = branchRngs.get(storage);
1963
+ if (!viewRng) {
1964
+ viewRng = createRng(options.seed ?? 0);
1965
+ instanceFor(storage, namespace, viewRng);
1966
+ }
1967
+ viewRng.setState(point.value.rngState);
1968
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
1969
+ captured.set(storage, point.value.snapshot);
1970
+ } else {
1971
+ storage = ensureBranch(namespace, selectedBranch, at);
1972
+ }
1973
+ } catch (error) {
1974
+ log(409);
1975
+ return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
1976
+ }
1977
+ const hits = await faults.take({
1978
+ operationId,
1979
+ method: request.method,
1980
+ path: url.pathname,
1981
+ namespace
1982
+ });
1983
+ const final = hits.find((hit) => hit.drop || hit.response);
1984
+ if (final?.drop) {
1985
+ log(0, final.id);
1986
+ throw new DroppedConnectionError();
1987
+ }
1988
+ if (final?.response) {
1989
+ log(final.response.status, final.id);
1990
+ return stamp(final.response);
1991
+ }
1992
+ const fired = hits.filter((hit) => hit.effect !== void 0);
1993
+ if (fired.length > 0)
1994
+ effects.set(request, fired.map((hit) => hit.effect));
1995
+ let response = await instanceFor(storage, namespace).fetch(request);
1996
+ if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
1997
+ const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
1998
+ response = mutableResponse(response);
1999
+ response.headers.set(CHECKPOINT_HEADER, point.id);
2000
+ }
2001
+ if (selectedBranch !== "main") {
2002
+ response = mutableResponse(response);
2003
+ response.headers.set(BRANCH_HEADER, selectedBranch);
2004
+ }
2005
+ if (at !== void 0) {
2006
+ response = mutableResponse(response);
2007
+ response.headers.set(AT_HEADER, at);
2008
+ }
2009
+ log(response.status, fired[0]?.id, response);
2010
+ return stamp(response);
2011
+ }
2012
+ };
2013
+ const control = createControlPlane({
2014
+ name: options.name,
2015
+ startedAt: wallNow(),
2016
+ wallNow,
2017
+ clock,
2018
+ faults,
2019
+ metrics,
2020
+ journal,
2021
+ defaultNamespace: DEFAULT_NAMESPACE,
2022
+ namespaces: runtime.namespaces,
2023
+ reset,
2024
+ timeTravel: {
2025
+ checkpoint: (name, branchName) => {
2026
+ const point = checkpoint(name, branchName);
2027
+ return {
2028
+ id: point.id,
2029
+ branch: point.branch,
2030
+ parent: point.parent,
2031
+ at: point.at,
2032
+ records: point.value.snapshot.records.length
2033
+ };
2034
+ },
2035
+ branch: (branchName, branchOptions) => {
2036
+ const point = branch(branchName, branchOptions);
2037
+ return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
2038
+ },
2039
+ checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
2040
+ retain: (name, checkpointId) => {
2041
+ timeline(name).retain(checkpointId);
2042
+ },
2043
+ release: (name, checkpointId) => timeline(name).release(checkpointId),
2044
+ inspect: (name) => {
2045
+ const history = timeline(name);
2046
+ return {
2047
+ branches: history.branches(),
2048
+ checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
2049
+ id,
2050
+ branch: branchName,
2051
+ parent,
2052
+ at
2053
+ }))
2054
+ };
2055
+ }
2056
+ },
2057
+ describe: options.describe ?? (() => ({})),
2058
+ ...options.presets ? {
2059
+ applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
2060
+ } : {},
2061
+ routes: {
2062
+ ...credentialRoutes(credentials),
2063
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
2064
+ ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2065
+ ...options.admin?.(runtime) ?? {}
2066
+ },
2067
+ adminKey: options.adminKey
2068
+ });
2069
+ return runtime;
2070
+ };
2071
+ var mutableResponse = (response) => {
2072
+ try {
2073
+ response.headers.set("x-mockingbird-mutable-probe", "1");
2074
+ response.headers.delete("x-mockingbird-mutable-probe");
2075
+ return response;
2076
+ } catch {
2077
+ return new Response(response.body, response);
2078
+ }
2079
+ };
2080
+ var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2081
+ var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
2082
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2083
+ var credentialRoutes = (registry) => ({
2084
+ "GET /credentials": () => adminJson(200, {
2085
+ credentials: registry.entries().map(({ credential, namespace }) => ({
2086
+ credential: maskCredential(credential),
2087
+ namespace
2088
+ }))
2089
+ }),
2090
+ "PUT /credentials": ({ body, namespace }) => {
2091
+ const pairs = [];
2092
+ const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
2093
+ if (Array.isArray(list)) {
2094
+ for (const each of list) {
2095
+ if (typeof each === "string")
2096
+ pairs.push([each, namespace]);
2097
+ else if (isObject(each) && typeof each.credential === "string") {
2098
+ pairs.push([
2099
+ each.credential,
2100
+ typeof each.namespace === "string" ? each.namespace : namespace
2101
+ ]);
2102
+ } else
2103
+ return adminFail(400, "each entry is a credential string or {credential, namespace}");
2104
+ }
2105
+ } else if (isObject(list)) {
2106
+ for (const [credential, target] of Object.entries(list)) {
2107
+ if (typeof target !== "string")
2108
+ return adminFail(400, `namespace for ${credential} must be a string`);
2109
+ pairs.push([credential, target]);
2110
+ }
2111
+ } else if (isObject(body) && typeof body.credential === "string") {
2112
+ pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
2113
+ } else {
2114
+ return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
2115
+ }
2116
+ for (const [credential, target] of pairs) {
2117
+ if (!NAMESPACE_PATTERN.test(target))
2118
+ return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
2119
+ registry.set(credential, target);
2120
+ }
2121
+ return adminJson(200, { mapped: pairs.length });
2122
+ },
2123
+ "DELETE /credentials": ({ url }) => {
2124
+ const credential = url.searchParams.get("credential");
2125
+ if (credential === null)
2126
+ registry.clear();
2127
+ else
2128
+ registry.remove(credential);
2129
+ return adminJson(200, { status: "ok" });
2130
+ }
2131
+ });
2132
+ var presetRoutes = (presets, runtime) => ({
2133
+ "GET /faults/presets": () => adminJson(200, {
2134
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
2135
+ }),
2136
+ "POST /faults/presets/:name": ({ params, body, namespace }) => {
2137
+ const name = params.name;
2138
+ if (!presets[name])
2139
+ return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
2140
+ const overrides = isObject(body) ? body : {};
2141
+ return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
2142
+ }
2143
+ });
2144
+
2145
+ // ../core/dist/validation.js
2146
+ var bodyIssues = (context, contentType = "application/json") => {
2147
+ const requestBody = context.operation.operation.requestBody;
2148
+ if (!requestBody)
2149
+ return [];
2150
+ const resolved = deref(context.document, requestBody);
2151
+ const schema = resolved.content?.[contentType]?.schema;
2152
+ if (!schema)
2153
+ return [];
2154
+ const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
2155
+ if (context.body.kind === "invalid") {
2156
+ return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
2157
+ }
2158
+ if (value === void 0) {
2159
+ return resolved.required ? [{ path: "", message: "request body is required" }] : [];
2160
+ }
2161
+ return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
2162
+ };
2163
+
2164
+ // src/catalog.ts
2165
+ var MEDPAX_BOX_SKU = "000000000200095263";
2166
+ var product = (row) => ({
2167
+ upc: `1234567${row.sku.replace(/\D/g, "").padStart(5, "0")}`,
2168
+ productImage: `https://example.com/${row.sku.toLowerCase()}.jpg`,
2169
+ supplementFactsHTML: "<div>Facts</div>",
2170
+ brand: "Test Brand",
2171
+ ...row
2172
+ });
2173
+ var DEFAULT_CATALOG = {
2174
+ products: [
2175
+ product({
2176
+ productName: "Test Product 1",
2177
+ sku: "SKU001",
2178
+ medPaxSku: "MP001",
2179
+ categories: "Supplements",
2180
+ retailPrice: 29.99,
2181
+ upc: "123456789001",
2182
+ descriptionShort: "Test product 1 description",
2183
+ productImage: "https://example.com/image1.jpg",
2184
+ quantity: 100,
2185
+ countUnit: "capsules",
2186
+ wholesalePrice: 19.99,
2187
+ defaultDosing: [{ time: "AM", qty: 1 }]
2188
+ }),
2189
+ product({
2190
+ productName: "Test Product 2",
2191
+ sku: "SKU002",
2192
+ medPaxSku: "MP002",
2193
+ categories: "Vitamins",
2194
+ retailPrice: 39.99,
2195
+ upc: "123456789002",
2196
+ descriptionShort: "Test product 2 description",
2197
+ productImage: "https://example.com/image2.jpg",
2198
+ quantity: 50,
2199
+ countUnit: "tablets",
2200
+ wholesalePrice: 29.99,
2201
+ defaultDosing: [{ time: "PM", qty: 2 }]
2202
+ }),
2203
+ product({
2204
+ productName: "Vitamin D3",
2205
+ sku: "VD001",
2206
+ medPaxSku: "MPVD001",
2207
+ categories: "Vitamins,Supplements",
2208
+ retailPrice: 19.99,
2209
+ descriptionShort: "Vitamin D3 supplement",
2210
+ quantity: 100,
2211
+ countUnit: "capsules",
2212
+ wholesalePrice: 14.99,
2213
+ defaultDosing: [{ time: "AM", qty: 1 }],
2214
+ medPaxDetails: {
2215
+ name: "Vitamin D3 5000 IU",
2216
+ genericName: "Cholecalciferol",
2217
+ quantity: 400,
2218
+ wholesalePrice: 0.12,
2219
+ retailPrice: 0.2
2220
+ }
2221
+ }),
2222
+ product({
2223
+ productName: "Vitamin D Complex",
2224
+ sku: "VD002",
2225
+ medPaxSku: "MPVD002",
2226
+ categories: "Vitamins",
2227
+ retailPrice: 29.99,
2228
+ descriptionShort: "Vitamin D complex supplement",
2229
+ quantity: 50,
2230
+ countUnit: "tablets",
2231
+ wholesalePrice: 24.99,
2232
+ defaultDosing: [{ time: "PM", qty: 2 }]
2233
+ }),
2234
+ product({
2235
+ productName: "Calcium",
2236
+ sku: "CA001",
2237
+ medPaxSku: "MPCA001",
2238
+ categories: "Minerals",
2239
+ retailPrice: 19.99,
2240
+ descriptionShort: "Calcium supplement",
2241
+ quantity: 100,
2242
+ countUnit: "capsules",
2243
+ wholesalePrice: 14.99,
2244
+ defaultDosing: [{ time: "AM", qty: 1 }],
2245
+ medPaxDetails: {
2246
+ name: "Calcium Citrate",
2247
+ genericName: "Calcium citrate",
2248
+ quantity: 0,
2249
+ wholesalePrice: 0.1,
2250
+ retailPrice: 0.18
2251
+ }
2252
+ }),
2253
+ product({
2254
+ productName: "Protein Powder",
2255
+ sku: "PP001",
2256
+ medPaxSku: "MPPP001",
2257
+ categories: "Supplements",
2258
+ retailPrice: 49.99,
2259
+ descriptionShort: "Protein powder",
2260
+ quantity: 0,
2261
+ countUnit: "grams",
2262
+ wholesalePrice: 34.99,
2263
+ defaultDosing: [{ time: "AM", qty: 1 }]
2264
+ }),
2265
+ product({
2266
+ productName: "Longeviti Blend MedPax Box",
2267
+ sku: MEDPAX_BOX_SKU,
2268
+ medPaxSku: "",
2269
+ categories: "MedPax",
2270
+ retailPrice: 0,
2271
+ descriptionShort: "30-day AM/PM MedPax carton",
2272
+ quantity: 1e3,
2273
+ countUnit: "box",
2274
+ wholesalePrice: 0,
2275
+ defaultDosing: []
2276
+ })
2277
+ ],
2278
+ medPaxPills: [
2279
+ {
2280
+ sku: "PL001",
2281
+ genericName: "Generic Name 1",
2282
+ privateLabelName: "Private Label Product 1",
2283
+ quantity: 30
2284
+ },
2285
+ {
2286
+ sku: "MP001",
2287
+ genericName: "Generic Pill 1",
2288
+ privateLabelName: "MedPax Pill 1",
2289
+ quantity: 30
2290
+ },
2291
+ {
2292
+ sku: "MP002",
2293
+ genericName: "Generic Pill 2",
2294
+ privateLabelName: "MedPax Pill 2",
2295
+ quantity: 60
2296
+ }
2297
+ ],
2298
+ privateLabelCartons: [
2299
+ {
2300
+ sku: "PLC001",
2301
+ name: "Private Label Carton 1",
2302
+ cartonImage: "https://example.com/carton1.jpg",
2303
+ quantity: 30
2304
+ }
2305
+ ]
2306
+ };
2307
+ var orderableSkus = (catalog) => {
2308
+ const skus = /* @__PURE__ */ new Set();
2309
+ for (const p of catalog.products) {
2310
+ skus.add(p.sku);
2311
+ if (p.medPaxSku) skus.add(p.medPaxSku);
2312
+ }
2313
+ for (const pill of catalog.medPaxPills) skus.add(pill.sku);
2314
+ for (const carton of catalog.privateLabelCartons) skus.add(carton.sku);
2315
+ return skus;
2316
+ };
2317
+ var unitPrice = (catalog, sku) => {
2318
+ for (const p of catalog.products) {
2319
+ if (p.sku === sku) return p.wholesalePrice;
2320
+ if (p.medPaxSku && p.medPaxSku === sku)
2321
+ return p.medPaxDetails?.wholesalePrice ?? p.wholesalePrice;
2322
+ }
2323
+ return 0;
2324
+ };
2325
+
2326
+ // src/generated/openapi.ts
2327
+ var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Wholescripts supplement fulfilment API (Mockingbird subset)","description":"Stateful mock subset of the Wholescripts ordering API: the product and private-label\\n(MedPax) catalogs, order submit, status polling and cancel. Hand-authored from the\\nconsumers' zod schemas and clients (the vendor publishes no spec).\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from the wire shapes our consumers read and write (backend and EMR wholescripts.types.ts zod schemas, the Makor wholescripts client, adapter and mappers)."}},"servers":[{"url":"https://api.wholescripts.com"}],"security":[{"basicAuth":[]}],"paths":{"/api/Orders/PrivateLabelProductList":{"get":{"operationId":"GetPrivateLabelProductList","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Private-label (MedPax) catalog","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PrivateLabelProductList"}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/api/Orders/ProductList":{"get":{"operationId":"GetProductList","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"instockonly","in":"query","required":false,"description":"\`true\` keeps only rows with quantity > 0 (the EMR sends it).","schema":{"type":"string","enum":["true","false"]}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":1000}},{"name":"search","in":"query","required":false,"description":"Case-insensitive match on name, SKU, MedPax SKU, brand or categories (Makor).","schema":{"type":"string","maxLength":40}}],"responses":{"200":{"description":"Products","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Product"}}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/api/Orders/Submit":{"post":{"operationId":"SubmitOrder","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrderSubmitRequest"}}}},"responses":{"200":{"description":"Submit outcome. A rejected order (bad body, unknown SKU, payment failure) is still 200, with success false and the reason in msg.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrderSubmitResponse"}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/api/Orders/Status":{"get":{"operationId":"GetOrderStatus","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"ordernum","in":"query","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"order","missing":"000000"}}}],"responses":{"200":{"description":"The order's status rows (empty for an unknown order number)","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/OrderStatus"}}}}},"400":{"description":"Missing ordernum","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AspNetError"}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/api/Orders/Cancel":{"post":{"operationId":"CancelOrder","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["OrderNumber"],"properties":{"OrderNumber":{"type":"string","x-mockingbird-resource-ref":{"type":"order","missing":"000000"}}}}}}},"responses":{"200":{"description":"Cancel outcome; success false when the order has progressed too far","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelResponse"}}}},"400":{"description":"Missing OrderNumber","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelResponse"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"description":"Unknown order","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelResponse"}}}}}}}},"components":{"securitySchemes":{"basicAuth":{"type":"http","scheme":"basic"}},"responses":{"Unauthorized":{"description":"Missing or wrong Basic credentials","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AspNetError"}}}}},"schemas":{"AspNetError":{"type":"object","required":["Message"],"properties":{"Message":{"type":"string"}}},"DefaultDosing":{"type":"object","required":["time","qty"],"properties":{"time":{"type":"string"},"qty":{"type":"number"}}},"MedPaxDetails":{"type":"object","required":["name","genericName","quantity","wholesalePrice","retailPrice"],"properties":{"name":{"type":"string"},"genericName":{"type":"string"},"quantity":{"type":"number"},"wholesalePrice":{"type":"number"},"retailPrice":{"type":"number"}}},"Product":{"type":"object","required":["productName","sku","medPaxSku","categories","retailPrice","upc","descriptionShort","brand","productImage","quantity","countUnit","wholesalePrice","supplementFactsHTML","defaultDosing"],"properties":{"productName":{"type":"string"},"sku":{"type":"string","x-mockingbird-resource":{"type":"sku","identity":true}},"medPaxSku":{"type":"string"},"categories":{"type":"string"},"retailPrice":{"type":"number"},"upc":{"type":"string"},"descriptionShort":{"type":"string"},"descriptionFull":{"type":"string"},"brand":{"type":"string"},"productImage":{"type":"string"},"quantity":{"type":"number"},"countUnit":{"type":"string"},"wholesalePrice":{"type":"number"},"supplementFactsHTML":{"type":"string"},"defaultDosing":{"type":"array","items":{"$ref":"#/components/schemas/DefaultDosing"}},"medPaxDetails":{"oneOf":[{"$ref":"#/components/schemas/MedPaxDetails"},{"type":"null"}]}}},"PrivateLabelProductList":{"type":"object","required":["privateLabelProducts","medPaxPills","privateLabelCartons"],"properties":{"privateLabelProducts":{"type":"array","items":{}},"medPaxPills":{"type":"array","items":{"type":"object","required":["sku","genericName","privateLabelName","quantity"],"properties":{"sku":{"type":"string","x-mockingbird-resource":{"type":"sku","identity":true}},"genericName":{"type":"string"},"privateLabelName":{"type":"string"},"quantity":{"type":"number"}}}},"privateLabelCartons":{"type":"array","items":{"type":"object","required":["sku","name","cartonImage","quantity"],"properties":{"sku":{"type":"string","x-mockingbird-resource":{"type":"sku","identity":true}},"name":{"type":"string"},"cartonImage":{"type":"string"},"quantity":{"type":"number"}}}}}},"MedPaxPill":{"type":"object","required":["Sku","Quantity","ItemTime"],"properties":{"productId":{"type":"string","maxLength":64},"Sku":{"type":"string","x-mockingbird-resource-ref":{"type":"sku","missing":"000000000000000000"}},"Quantity":{"type":"integer","minimum":1,"maximum":1000},"ItemTime":{"type":"string","enum":["AM","PM","AM with food","PM with food"]}}},"OrderItem":{"type":"object","required":["Sku","Quantity"],"properties":{"Sku":{"type":"string","x-mockingbird-resource-ref":{"type":"sku","missing":"000000000000000000"}},"Quantity":{"type":"integer","minimum":1,"maximum":1000},"MedPaxName":{"type":["string","null"],"maxLength":60},"MedPaxPills":{"type":["array","null"],"maxItems":4,"items":{"$ref":"#/components/schemas/MedPaxPill"}}}},"OrderSubmitRequest":{"type":"object","required":["ShippingAddress","Items","ShippingMethod"],"properties":{"ShippingAddress":{"type":"object","required":["FName","LName","Address1","City","State","Zip"],"properties":{"FName":{"type":"string","minLength":1,"maxLength":40},"LName":{"type":"string","minLength":1,"maxLength":40},"Address1":{"type":"string","minLength":1,"maxLength":80},"Address2":{"type":["string","null"],"maxLength":80},"City":{"type":"string","minLength":1,"maxLength":40},"State":{"type":"string","pattern":"^[A-Z]{2}$"},"Zip":{"type":"string","pattern":"^[0-9]{5}(-[0-9]{4})?$"},"Email":{"type":"string","format":"email","maxLength":120}}},"Notes":{"type":["string","null"],"maxLength":500},"Items":{"type":"array","minItems":1,"maxItems":4,"items":{"$ref":"#/components/schemas/OrderItem"}},"ShippingMethod":{"type":"string","minLength":1,"maxLength":40}}},"OrderSubmitResponse":{"type":"object","required":["orderNumber","success","msg"],"properties":{"orderNumber":{"type":"string","x-mockingbird-resource":{"type":"order","identity":true}},"success":{"type":"boolean"},"msg":{"type":"string"}}},"Tracking":{"type":"object","required":["trackingNumber","carrier"],"properties":{"trackingNumber":{"type":"string"},"carrier":{"type":"string"},"trackingUrl":{"type":"string"}}},"OrderStatus":{"type":"object","required":["orderNumber","orderDate","salesOrder","status","tracking","message","subTotal","shipMethod","shipCharge","discount","tax","serviceFee","orderTotal"],"properties":{"orderNumber":{"type":"string"},"orderDate":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"salesOrder":{"type":"string"},"status":{"type":"string"},"tracking":{"type":"array","items":{"$ref":"#/components/schemas/Tracking"}},"message":{"type":"string"},"subTotal":{"type":"number"},"shipMethod":{"type":"string"},"shipCharge":{"type":"number"},"discount":{"type":"number"},"tax":{"type":"number"},"serviceFee":{"type":"number"},"orderTotal":{"type":"number"}}},"CancelResponse":{"type":"object","required":["success","msg"],"properties":{"success":{"type":"boolean"},"msg":{"type":"string"}}}}}}`);
2328
+ var operationIds = ["GetPrivateLabelProductList", "GetProductList", "SubmitOrder", "GetOrderStatus", "CancelOrder"];
2329
+ var supportedOperationIds = ["GetPrivateLabelProductList", "GetProductList", "SubmitOrder", "GetOrderStatus", "CancelOrder"];
2330
+
2331
+ // src/state.ts
2332
+ var DEFAULT_SETTINGS = { accounts: [], autoAdvance: null };
2333
+ var FIRST_ORDER_NUMBER = 700001;
2334
+ var WholescriptsState = class {
2335
+ constructor(sqlite, namespace, seed) {
2336
+ this.seed = seed;
2337
+ this.orders = new Collection(sqlite, namespace, "orders");
2338
+ this.catalogs = new Collection(sqlite, namespace, "catalog");
2339
+ this.settings = new Collection(sqlite, namespace, "settings");
2340
+ this.ensureSeeded();
2341
+ }
2342
+ seed;
2343
+ orders;
2344
+ catalogs;
2345
+ settings;
2346
+ /** Re-apply the catalog and settings after a reset. */
2347
+ ensureSeeded() {
2348
+ if (!this.catalogs.has("catalog")) {
2349
+ this.catalogs.insert("catalog", this.seed.catalog ?? DEFAULT_CATALOG);
2350
+ }
2351
+ if (!this.settings.has("settings")) {
2352
+ this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed.settings });
2353
+ }
2354
+ }
2355
+ catalog() {
2356
+ return this.catalogs.get("catalog") ?? DEFAULT_CATALOG;
2357
+ }
2358
+ replaceCatalog(catalog) {
2359
+ this.catalogs.insert("catalog", catalog);
2360
+ return catalog;
2361
+ }
2362
+ current() {
2363
+ return this.settings.get("settings") ?? DEFAULT_SETTINGS;
2364
+ }
2365
+ update(patch) {
2366
+ const next = { ...this.current(), ...patch };
2367
+ this.settings.insert("settings", next);
2368
+ return next;
2369
+ }
2370
+ nextOrderNumber() {
2371
+ return String(FIRST_ORDER_NUMBER + this.orders.count());
2372
+ }
2373
+ };
2374
+
2375
+ // src/runtime.ts
2376
+ var WHOLESCRIPTS_PRESETS = {
2377
+ submit_rejected: {
2378
+ description: "Submit answers 200 {success: false, msg} (the backend and Makor both reject it)",
2379
+ rules: [{ operationId: "SubmitOrder", effect: "submit_rejected" }]
2380
+ },
2381
+ submit_timeout: {
2382
+ description: "Submit places the order, then drops the connection (Makor's 'order may have been placed')",
2383
+ rules: [{ operationId: "SubmitOrder", effect: "submit_timeout" }]
2384
+ },
2385
+ status_empty: {
2386
+ description: "Status answers [] even for a known order (backend returns null, Makor 'unknown')",
2387
+ rules: [{ operationId: "GetOrderStatus", effect: "status_empty" }]
2388
+ },
2389
+ status_schema_drift: {
2390
+ description: "Status rows drop salesOrder and stringify orderTotal (the backend zod check fails: data null)",
2391
+ rules: [{ operationId: "GetOrderStatus", effect: "status_schema_drift" }]
2392
+ },
2393
+ server_error: {
2394
+ description: "Every call answers 500 (Makor retries 5xx; the backend throws)",
2395
+ rules: [{ status: 500, body: { Message: "An error has occurred." } }]
2396
+ },
2397
+ unauthorized: {
2398
+ description: "Every call answers 401, as with rotated Basic credentials",
2399
+ rules: [{ status: 401, body: { Message: "Authorization has been denied for this request." } }]
2400
+ }
2401
+ };
2402
+ var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2403
+ var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
2404
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2405
+ var parseAutoAdvance = (value) => {
2406
+ if (value === null) return null;
2407
+ if (!isRecord4(value)) return "autoAdvance must be {afterMs, path} or null";
2408
+ if (typeof value.afterMs !== "number" || value.afterMs < 0)
2409
+ return "autoAdvance.afterMs must be ms";
2410
+ if (!Array.isArray(value.path) || value.path.some((s) => typeof s !== "string")) {
2411
+ return "autoAdvance.path must be a list of vendor statuses";
2412
+ }
2413
+ return { afterMs: value.afterMs, path: value.path };
2414
+ };
2415
+ var adminRoutes = (runtime) => ({
2416
+ "GET /orders": ({ namespace }) => json3(200, { orders: runtime.instance(namespace).orders() }),
2417
+ "POST /orders/:id/transition": ({ params, body, namespace }) => {
2418
+ if (!isRecord4(body) || typeof body.to !== "string") {
2419
+ return adminError3(
2420
+ 400,
2421
+ 'expected {"to": "Pending|Processing|Complete|Cancelled|Error|\u2026", "trackingNumber"?, "carrier"?, "message"?}'
2422
+ );
2423
+ }
2424
+ const optional = (key) => typeof body[key] === "string" ? { [key]: body[key] } : {};
2425
+ const order = runtime.instance(namespace).transition(params.id, {
2426
+ to: body.to,
2427
+ ...optional("trackingNumber"),
2428
+ ...optional("carrier"),
2429
+ ...optional("trackingUrl"),
2430
+ ...optional("message")
2431
+ });
2432
+ return order ? json3(200, order) : adminError3(404, `no order ${params.id}`);
2433
+ },
2434
+ "GET /catalog": ({ namespace }) => json3(200, runtime.instance(namespace).state.catalog()),
2435
+ "PUT /catalog": ({ body, namespace }) => {
2436
+ if (!isRecord4(body) || !Array.isArray(body.products) || !Array.isArray(body.medPaxPills) || !Array.isArray(body.privateLabelCartons)) {
2437
+ return adminError3(
2438
+ 400,
2439
+ "expected {products: [...], medPaxPills: [...], privateLabelCartons: [...]}"
2440
+ );
2441
+ }
2442
+ return json3(200, runtime.instance(namespace).state.replaceCatalog(body));
2443
+ },
2444
+ "GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
2445
+ "PUT /settings": ({ body, namespace }) => {
2446
+ if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
2447
+ const patch = {};
2448
+ if (body.accounts !== void 0) {
2449
+ if (!Array.isArray(body.accounts)) return adminError3(400, "accounts: [{username, password}]");
2450
+ patch.accounts = body.accounts.filter(isRecord4).map((a) => ({
2451
+ username: String(a.username),
2452
+ password: String(a.password)
2453
+ }));
2454
+ }
2455
+ if (body.autoAdvance !== void 0) {
2456
+ const parsed = parseAutoAdvance(body.autoAdvance);
2457
+ if (typeof parsed === "string") return adminError3(400, parsed);
2458
+ patch.autoAdvance = parsed;
2459
+ }
2460
+ return json3(200, runtime.instance(namespace).state.update(patch));
2461
+ },
2462
+ "POST /tick": ({ namespace }) => json3(200, { applied: runtime.instance(namespace).tick() })
2463
+ });
2464
+ var createRuntime2 = (options = {}) => {
2465
+ const runtime = createRuntime({
2466
+ name: WHOLESCRIPTS_NAMESPACE,
2467
+ document,
2468
+ ...options.sqlite ? { sqlite: options.sqlite } : {},
2469
+ ...options.clock ? { clock: options.clock } : {},
2470
+ ...options.seed !== void 0 ? { seed: options.seed } : {},
2471
+ ...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
2472
+ ...options.onLog ? { onLog: options.onLog } : {},
2473
+ credential: basicUsername,
2474
+ presets: WHOLESCRIPTS_PRESETS,
2475
+ create: ({ sqlite, namespace, clock }) => new WholescriptsAPI({
2476
+ sqlite,
2477
+ namespace,
2478
+ now: clock.now,
2479
+ ...options.catalog ? { catalog: options.catalog } : {},
2480
+ ...options.settings ? { settings: options.settings } : {}
2481
+ }),
2482
+ admin: adminRoutes
2483
+ });
2484
+ let timer;
2485
+ if (options.tickMs !== void 0 && options.tickMs > 0) {
2486
+ timer = setInterval(() => {
2487
+ for (const name of runtime.namespaces()) runtime.instance(name).tick();
2488
+ }, options.tickMs);
2489
+ timer.unref?.();
2490
+ }
2491
+ return Object.assign(runtime, {
2492
+ stop: () => {
2493
+ if (timer !== void 0) clearInterval(timer);
2494
+ }
2495
+ });
2496
+ };
2497
+
2498
+ // src/index.ts
2499
+ var WHOLESCRIPTS_NAMESPACE = "wholescripts";
2500
+ var UNAUTHORIZED = { Message: "Authorization has been denied for this request." };
2501
+ var basicUsername = (request) => basicAuth(request)?.username || void 0;
2502
+ var record = (context) => context.body.kind === "json" && typeof context.body.value === "object" && context.body.value !== null && !Array.isArray(context.body.value) ? context.body.value : void 0;
2503
+ var round2 = (value) => Math.round(value * 100) / 100;
2504
+ var CANONICAL = {
2505
+ pending: "Pending",
2506
+ processing: "Processing",
2507
+ complete: "Complete",
2508
+ completed: "Complete",
2509
+ cancelled: "Cancelled",
2510
+ canceled: "Cancelled",
2511
+ error: "Error"
2512
+ };
2513
+ var canonicalStatus = (to) => CANONICAL[to.trim().toLowerCase()] ?? to;
2514
+ var statusRow = (order) => ({
2515
+ orderNumber: order.orderNumber,
2516
+ orderDate: order.orderDate,
2517
+ salesOrder: order.salesOrder,
2518
+ status: order.status,
2519
+ tracking: order.tracking,
2520
+ message: order.message,
2521
+ subTotal: order.subTotal,
2522
+ shipMethod: order.shipMethod,
2523
+ shipCharge: order.shipCharge,
2524
+ discount: order.discount,
2525
+ tax: order.tax,
2526
+ serviceFee: order.serviceFee,
2527
+ orderTotal: order.orderTotal
2528
+ });
2529
+ var trackingUrl = (carrier, number) => /ups/i.test(carrier) ? `https://www.ups.com/track?tracknum=${number}` : /usps/i.test(carrier) ? `https://tools.usps.com/go/TrackConfirmAction?tLabels=${number}` : `https://www.fedex.com/fedextrack/?trknbr=${number}`;
2530
+ var WholescriptsAPI = class {
2531
+ app;
2532
+ sqlite;
2533
+ state;
2534
+ service;
2535
+ now;
2536
+ constructor(options = {}) {
2537
+ const sqlite = bootSqlite(options.sqlite);
2538
+ const namespace = options.namespace ?? WHOLESCRIPTS_NAMESPACE;
2539
+ this.now = options.now ?? (() => Date.now());
2540
+ this.state = new WholescriptsState(sqlite, namespace, {
2541
+ catalog: options.catalog,
2542
+ settings: options.settings ?? {}
2543
+ });
2544
+ const handlers = defineOperations({
2545
+ GetPrivateLabelProductList: () => {
2546
+ const catalog = this.state.catalog();
2547
+ return jsonRes(200, {
2548
+ privateLabelProducts: [],
2549
+ medPaxPills: catalog.medPaxPills,
2550
+ privateLabelCartons: catalog.privateLabelCartons
2551
+ });
2552
+ },
2553
+ GetProductList: (context) => this.productList(context),
2554
+ SubmitOrder: (context) => this.submit(context),
2555
+ GetOrderStatus: (context) => this.status(context),
2556
+ CancelOrder: (context) => this.cancel(context)
2557
+ });
2558
+ this.service = createService({
2559
+ document,
2560
+ handlers,
2561
+ sqlite,
2562
+ namespace,
2563
+ now: this.now,
2564
+ notFound: () => jsonRes(404, { Message: "No HTTP resource was found that matches the request URI." }),
2565
+ onError: (error) => {
2566
+ if (error instanceof HttpError) return error.toResponse();
2567
+ throw error;
2568
+ },
2569
+ before: (context) => {
2570
+ this.tick();
2571
+ const credentials = basicAuth(context.request);
2572
+ if (!credentials?.username || !credentials.password) return jsonRes(401, UNAUTHORIZED);
2573
+ const accounts = this.state.current().accounts;
2574
+ if (accounts.length > 0 && !accounts.some(
2575
+ (a) => a.username === credentials.username && a.password === credentials.password
2576
+ )) {
2577
+ return jsonRes(401, UNAUTHORIZED);
2578
+ }
2579
+ return void 0;
2580
+ }
2581
+ });
2582
+ this.app = this.service.app;
2583
+ this.sqlite = this.service.sqlite;
2584
+ }
2585
+ fetch(request) {
2586
+ return this.service.fetch(request);
2587
+ }
2588
+ async reset() {
2589
+ await this.service.reset();
2590
+ this.state.ensureSeeded();
2591
+ }
2592
+ iso() {
2593
+ return new Date(this.now()).toISOString();
2594
+ }
2595
+ productList(context) {
2596
+ const params = context.url.searchParams;
2597
+ let rows = this.state.catalog().products;
2598
+ if (params.get("instockonly")?.toLowerCase() === "true") {
2599
+ rows = rows.filter((p) => p.quantity > 0);
2600
+ }
2601
+ const search = params.get("search")?.trim().toLowerCase();
2602
+ if (search) {
2603
+ rows = rows.filter(
2604
+ (p) => [p.productName, p.sku, p.medPaxSku, p.brand, p.categories].some(
2605
+ (field) => field.toLowerCase().includes(search)
2606
+ )
2607
+ );
2608
+ }
2609
+ const limit = Number(params.get("limit"));
2610
+ if (Number.isInteger(limit) && limit > 0) rows = rows.slice(0, limit);
2611
+ return jsonRes(200, rows);
2612
+ }
2613
+ submit(context) {
2614
+ const rejected = (msg) => jsonRes(200, { orderNumber: "", success: false, msg });
2615
+ if (faultEffect(context.request, "submit_rejected") !== void 0) {
2616
+ return rejected("Payment authorization failed");
2617
+ }
2618
+ const body = record(context);
2619
+ if (!body) return rejected("Invalid order: the request body must be a JSON object");
2620
+ const issues = bodyIssues(context);
2621
+ if (issues.length > 0) {
2622
+ const first = issues[0];
2623
+ return rejected(`Invalid order: ${first?.path || "body"} ${first?.message ?? "is invalid"}`);
2624
+ }
2625
+ const items = body.Items;
2626
+ const catalog = this.state.catalog();
2627
+ const skus = orderableSkus(catalog);
2628
+ const lines = items.flatMap((item) => [
2629
+ { sku: item.Sku, quantity: item.Quantity },
2630
+ ...(item.MedPaxPills ?? []).map((pill) => ({ sku: pill.Sku, quantity: pill.Quantity }))
2631
+ ]);
2632
+ const unknown = lines.find((line) => !skus.has(line.sku));
2633
+ if (unknown) return rejected(`Invalid SKU: ${unknown.sku}`);
2634
+ const subTotal = round2(
2635
+ lines.reduce((sum, line) => sum + unitPrice(catalog, line.sku) * line.quantity, 0)
2636
+ );
2637
+ const shipMethod = String(body.ShippingMethod);
2638
+ const shipCharge = /free/i.test(shipMethod) || subTotal === 0 ? 0 : 9.95;
2639
+ const order = {
2640
+ orderNumber: this.state.nextOrderNumber(),
2641
+ orderDate: this.iso(),
2642
+ salesOrder: "",
2643
+ status: "Pending",
2644
+ tracking: [],
2645
+ message: "",
2646
+ subTotal,
2647
+ shipMethod,
2648
+ shipCharge,
2649
+ discount: 0,
2650
+ tax: 0,
2651
+ serviceFee: 0,
2652
+ orderTotal: round2(subTotal + shipCharge),
2653
+ items: lines,
2654
+ createdAtMs: this.now(),
2655
+ advanced: 0
2656
+ };
2657
+ this.state.orders.insert(order.orderNumber, order);
2658
+ if (faultEffect(context.request, "submit_timeout") !== void 0) {
2659
+ throw new DroppedConnectionError();
2660
+ }
2661
+ return annotateResponse(
2662
+ jsonRes(200, {
2663
+ orderNumber: order.orderNumber,
2664
+ success: true,
2665
+ msg: "Order submitted successfully"
2666
+ }),
2667
+ { ids: { orderNumber: order.orderNumber } }
2668
+ );
2669
+ }
2670
+ status(context) {
2671
+ const ordernum = context.url.searchParams.get("ordernum")?.trim();
2672
+ if (!ordernum) return jsonRes(400, { Message: "The ordernum parameter is required." });
2673
+ const order = this.state.orders.get(ordernum);
2674
+ if (!order || faultEffect(context.request, "status_empty") !== void 0) {
2675
+ return jsonRes(200, []);
2676
+ }
2677
+ const row = statusRow(order);
2678
+ if (faultEffect(context.request, "status_schema_drift") !== void 0) {
2679
+ delete row.salesOrder;
2680
+ row.orderTotal = String(row.orderTotal);
2681
+ }
2682
+ return annotateResponse(jsonRes(200, [row]), { ids: { orderNumber: order.orderNumber } });
2683
+ }
2684
+ cancel(context) {
2685
+ const body = record(context);
2686
+ const orderNumber = typeof body?.OrderNumber === "string" ? body.OrderNumber.trim() : "";
2687
+ if (!orderNumber) return jsonRes(400, { success: false, msg: "OrderNumber is required" });
2688
+ const order = this.state.orders.get(orderNumber);
2689
+ if (!order) return jsonRes(404, { success: false, msg: `Order ${orderNumber} not found` });
2690
+ const ids = { orderNumber };
2691
+ if (order.status === "Cancelled") {
2692
+ return annotateResponse(
2693
+ jsonRes(200, { success: false, msg: `Order ${orderNumber} is already cancelled` }),
2694
+ { ids }
2695
+ );
2696
+ }
2697
+ if (!["Pending", "Processing"].includes(order.status) || order.tracking.length > 0) {
2698
+ return annotateResponse(
2699
+ jsonRes(200, {
2700
+ success: false,
2701
+ msg: `Order ${orderNumber} cannot be cancelled: it is ${order.status}${order.tracking.length > 0 ? " and has shipped" : ""}`
2702
+ }),
2703
+ { ids }
2704
+ );
2705
+ }
2706
+ this.transition(orderNumber, { to: "Cancelled", message: "Cancelled by customer request" });
2707
+ return annotateResponse(
2708
+ jsonRes(200, { success: true, msg: `Order ${orderNumber} cancelled` }),
2709
+ { ids }
2710
+ );
2711
+ }
2712
+ /** Move an order to a vendor status; `Complete` (or a tracking number) adds tracking. */
2713
+ transition(orderNumber, input) {
2714
+ const order = this.state.orders.get(orderNumber);
2715
+ if (!order) return void 0;
2716
+ const status = canonicalStatus(input.to);
2717
+ let tracking = order.tracking;
2718
+ if (input.trackingNumber) {
2719
+ const carrier = input.carrier ?? "UPS";
2720
+ tracking = [
2721
+ ...order.tracking.filter((t) => t.trackingNumber !== input.trackingNumber),
2722
+ {
2723
+ trackingNumber: input.trackingNumber,
2724
+ carrier,
2725
+ trackingUrl: input.trackingUrl ?? trackingUrl(carrier, input.trackingNumber)
2726
+ }
2727
+ ];
2728
+ } else if (status === "Complete" && tracking.length === 0) {
2729
+ const number = `1Z${opaqueToken(order.orderNumber, 16).toUpperCase()}`;
2730
+ const carrier = input.carrier ?? "UPS";
2731
+ tracking = [{ trackingNumber: number, carrier, trackingUrl: trackingUrl(carrier, number) }];
2732
+ }
2733
+ const next = {
2734
+ ...order,
2735
+ status,
2736
+ tracking,
2737
+ salesOrder: order.salesOrder || (status === "Processing" || status === "Complete" ? `SO${order.orderNumber}` : ""),
2738
+ message: input.message ?? (status === "Error" ? "Order could not be processed" : "")
2739
+ };
2740
+ this.state.orders.update(orderNumber, next);
2741
+ return this.state.orders.get(orderNumber);
2742
+ }
2743
+ /**
2744
+ * Apply every auto-advance step that is due on the mock clock. Runs before each vendor
2745
+ * request, on `POST /__admin/tick`, and from the served runtime's background ticker.
2746
+ */
2747
+ tick() {
2748
+ const plan = this.state.current().autoAdvance;
2749
+ if (!plan || plan.path.length === 0) return 0;
2750
+ let applied = 0;
2751
+ for (const { value: order } of this.state.orders.list({ order: "oldest" })) {
2752
+ let current = order;
2753
+ while (current.advanced < plan.path.length) {
2754
+ const due = current.createdAtMs + plan.afterMs * (current.advanced + 1);
2755
+ if (this.now() < due) break;
2756
+ const moved = this.transition(current.orderNumber, {
2757
+ to: plan.path[current.advanced]
2758
+ });
2759
+ if (!moved) break;
2760
+ current = { ...moved, advanced: current.advanced + 1 };
2761
+ this.state.orders.update(current.orderNumber, current);
2762
+ applied++;
2763
+ }
2764
+ }
2765
+ return applied;
2766
+ }
2767
+ orders() {
2768
+ return this.state.orders.list({ order: "oldest" }).map((row) => row.value);
2769
+ }
2770
+ };
2771
+
2772
+ export {
2773
+ MEDPAX_BOX_SKU,
2774
+ DEFAULT_CATALOG,
2775
+ document,
2776
+ operationIds,
2777
+ supportedOperationIds,
2778
+ WHOLESCRIPTS_PRESETS,
2779
+ createRuntime2 as createRuntime,
2780
+ WHOLESCRIPTS_NAMESPACE,
2781
+ basicUsername,
2782
+ canonicalStatus,
2783
+ WholescriptsAPI
2784
+ };
2785
+ //# sourceMappingURL=chunk-ARWCVRNR.js.map