@crvouga/mockingbird-service-customerio 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,3284 @@
1
+ // ../core/dist/clock.js
2
+ var createClock = (source = Date.now) => {
3
+ let offsetMs = 0;
4
+ let frozenAt;
5
+ const now = () => frozenAt ?? source() + offsetMs;
6
+ return {
7
+ now,
8
+ set: (epochMs) => {
9
+ if (frozenAt !== void 0)
10
+ frozenAt = epochMs;
11
+ else
12
+ offsetMs = epochMs - source();
13
+ },
14
+ advance: (deltaMs) => {
15
+ if (frozenAt !== void 0)
16
+ frozenAt += deltaMs;
17
+ else
18
+ offsetMs += deltaMs;
19
+ },
20
+ freeze: () => {
21
+ frozenAt = now();
22
+ },
23
+ unfreeze: () => {
24
+ if (frozenAt === void 0)
25
+ return;
26
+ offsetMs = frozenAt - source();
27
+ frozenAt = void 0;
28
+ },
29
+ reset: () => {
30
+ offsetMs = 0;
31
+ frozenAt = void 0;
32
+ },
33
+ state: () => ({ now: now(), frozen: frozenAt !== void 0, offsetMs })
34
+ };
35
+ };
36
+
37
+ // ../core/dist/collection.js
38
+ var Collection = class {
39
+ sqlite;
40
+ namespace;
41
+ name;
42
+ constructor(sqlite, namespace, name) {
43
+ this.sqlite = sqlite;
44
+ this.namespace = namespace;
45
+ this.name = name;
46
+ }
47
+ bumpCollectionSeq() {
48
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
49
+ const next = (row?.value ?? 0) + 1;
50
+ this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
51
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
52
+ return next;
53
+ }
54
+ nextSequence() {
55
+ return this.sqlite.transaction(() => this.bumpCollectionSeq());
56
+ }
57
+ get(id) {
58
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
59
+ if (!row)
60
+ return void 0;
61
+ return JSON.parse(row.value).value;
62
+ }
63
+ has(id) {
64
+ const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
65
+ return row !== void 0;
66
+ }
67
+ /** Insert a new record, assigning it the next sequence number. */
68
+ insert(id, value) {
69
+ return this.sqlite.transaction(() => {
70
+ const seq = this.bumpCollectionSeq();
71
+ const stored = { seq, value };
72
+ this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
73
+ VALUES (?, ?, ?, ?, ?)
74
+ ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
75
+ return stored;
76
+ });
77
+ }
78
+ /** Replace an existing record's value, keeping its position. */
79
+ update(id, value) {
80
+ return this.sqlite.transaction(() => {
81
+ const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
82
+ if (!row)
83
+ return void 0;
84
+ const stored = { seq: row.seq, value };
85
+ this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
86
+ return stored;
87
+ });
88
+ }
89
+ delete(id) {
90
+ const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
91
+ return result.changes > 0;
92
+ }
93
+ /** How many records the collection holds, without reading them. */
94
+ count() {
95
+ const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
96
+ return Number(row?.n ?? 0);
97
+ }
98
+ list(options = {}) {
99
+ const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
100
+ const out = [];
101
+ for (const row of rows) {
102
+ const stored = JSON.parse(row.value);
103
+ if (options.where && !options.where(stored.value, stored.seq))
104
+ continue;
105
+ out.push({ id: row.id, seq: stored.seq, value: stored.value });
106
+ }
107
+ out.sort((a, b) => options.order === "oldest" ? a.seq - b.seq : b.seq - a.seq);
108
+ return out;
109
+ }
110
+ };
111
+
112
+ // ../core/dist/control.js
113
+ var HEALTH_PATH = "/health";
114
+ var ADMIN_PREFIX = "/__admin";
115
+ var ADMIN_KEY_HEADER = "x-mockingbird-admin-key";
116
+ var NAMESPACE_HEADER = "x-mockingbird-namespace";
117
+ var json = (status, body) => new Response(JSON.stringify(body), {
118
+ status,
119
+ headers: { "content-type": "application/json" }
120
+ });
121
+ var adminError = (status, message) => json(status, { error: { type: "mockingbird_admin", message } });
122
+ var UNITS = {
123
+ ms: 1,
124
+ s: 1e3,
125
+ m: 6e4,
126
+ h: 36e5,
127
+ d: 864e5
128
+ };
129
+ var parseDuration = (value) => {
130
+ if (typeof value === "number" && Number.isFinite(value))
131
+ return value;
132
+ if (typeof value !== "string")
133
+ return void 0;
134
+ const match = /^(-?\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(value.trim());
135
+ if (!match)
136
+ return void 0;
137
+ return Number(match[1]) * UNITS[match[2]];
138
+ };
139
+ var parseInstant = (value) => {
140
+ if (typeof value === "number" && Number.isFinite(value))
141
+ return value;
142
+ if (typeof value !== "string")
143
+ return void 0;
144
+ const parsed = Date.parse(value);
145
+ return Number.isNaN(parsed) ? void 0 : parsed;
146
+ };
147
+ var matchRoute = (pattern, path) => {
148
+ const want = pattern.split("/").filter(Boolean);
149
+ const have = path.split("/").filter(Boolean);
150
+ if (want.length !== have.length)
151
+ return void 0;
152
+ const params = {};
153
+ for (let i = 0; i < want.length; i++) {
154
+ const segment = want[i];
155
+ const actual = have[i];
156
+ if (segment.startsWith(":"))
157
+ params[segment.slice(1)] = decodeURIComponent(actual);
158
+ else if (segment !== actual)
159
+ return void 0;
160
+ }
161
+ return params;
162
+ };
163
+ var readJson = async (request) => {
164
+ const text = await request.text();
165
+ if (text.trim() === "")
166
+ return void 0;
167
+ return JSON.parse(text);
168
+ };
169
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
170
+ var createControlPlane = (context) => {
171
+ const snapshots = /* @__PURE__ */ new Map();
172
+ let snapshotCounter = 0;
173
+ const headerNamespace = (request) => request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace;
174
+ const adminNamespace = (request, url) => url.searchParams.get("namespace") ?? headerNamespace(request);
175
+ const builtin = {
176
+ "GET /": () => json(200, {
177
+ service: context.name,
178
+ routes: [...Object.keys(builtin), ...Object.keys(context.routes)].sort()
179
+ }),
180
+ "POST /reset": async ({ url, namespace }) => {
181
+ const target = url.searchParams.get("all") === "1" ? "*" : namespace;
182
+ await context.reset(target);
183
+ return json(200, { status: "ok", reset: target === "*" ? context.namespaces() : [target] });
184
+ },
185
+ "GET /namespaces": () => json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),
186
+ "GET /clock": () => json(200, context.clock.state()),
187
+ "POST /clock": ({ body }) => {
188
+ if (!isRecord(body))
189
+ return adminError(400, "expected a JSON object");
190
+ if (body.reset === true)
191
+ context.clock.reset();
192
+ if (body.set !== void 0) {
193
+ const instant = parseInstant(body.set);
194
+ if (instant === void 0)
195
+ return adminError(400, "set: expected epoch ms or ISO-8601");
196
+ context.clock.set(instant);
197
+ }
198
+ if (body.advance !== void 0) {
199
+ const delta = parseDuration(body.advance);
200
+ if (delta === void 0)
201
+ return adminError(400, 'advance: expected ms or "15m"-style');
202
+ context.clock.advance(delta);
203
+ }
204
+ if (body.freeze === true)
205
+ context.clock.freeze();
206
+ if (body.freeze === false)
207
+ context.clock.unfreeze();
208
+ return json(200, context.clock.state());
209
+ },
210
+ "GET /faults": () => json(200, { faults: context.faults.list() }),
211
+ "POST /faults": ({ body, namespace }) => {
212
+ if (isRecord(body) && typeof body.preset === "string") {
213
+ if (!context.applyPreset)
214
+ return adminError(400, `${context.name} has no fault presets`);
215
+ const { preset, ...overrides } = body;
216
+ try {
217
+ return json(201, {
218
+ preset,
219
+ rules: context.applyPreset(preset, namespace, overrides)
220
+ });
221
+ } catch (error) {
222
+ return adminError(404, error instanceof Error ? error.message : String(error));
223
+ }
224
+ }
225
+ if (!isRecord(body) || typeof body.status !== "number" && typeof body.delayMs !== "number" && typeof body.latencyMs !== "number" && body.drop !== true && typeof body.effect !== "string") {
226
+ return adminError(400, "a fault needs a numeric status, a delayMs/latencyMs, drop: true, an effect, or a preset");
227
+ }
228
+ const rule = {
229
+ // Scoped to the caller's namespace unless it asks for every one, so one worker's
230
+ // injected failure never lands on another's request.
231
+ namespace,
232
+ ...body,
233
+ id: typeof body.id === "string" ? body.id : `fault_${context.faults.list().length + 1}`
234
+ };
235
+ return json(201, context.faults.add(rule));
236
+ },
237
+ "DELETE /faults": ({ url }) => {
238
+ const id = url.searchParams.get("id");
239
+ if (id === null) {
240
+ context.faults.clear();
241
+ return json(200, { status: "ok" });
242
+ }
243
+ return context.faults.remove(id) ? json(200, { status: "ok" }) : adminError(404, `no fault ${id}`);
244
+ },
245
+ "POST /snapshots": ({ namespace }) => {
246
+ const point = context.timeTravel.checkpoint(namespace, "main");
247
+ context.timeTravel.retain(namespace, point.id);
248
+ snapshotCounter++;
249
+ const id = `snap_${snapshotCounter}`;
250
+ snapshots.set(id, { namespace, checkpoint: point.id });
251
+ return json(201, { id, namespace, records: point.records ?? 0 });
252
+ },
253
+ "POST /snapshots/:id/restore": ({ params, namespace }) => {
254
+ const alias = snapshots.get(params.id);
255
+ if (!alias)
256
+ return adminError(404, `no snapshot ${params.id}`);
257
+ if (alias.namespace !== namespace) {
258
+ return adminError(409, `snapshot ${params.id} belongs to namespace ${alias.namespace}`);
259
+ }
260
+ context.timeTravel.checkout(alias.checkpoint, { namespace, branch: "main" });
261
+ return json(200, { status: "ok", id: params.id, namespace });
262
+ },
263
+ "DELETE /snapshots/:id": ({ params }) => {
264
+ const id = params.id;
265
+ const alias = snapshots.get(id);
266
+ if (!alias)
267
+ return adminError(404, `no snapshot ${id}`);
268
+ snapshots.delete(id);
269
+ context.timeTravel.release(alias.namespace, alias.checkpoint);
270
+ return json(200, { status: "ok" });
271
+ },
272
+ "GET /timeline": ({ namespace }) => json(200, context.timeTravel.inspect(namespace)),
273
+ "POST /checkpoints": ({ body, namespace }) => {
274
+ const branch = isRecord(body) && typeof body.branch === "string" ? body.branch : "main";
275
+ try {
276
+ return json(201, context.timeTravel.checkpoint(namespace, branch));
277
+ } catch (error) {
278
+ return adminError(409, error instanceof Error ? error.message : String(error));
279
+ }
280
+ },
281
+ "POST /branches/:name": ({ params, body, namespace }) => {
282
+ const at = isRecord(body) && typeof body.at === "string" ? body.at : void 0;
283
+ try {
284
+ return json(201, context.timeTravel.branch(params.name, {
285
+ namespace,
286
+ ...at !== void 0 ? { at } : {}
287
+ }));
288
+ } catch (error) {
289
+ return adminError(409, error instanceof Error ? error.message : String(error));
290
+ }
291
+ },
292
+ "POST /branches/:name/checkout": ({ params, body, namespace }) => {
293
+ if (!isRecord(body) || typeof body.checkpoint !== "string") {
294
+ return adminError(400, 'expected {"checkpoint":"cp_..."}');
295
+ }
296
+ try {
297
+ context.timeTravel.checkout(body.checkpoint, {
298
+ namespace,
299
+ branch: params.name
300
+ });
301
+ return json(200, { status: "ok", branch: params.name, checkpoint: body.checkpoint });
302
+ } catch (error) {
303
+ return adminError(409, error instanceof Error ? error.message : String(error));
304
+ }
305
+ },
306
+ "GET /requests": ({ url, namespace }) => {
307
+ const status = url.searchParams.get("status");
308
+ const since = url.searchParams.get("since");
309
+ const limit = url.searchParams.get("limit");
310
+ const sinceMs = since === null ? void 0 : parseInstant(/^\d+$/.test(since) ? Number(since) : since);
311
+ if (since !== null && sinceMs === void 0) {
312
+ return adminError(400, "since: expected epoch ms or ISO-8601");
313
+ }
314
+ if (status !== null && !/^\d{3}$/.test(status))
315
+ return adminError(400, "status: expected an HTTP status");
316
+ if (limit !== null && !/^\d+$/.test(limit))
317
+ return adminError(400, "limit: expected a count");
318
+ const operationId = url.searchParams.get("operationId");
319
+ const everyNamespace = url.searchParams.get("all") === "1";
320
+ return json(200, {
321
+ size: context.journal.size,
322
+ requests: context.journal.list({
323
+ ...everyNamespace ? {} : { namespace },
324
+ ...operationId !== null ? { operationId } : {},
325
+ ...status !== null ? { status: Number(status) } : {},
326
+ ...sinceMs !== void 0 ? { since: sinceMs } : {},
327
+ ...limit !== null ? { limit: Number(limit) } : {}
328
+ })
329
+ });
330
+ },
331
+ "DELETE /requests": ({ url, namespace }) => {
332
+ context.journal.clear(url.searchParams.get("all") === "1" ? void 0 : namespace);
333
+ return json(200, { status: "ok" });
334
+ },
335
+ "GET /metrics": () => json(200, context.metrics.report()),
336
+ "DELETE /metrics": () => {
337
+ context.metrics.reset();
338
+ return json(200, { status: "ok" });
339
+ }
340
+ };
341
+ const routes = [...Object.entries(context.routes), ...Object.entries(builtin)].map(([key, handler]) => {
342
+ const space = key.indexOf(" ");
343
+ return { method: key.slice(0, space), pattern: key.slice(space + 1), handler };
344
+ });
345
+ return {
346
+ namespaceOf: headerNamespace,
347
+ async handle(request) {
348
+ const url = new URL(request.url);
349
+ if (url.pathname === HEALTH_PATH && request.method === "GET") {
350
+ return json(200, {
351
+ status: "ok",
352
+ service: context.name,
353
+ uptimeMs: context.wallNow() - context.startedAt,
354
+ clock: context.clock.state(),
355
+ namespaces: context.namespaces().length,
356
+ ...context.describe()
357
+ });
358
+ }
359
+ if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {
360
+ return void 0;
361
+ }
362
+ if (context.adminKey !== void 0 && request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey) {
363
+ return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`);
364
+ }
365
+ const path = url.pathname.slice(ADMIN_PREFIX.length) || "/";
366
+ for (const route of routes) {
367
+ if (route.method !== request.method)
368
+ continue;
369
+ const params = matchRoute(route.pattern, path);
370
+ if (!params)
371
+ continue;
372
+ let body;
373
+ try {
374
+ body = await readJson(request);
375
+ } catch {
376
+ return adminError(400, "request body is not valid JSON");
377
+ }
378
+ return route.handler({
379
+ request,
380
+ url,
381
+ params,
382
+ namespace: adminNamespace(request, url),
383
+ body
384
+ });
385
+ }
386
+ return adminError(404, `no admin route ${request.method} ${path}; GET ${ADMIN_PREFIX} lists them`);
387
+ }
388
+ };
389
+ };
390
+
391
+ // ../core/dist/credentials.js
392
+ var bearerToken = (request) => {
393
+ const header = request.headers.get("authorization");
394
+ if (!header)
395
+ return void 0;
396
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim());
397
+ return match?.[1]?.trim() || void 0;
398
+ };
399
+ var basicAuth = (request) => {
400
+ const header = request.headers.get("authorization");
401
+ if (!header)
402
+ return void 0;
403
+ const match = /^Basic\s+(.+)$/i.exec(header.trim());
404
+ if (!match?.[1])
405
+ return void 0;
406
+ let decoded;
407
+ try {
408
+ decoded = atob(match[1].trim());
409
+ } catch {
410
+ return void 0;
411
+ }
412
+ const colon = decoded.indexOf(":");
413
+ if (colon < 0)
414
+ return { username: decoded, password: "" };
415
+ return { username: decoded.slice(0, colon), password: decoded.slice(colon + 1) };
416
+ };
417
+ var createCredentialRegistry = () => {
418
+ const map = /* @__PURE__ */ new Map();
419
+ return {
420
+ set: (credential, namespace) => {
421
+ map.set(credential, namespace);
422
+ },
423
+ get: (credential) => map.get(credential),
424
+ remove: (credential) => map.delete(credential),
425
+ clear: () => map.clear(),
426
+ entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
427
+ };
428
+ };
429
+ var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
430
+
431
+ // ../core/dist/rng.js
432
+ var seedFrom = (value) => {
433
+ let hash = 2166136261;
434
+ for (let i = 0; i < value.length; i++) {
435
+ hash ^= value.charCodeAt(i);
436
+ hash = Math.imul(hash, 16777619);
437
+ }
438
+ return hash >>> 0;
439
+ };
440
+ var createRng = (seed = 0) => {
441
+ const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
442
+ let state = numeric;
443
+ const next = () => {
444
+ state = state + 1831565813 >>> 0;
445
+ let t = state;
446
+ t = Math.imul(t ^ t >>> 15, t | 1);
447
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
448
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
449
+ };
450
+ return {
451
+ next,
452
+ int: (min, max) => min + Math.floor(next() * (max - min + 1)),
453
+ reset: () => {
454
+ state = numeric;
455
+ },
456
+ state: () => state,
457
+ setState: (next2) => {
458
+ if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
459
+ throw new RangeError("rng state must be an unsigned 32-bit integer");
460
+ }
461
+ state = next2 >>> 0;
462
+ },
463
+ seed: numeric
464
+ };
465
+ };
466
+
467
+ // ../core/dist/faults.js
468
+ var matches = (rule, candidate) => {
469
+ if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
470
+ return false;
471
+ }
472
+ if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
473
+ return false;
474
+ if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
475
+ return false;
476
+ }
477
+ if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
478
+ return false;
479
+ return true;
480
+ };
481
+ var faultResponse = (rule) => {
482
+ const status = rule.status ?? 500;
483
+ const headers = { "content-type": "application/json", ...rule.headers };
484
+ if (typeof rule.body === "string")
485
+ return new Response(rule.body, { status, headers });
486
+ if (rule.body === null)
487
+ return new Response(null, { status, headers: rule.headers ?? {} });
488
+ const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
489
+ return new Response(JSON.stringify(body), { status, headers });
490
+ };
491
+ var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
492
+ const entries = [];
493
+ return {
494
+ add(rule) {
495
+ const existing = entries.findIndex((e) => e.rule.id === rule.id);
496
+ const entry = { rule, remaining: rule.count ?? null, hits: 0 };
497
+ if (existing >= 0)
498
+ entries[existing] = entry;
499
+ else
500
+ entries.push(entry);
501
+ return rule;
502
+ },
503
+ list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
504
+ remove(id) {
505
+ const index = entries.findIndex((e) => e.rule.id === id);
506
+ if (index < 0)
507
+ return false;
508
+ entries.splice(index, 1);
509
+ return true;
510
+ },
511
+ clear() {
512
+ entries.length = 0;
513
+ },
514
+ async take(candidate) {
515
+ const hits = [];
516
+ for (const entry of entries) {
517
+ if (entry.remaining === 0)
518
+ continue;
519
+ if (!matches(entry.rule, candidate))
520
+ continue;
521
+ const rate = entry.rule.rate ?? 1;
522
+ if (rng.next() >= rate)
523
+ continue;
524
+ entry.hits++;
525
+ if (entry.remaining !== null)
526
+ entry.remaining--;
527
+ const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
528
+ if (delay !== void 0 && delay > 0) {
529
+ await sleep(delay);
530
+ }
531
+ const hit = { id: entry.rule.id };
532
+ if (entry.rule.effect !== void 0) {
533
+ hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
534
+ }
535
+ if (entry.rule.drop === true)
536
+ hit.drop = true;
537
+ else if (entry.rule.status !== void 0)
538
+ hit.response = faultResponse(entry.rule);
539
+ hits.push(hit);
540
+ if (hit.drop || hit.response)
541
+ break;
542
+ }
543
+ return hits;
544
+ }
545
+ };
546
+ };
547
+
548
+ // ../../openapi/core/dist/refs.js
549
+ var OpenAPIReferenceError = class extends Error {
550
+ ref;
551
+ constructor(ref) {
552
+ super(`unresolvable $ref: ${ref}`);
553
+ this.ref = ref;
554
+ this.name = "OpenAPIReferenceError";
555
+ }
556
+ };
557
+ var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
558
+ var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
559
+ var resolveRef = (document2, ref) => {
560
+ if (!ref.startsWith("#/"))
561
+ throw new OpenAPIReferenceError(ref);
562
+ let cursor = document2;
563
+ for (const raw of ref.slice(2).split("/")) {
564
+ const segment = unescapePointer(raw);
565
+ if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
566
+ throw new OpenAPIReferenceError(ref);
567
+ }
568
+ cursor = cursor[segment];
569
+ }
570
+ if (cursor === void 0)
571
+ throw new OpenAPIReferenceError(ref);
572
+ return cursor;
573
+ };
574
+ var deref = (document2, value) => {
575
+ let current = value;
576
+ const seen = /* @__PURE__ */ new Set();
577
+ while (isReference(current)) {
578
+ if (seen.has(current.$ref))
579
+ throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
580
+ seen.add(current.$ref);
581
+ current = resolveRef(document2, current.$ref);
582
+ }
583
+ return current;
584
+ };
585
+
586
+ // ../../openapi/core/dist/types.js
587
+ var HTTP_METHODS = [
588
+ "get",
589
+ "put",
590
+ "post",
591
+ "delete",
592
+ "options",
593
+ "head",
594
+ "patch",
595
+ "trace"
596
+ ];
597
+
598
+ // ../../openapi/core/dist/document.js
599
+ var mergeParameters = (document2, item, own) => {
600
+ const merged = /* @__PURE__ */ new Map();
601
+ for (const raw of item.parameters ?? []) {
602
+ const parameter = deref(document2, raw);
603
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
604
+ }
605
+ for (const raw of own ?? []) {
606
+ const parameter = deref(document2, raw);
607
+ merged.set(`${parameter.in}:${parameter.name}`, parameter);
608
+ }
609
+ return [...merged.values()];
610
+ };
611
+ var listOperations = (document2) => {
612
+ const operations = [];
613
+ for (const [path, item] of Object.entries(document2.paths)) {
614
+ for (const method of HTTP_METHODS) {
615
+ const operation = item[method];
616
+ if (operation?.operationId === void 0)
617
+ continue;
618
+ const responses = {};
619
+ for (const [status, response] of Object.entries(operation.responses)) {
620
+ responses[status] = deref(document2, response);
621
+ }
622
+ operations.push({
623
+ operationId: operation.operationId,
624
+ method,
625
+ path,
626
+ operation,
627
+ parameters: mergeParameters(document2, item, operation.parameters),
628
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
629
+ responses
630
+ });
631
+ }
632
+ }
633
+ return operations;
634
+ };
635
+
636
+ // ../../openapi/core/dist/schema.js
637
+ var resolveSchema = (document2, schema) => {
638
+ let current = schema;
639
+ const seen = /* @__PURE__ */ new Set();
640
+ while (typeof current.$ref === "string") {
641
+ const ref = current.$ref;
642
+ if (seen.has(ref))
643
+ break;
644
+ seen.add(ref);
645
+ const { $ref: _ignored, ...siblings } = current;
646
+ const target = resolveRef(document2, ref);
647
+ current = { ...target, ...siblings };
648
+ }
649
+ if (current.nullable === true) {
650
+ const { nullable: _nullable, ...rest } = current;
651
+ const types = schemaTypes(rest);
652
+ if (types.length > 0 && !types.includes("null"))
653
+ current = { ...rest, type: [...types, "null"] };
654
+ else
655
+ current = rest;
656
+ }
657
+ return current;
658
+ };
659
+ var schemaTypes = (schema) => {
660
+ if (Array.isArray(schema.type))
661
+ return schema.type;
662
+ if (schema.type !== void 0)
663
+ return [schema.type];
664
+ const inferred = [];
665
+ if (schema.properties || schema.required || schema.additionalProperties !== void 0)
666
+ inferred.push("object");
667
+ if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
668
+ inferred.push("array");
669
+ if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
670
+ inferred.push("string");
671
+ if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
672
+ inferred.push("number");
673
+ return inferred;
674
+ };
675
+ var jsonTypeOf = (value) => {
676
+ if (value === null)
677
+ return "null";
678
+ if (Array.isArray(value))
679
+ return "array";
680
+ switch (typeof value) {
681
+ case "string":
682
+ return "string";
683
+ case "boolean":
684
+ return "boolean";
685
+ case "number":
686
+ return Number.isInteger(value) ? "integer" : "number";
687
+ case "object":
688
+ return "object";
689
+ default:
690
+ return "undefined";
691
+ }
692
+ };
693
+ var deepEqual = (a, b) => {
694
+ if (a === b)
695
+ return true;
696
+ if (typeof a !== typeof b || a === null || b === null)
697
+ return false;
698
+ if (Array.isArray(a)) {
699
+ return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
700
+ }
701
+ if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
702
+ const ka = Object.keys(a);
703
+ const kb = Object.keys(b);
704
+ return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
705
+ }
706
+ return false;
707
+ };
708
+ var FORMAT_PATTERNS = {
709
+ 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,
710
+ date: /^\d{4}-\d{2}-\d{2}$/,
711
+ "date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
712
+ email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
713
+ uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
714
+ ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
715
+ };
716
+ var graphemeLength = (value) => [...value].length;
717
+ var validateValue = (document2, schema, value, path = []) => {
718
+ const errors = [];
719
+ const s = resolveSchema(document2, schema);
720
+ const fail = (message) => errors.push({ path, message });
721
+ const actual = jsonTypeOf(value);
722
+ if (actual === "undefined") {
723
+ fail("value is undefined");
724
+ return errors;
725
+ }
726
+ const types = schemaTypes(s);
727
+ if (types.length > 0) {
728
+ const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
729
+ if (!ok) {
730
+ fail(`expected type ${types.join("|")}, got ${actual}`);
731
+ return errors;
732
+ }
733
+ }
734
+ if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
735
+ fail("value not in enum");
736
+ }
737
+ if (s.const !== void 0 && !deepEqual(s.const, value))
738
+ fail("value does not equal const");
739
+ if (typeof value === "string") {
740
+ const length = graphemeLength(value);
741
+ if (s.minLength !== void 0 && length < s.minLength)
742
+ fail(`length ${length} < minLength ${s.minLength}`);
743
+ if (s.maxLength !== void 0 && length > s.maxLength)
744
+ fail(`length ${length} > maxLength ${s.maxLength}`);
745
+ if (s.pattern !== void 0) {
746
+ try {
747
+ if (!new RegExp(s.pattern, "u").test(value))
748
+ fail(`does not match pattern ${s.pattern}`);
749
+ } catch {
750
+ }
751
+ }
752
+ if (s.format !== void 0) {
753
+ const pattern = FORMAT_PATTERNS[s.format];
754
+ if (pattern && !pattern.test(value))
755
+ fail(`does not match format ${s.format}`);
756
+ }
757
+ }
758
+ if (typeof value === "number") {
759
+ if (s.minimum !== void 0 && value < s.minimum)
760
+ fail(`${value} < minimum ${s.minimum}`);
761
+ if (s.maximum !== void 0 && value > s.maximum)
762
+ fail(`${value} > maximum ${s.maximum}`);
763
+ if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
764
+ fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
765
+ if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
766
+ fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
767
+ if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
768
+ fail(`${value} is not a multiple of ${s.multipleOf}`);
769
+ }
770
+ }
771
+ if (Array.isArray(value)) {
772
+ if (s.minItems !== void 0 && value.length < s.minItems)
773
+ fail(`${value.length} items < minItems ${s.minItems}`);
774
+ if (s.maxItems !== void 0 && value.length > s.maxItems)
775
+ fail(`${value.length} items > maxItems ${s.maxItems}`);
776
+ if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
777
+ fail("items are not unique");
778
+ value.forEach((item, i) => {
779
+ const itemSchema = s.prefixItems?.[i] ?? s.items;
780
+ if (itemSchema)
781
+ errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
782
+ });
783
+ }
784
+ if (actual === "object") {
785
+ const record = value;
786
+ const keys = Object.keys(record);
787
+ for (const name of s.required ?? [])
788
+ if (!(name in record))
789
+ fail(`missing required property ${name}`);
790
+ if (s.minProperties !== void 0 && keys.length < s.minProperties)
791
+ fail(`${keys.length} properties < minProperties ${s.minProperties}`);
792
+ if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
793
+ fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
794
+ for (const key of keys) {
795
+ const property = s.properties?.[key];
796
+ if (property) {
797
+ errors.push(...validateValue(document2, property, record[key], [...path, key]));
798
+ continue;
799
+ }
800
+ if (s.additionalProperties === false)
801
+ fail(`unexpected property ${key}`);
802
+ else if (typeof s.additionalProperties === "object") {
803
+ errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
804
+ }
805
+ if (s.propertyNames) {
806
+ const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
807
+ if (nameErrors.length > 0)
808
+ fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
809
+ }
810
+ }
811
+ }
812
+ if (s.allOf)
813
+ for (const branch of s.allOf)
814
+ errors.push(...validateValue(document2, branch, value, path));
815
+ if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
816
+ fail("matches no anyOf branch");
817
+ if (s.oneOf) {
818
+ const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
819
+ if (matches2 !== 1)
820
+ fail(`matches ${matches2} oneOf branches, expected exactly 1`);
821
+ }
822
+ if (s.not && validateValue(document2, s.not, value).length === 0)
823
+ fail("matches forbidden `not` schema");
824
+ return errors;
825
+ };
826
+
827
+ // ../../http/codec/dist/form.js
828
+ var parsePath = (rawKey) => {
829
+ const open = rawKey.indexOf("[");
830
+ if (open === -1)
831
+ return [rawKey];
832
+ const path = [rawKey.slice(0, open)];
833
+ const rest = rawKey.slice(open);
834
+ const pattern = /\[([^\]]*)\]/g;
835
+ let match = pattern.exec(rest);
836
+ let consumed = 0;
837
+ while (match !== null) {
838
+ if (match.index !== consumed)
839
+ return [rawKey];
840
+ path.push(match[1] ?? "");
841
+ consumed = match.index + match[0].length;
842
+ match = pattern.exec(rest);
843
+ }
844
+ if (consumed !== rest.length)
845
+ return [rawKey];
846
+ return path;
847
+ };
848
+ var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
849
+ var put = (target, key, value) => {
850
+ if (key === "__proto__") {
851
+ Object.defineProperty(target, key, {
852
+ value,
853
+ enumerable: true,
854
+ writable: true,
855
+ configurable: true
856
+ });
857
+ return;
858
+ }
859
+ ;
860
+ target[key] = value;
861
+ };
862
+ var assign = (target, path, value) => {
863
+ let cursor = target;
864
+ for (let i = 0; i < path.length; i++) {
865
+ const segment = path[i];
866
+ const last = i === path.length - 1;
867
+ if (Array.isArray(cursor)) {
868
+ const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
869
+ if (index === void 0)
870
+ return;
871
+ if (last) {
872
+ put(cursor, index, value);
873
+ return;
874
+ }
875
+ const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
876
+ if (next === void 0 || typeof next === "string") {
877
+ const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
878
+ put(cursor, index, created);
879
+ cursor = created;
880
+ } else {
881
+ cursor = next;
882
+ }
883
+ continue;
884
+ }
885
+ if (typeof cursor === "string")
886
+ return;
887
+ if (last) {
888
+ put(cursor, segment, value);
889
+ return;
890
+ }
891
+ const nextSegment = path[i + 1];
892
+ const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
893
+ if (existing === void 0 || typeof existing === "string") {
894
+ const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
895
+ put(cursor, segment, created);
896
+ cursor = created;
897
+ } else {
898
+ cursor = existing;
899
+ }
900
+ }
901
+ };
902
+ var decodeFormPairs = (pairs) => {
903
+ const out = {};
904
+ for (const [rawKey, value] of pairs)
905
+ assign(out, parsePath(rawKey), value);
906
+ return densify(out);
907
+ };
908
+ var densify = (value) => {
909
+ if (typeof value === "string")
910
+ return value;
911
+ if (Array.isArray(value))
912
+ return value.filter((item) => item !== void 0).map(densify);
913
+ const out = {};
914
+ for (const [key, item] of Object.entries(value))
915
+ put(out, key, densify(item));
916
+ return out;
917
+ };
918
+ var decodeForm = (text) => {
919
+ const source = text.startsWith("?") ? text.slice(1) : text;
920
+ return decodeFormPairs(new URLSearchParams(source).entries());
921
+ };
922
+
923
+ // ../../http/codec/dist/content.js
924
+ var JSON_MEDIA_TYPE = "application/json";
925
+ var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
926
+ var mediaTypeOf = (contentType) => {
927
+ if (!contentType)
928
+ return void 0;
929
+ const essence = contentType.split(";")[0]?.trim().toLowerCase();
930
+ return essence ? essence : void 0;
931
+ };
932
+ var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
933
+ var utf8 = new TextDecoder("utf-8", { fatal: false });
934
+ var decodeBody = (contentType, bytes) => {
935
+ if (bytes.byteLength === 0)
936
+ return { kind: "empty" };
937
+ const mediaType = mediaTypeOf(contentType);
938
+ if (mediaType === void 0)
939
+ return { kind: "bytes", value: bytes };
940
+ if (isJsonMediaType(mediaType)) {
941
+ const text = utf8.decode(bytes);
942
+ try {
943
+ return { kind: "json", value: JSON.parse(text) };
944
+ } catch (error) {
945
+ return {
946
+ kind: "invalid",
947
+ mediaType,
948
+ text,
949
+ error: error instanceof Error ? error.message : String(error)
950
+ };
951
+ }
952
+ }
953
+ if (mediaType === FORM_MEDIA_TYPE) {
954
+ return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
955
+ }
956
+ if (mediaType.startsWith("text/"))
957
+ return { kind: "text", value: utf8.decode(bytes) };
958
+ return { kind: "bytes", value: bytes };
959
+ };
960
+ var readBody = async (message) => {
961
+ const bytes = new Uint8Array(await message.arrayBuffer());
962
+ return decodeBody(message.headers.get("content-type"), bytes);
963
+ };
964
+
965
+ // ../core/dist/http.js
966
+ var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
967
+ status,
968
+ headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
969
+ });
970
+ var HttpError = class extends Error {
971
+ status;
972
+ body;
973
+ headers;
974
+ constructor(status, body, headers = {}) {
975
+ super(`HTTP ${status}`);
976
+ this.status = status;
977
+ this.body = body;
978
+ this.headers = headers;
979
+ this.name = "HttpError";
980
+ }
981
+ toResponse() {
982
+ const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
983
+ if (contentType === "text/plain") {
984
+ return new Response(String(this.body), {
985
+ status: this.status,
986
+ headers: this.headers
987
+ });
988
+ }
989
+ return jsonRes(this.status, this.body, this.headers);
990
+ }
991
+ };
992
+
993
+ // ../core/dist/ids.js
994
+ var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
995
+ var mix = (input) => {
996
+ let hash = 2166136261;
997
+ for (let i = 0; i < input.length; i++) {
998
+ hash ^= input.charCodeAt(i);
999
+ hash = Math.imul(hash, 16777619) >>> 0;
1000
+ }
1001
+ hash ^= hash >>> 16;
1002
+ hash = Math.imul(hash, 2246822507) >>> 0;
1003
+ hash ^= hash >>> 13;
1004
+ return hash >>> 0;
1005
+ };
1006
+ var opaqueToken = (input, length) => {
1007
+ let out = "";
1008
+ let round = 0;
1009
+ while (out.length < length) {
1010
+ let hash = mix(`${input}:${round++}`);
1011
+ for (let i = 0; i < 5 && out.length < length; i++) {
1012
+ out += ALPHABET.charAt(hash % ALPHABET.length);
1013
+ hash = Math.floor(hash / ALPHABET.length);
1014
+ }
1015
+ }
1016
+ return out;
1017
+ };
1018
+ var IdSequence = class {
1019
+ sqlite;
1020
+ namespace;
1021
+ salt;
1022
+ constructor(sqlite, namespace, salt = "mockingbird") {
1023
+ this.sqlite = sqlite;
1024
+ this.namespace = namespace;
1025
+ this.salt = salt;
1026
+ }
1027
+ next(prefix, length = 14) {
1028
+ return this.sqlite.transaction(() => {
1029
+ const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'").get(this.namespace, prefix);
1030
+ const value = (row?.value ?? 0) + 1;
1031
+ this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)
1032
+ ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, prefix, value);
1033
+ return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`;
1034
+ });
1035
+ }
1036
+ };
1037
+
1038
+ // ../core/dist/journal.js
1039
+ var DEFAULT_JOURNAL_SIZE = 1e3;
1040
+ var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
1041
+ const capacity = Math.max(0, Math.floor(size));
1042
+ const rings = /* @__PURE__ */ new Map();
1043
+ let sequence = 0;
1044
+ const order = /* @__PURE__ */ new WeakMap();
1045
+ const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
1046
+ return {
1047
+ size: capacity,
1048
+ record(entry) {
1049
+ if (capacity === 0)
1050
+ return;
1051
+ order.set(entry, sequence++);
1052
+ let ring = rings.get(entry.namespace);
1053
+ if (!ring) {
1054
+ ring = { entries: [], next: 0 };
1055
+ rings.set(entry.namespace, ring);
1056
+ }
1057
+ if (ring.entries.length < capacity)
1058
+ ring.entries.push(entry);
1059
+ else {
1060
+ ring.entries[ring.next] = entry;
1061
+ ring.next = (ring.next + 1) % capacity;
1062
+ }
1063
+ },
1064
+ list(query = {}) {
1065
+ 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));
1066
+ 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));
1067
+ return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
1068
+ },
1069
+ clear(namespace) {
1070
+ if (namespace === void 0)
1071
+ rings.clear();
1072
+ else
1073
+ rings.delete(namespace);
1074
+ }
1075
+ };
1076
+ };
1077
+ var notes = /* @__PURE__ */ new WeakMap();
1078
+ var annotateResponse = (response, extra) => {
1079
+ const existing = notes.get(response);
1080
+ notes.set(response, {
1081
+ ...existing,
1082
+ ...extra,
1083
+ ...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
1084
+ });
1085
+ return response;
1086
+ };
1087
+ var responseNotes = (response) => notes.get(response);
1088
+
1089
+ // ../core/dist/metrics.js
1090
+ var createMetrics = () => {
1091
+ let requests = 0;
1092
+ let faults = 0;
1093
+ let totalDurationMs = 0;
1094
+ const byOperation = /* @__PURE__ */ new Map();
1095
+ const unmatched = /* @__PURE__ */ new Map();
1096
+ return {
1097
+ record(entry) {
1098
+ requests++;
1099
+ totalDurationMs += entry.durationMs;
1100
+ if (entry.faultId !== void 0)
1101
+ faults++;
1102
+ const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
1103
+ byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
1104
+ if (entry.unmatched) {
1105
+ const route = `${entry.method} ${entry.path}`;
1106
+ unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
1107
+ }
1108
+ },
1109
+ report: () => ({
1110
+ requests,
1111
+ byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
1112
+ unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
1113
+ const space = route.indexOf(" ");
1114
+ return { method: route.slice(0, space), path: route.slice(space + 1), count };
1115
+ }),
1116
+ faults,
1117
+ totalDurationMs
1118
+ }),
1119
+ reset() {
1120
+ requests = 0;
1121
+ faults = 0;
1122
+ totalDurationMs = 0;
1123
+ byOperation.clear();
1124
+ unmatched.clear();
1125
+ }
1126
+ };
1127
+ };
1128
+
1129
+ // ../core/dist/outbox.js
1130
+ var OutboxStore = class {
1131
+ items;
1132
+ constructor(sqlite, namespace, name = "outbox") {
1133
+ this.items = new Collection(sqlite, namespace, name);
1134
+ }
1135
+ record(item) {
1136
+ this.items.insert(item.id, item);
1137
+ return item;
1138
+ }
1139
+ get(id) {
1140
+ return this.items.get(id);
1141
+ }
1142
+ update(id, item) {
1143
+ this.items.update(id, item);
1144
+ }
1145
+ /** Oldest first, so a suite reads messages in the order they were sent. */
1146
+ list(query = {}) {
1147
+ const to = query.to?.toLowerCase();
1148
+ const matched = this.items.list({ order: "oldest" }).map((row) => row.value).filter((item) => {
1149
+ if (to !== void 0) {
1150
+ const recipients = Array.isArray(item.to) ? item.to : [item.to];
1151
+ if (!recipients.some((r) => r.toLowerCase() === to))
1152
+ return false;
1153
+ }
1154
+ if (query.since !== void 0 && Date.parse(item.createdAt) < query.since)
1155
+ return false;
1156
+ if (query.where && !query.where(item))
1157
+ return false;
1158
+ return true;
1159
+ });
1160
+ return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
1161
+ }
1162
+ };
1163
+ var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1164
+ var parseSince = (value) => {
1165
+ if (value === null)
1166
+ return void 0;
1167
+ const parsed = /^\d+$/.test(value) ? Number(value) : Date.parse(value);
1168
+ return Number.isNaN(parsed) ? null : parsed;
1169
+ };
1170
+ var outboxAdminRoutes = (runtime, pick, filter) => ({
1171
+ "GET /outbox": ({ url, namespace }) => {
1172
+ const since = parseSince(url.searchParams.get("since"));
1173
+ if (since === null) {
1174
+ return json2(400, {
1175
+ error: { type: "mockingbird_admin", message: "since: expected epoch ms or ISO-8601" }
1176
+ });
1177
+ }
1178
+ const limit = url.searchParams.get("limit");
1179
+ const where = filter?.(url.searchParams);
1180
+ const to = url.searchParams.get("to");
1181
+ return json2(200, {
1182
+ messages: pick(runtime.instance(namespace)).list({
1183
+ ...to !== null ? { to } : {},
1184
+ ...since !== void 0 ? { since } : {},
1185
+ ...where ? { where } : {},
1186
+ ...limit !== null && /^\d+$/.test(limit) ? { limit: Number(limit) } : {}
1187
+ })
1188
+ });
1189
+ },
1190
+ "GET /outbox/:id": ({ params, namespace }) => {
1191
+ const item = pick(runtime.instance(namespace)).get(params.id);
1192
+ return item ? json2(200, item) : json2(404, { error: { type: "mockingbird_admin", message: `no message ${params.id}` } });
1193
+ }
1194
+ });
1195
+ var extractLinks = (html) => {
1196
+ const links = [];
1197
+ for (const match of html.matchAll(/href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)) {
1198
+ const raw = match[1] ?? match[2] ?? match[3] ?? "";
1199
+ const decoded = raw.replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
1200
+ if (decoded && !links.includes(decoded))
1201
+ links.push(decoded);
1202
+ }
1203
+ return links;
1204
+ };
1205
+
1206
+ // ../../core/dist/timeline.js
1207
+ var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1208
+ var Timeline = class {
1209
+ maxCheckpoints;
1210
+ now;
1211
+ makeId;
1212
+ nodes = /* @__PURE__ */ new Map();
1213
+ heads = /* @__PURE__ */ new Map();
1214
+ /** Unreferenced nodes in the exact order they became collectible. */
1215
+ evictable = /* @__PURE__ */ new Set();
1216
+ /** Branch heads plus explicit retainers. Absent means zero. */
1217
+ references = /* @__PURE__ */ new Map();
1218
+ explicitPins = /* @__PURE__ */ new Map();
1219
+ sequence = 0;
1220
+ constructor(options = {}) {
1221
+ const max = options.maxCheckpoints ?? 1e3;
1222
+ if (!Number.isSafeInteger(max) || max < 1)
1223
+ throw new RangeError("maxCheckpoints must be a positive integer");
1224
+ this.maxCheckpoints = max;
1225
+ this.now = options.now ?? (() => this.sequence);
1226
+ this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
1227
+ }
1228
+ /** Capture a new immutable value and move `branch` to it. */
1229
+ commit(value, options = {}) {
1230
+ const branch = options.branch ?? "main";
1231
+ this.assertBranch(branch);
1232
+ const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
1233
+ if (parent !== null && !this.nodes.has(parent))
1234
+ throw new RangeError(`no checkpoint ${parent}`);
1235
+ const id = this.makeId(++this.sequence);
1236
+ if (this.nodes.has(id))
1237
+ throw new RangeError(`duplicate checkpoint id ${id}`);
1238
+ const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
1239
+ this.nodes.set(id, checkpoint);
1240
+ this.moveHead(branch, id);
1241
+ this.collect(this.maxCheckpoints);
1242
+ return checkpoint;
1243
+ }
1244
+ /** Create a branch pointer without copying its checkpoint value. */
1245
+ fork(branch, options = {}) {
1246
+ this.assertBranch(branch);
1247
+ if (this.heads.has(branch))
1248
+ throw new RangeError(`branch already exists: ${branch}`);
1249
+ const from = options.from ?? this.heads.get("main");
1250
+ if (from === void 0)
1251
+ return void 0;
1252
+ const checkpoint = this.get(from);
1253
+ this.moveHead(branch, checkpoint.id);
1254
+ return checkpoint;
1255
+ }
1256
+ /** Move a branch pointer to an existing checkpoint. */
1257
+ checkout(branch, id) {
1258
+ this.assertBranch(branch);
1259
+ const checkpoint = this.get(id);
1260
+ this.moveHead(branch, checkpoint.id);
1261
+ return checkpoint;
1262
+ }
1263
+ get(id) {
1264
+ const checkpoint = this.nodes.get(id);
1265
+ if (!checkpoint)
1266
+ throw new RangeError(`no checkpoint ${id}`);
1267
+ return checkpoint;
1268
+ }
1269
+ head(branch = "main") {
1270
+ const id = this.heads.get(branch);
1271
+ return id === void 0 ? void 0 : this.get(id);
1272
+ }
1273
+ hasBranch(branch) {
1274
+ return this.heads.has(branch);
1275
+ }
1276
+ branches() {
1277
+ return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
1278
+ }
1279
+ checkpoints() {
1280
+ return [...this.nodes.values()];
1281
+ }
1282
+ /** Number of retained checkpoints without allocating an array. */
1283
+ get size() {
1284
+ return this.nodes.size;
1285
+ }
1286
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
1287
+ retain(id) {
1288
+ const checkpoint = this.get(id);
1289
+ this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
1290
+ this.addReference(id);
1291
+ return checkpoint;
1292
+ }
1293
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
1294
+ release(id) {
1295
+ if (!this.nodes.has(id))
1296
+ return false;
1297
+ const pins = this.explicitPins.get(id) ?? 0;
1298
+ if (pins === 0)
1299
+ return false;
1300
+ if (pins === 1)
1301
+ this.explicitPins.delete(id);
1302
+ else
1303
+ this.explicitPins.set(id, pins - 1);
1304
+ this.removeReference(id);
1305
+ this.collect(this.maxCheckpoints);
1306
+ return true;
1307
+ }
1308
+ deleteBranch(branch) {
1309
+ if (branch === "main")
1310
+ throw new RangeError("cannot delete main branch");
1311
+ const previous = this.heads.get(branch);
1312
+ const deleted = this.heads.delete(branch);
1313
+ if (previous !== void 0)
1314
+ this.removeReference(previous);
1315
+ this.collect(this.maxCheckpoints);
1316
+ return deleted;
1317
+ }
1318
+ /**
1319
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
1320
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
1321
+ * storage dependency, so a retained node remains usable after pruning.
1322
+ */
1323
+ gc(max = this.maxCheckpoints) {
1324
+ if (!Number.isSafeInteger(max) || max < 1)
1325
+ throw new RangeError("max must be a positive integer");
1326
+ const removed = [];
1327
+ this.collect(max, removed);
1328
+ return removed;
1329
+ }
1330
+ collect(max, removed) {
1331
+ while (this.nodes.size > max && this.evictable.size > 0) {
1332
+ const id = this.evictable.values().next().value;
1333
+ this.evictable.delete(id);
1334
+ this.nodes.delete(id);
1335
+ removed?.push(id);
1336
+ }
1337
+ }
1338
+ moveHead(branch, id) {
1339
+ const previous = this.heads.get(branch);
1340
+ if (previous === id)
1341
+ return;
1342
+ if (previous !== void 0)
1343
+ this.removeReference(previous);
1344
+ this.heads.set(branch, id);
1345
+ this.addReference(id);
1346
+ }
1347
+ addReference(id) {
1348
+ this.references.set(id, (this.references.get(id) ?? 0) + 1);
1349
+ this.evictable.delete(id);
1350
+ }
1351
+ removeReference(id) {
1352
+ const next = (this.references.get(id) ?? 0) - 1;
1353
+ if (next > 0)
1354
+ this.references.set(id, next);
1355
+ else {
1356
+ this.references.delete(id);
1357
+ if (this.nodes.has(id))
1358
+ this.evictable.add(id);
1359
+ }
1360
+ }
1361
+ assertBranch(branch) {
1362
+ if (!BRANCH_PATTERN.test(branch))
1363
+ throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
1364
+ }
1365
+ };
1366
+
1367
+ // ../../sqlite/dist/default.js
1368
+ import { Database } from "@crvouga/mockingbird-service-sqlite";
1369
+ var createDefaultSqlite = () => new Database();
1370
+ var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
1371
+
1372
+ // ../../sqlite/dist/migrate.js
1373
+ var ensureMigrationsTable = (sqlite) => {
1374
+ sqlite.exec(`
1375
+ CREATE TABLE IF NOT EXISTS schema_migrations (
1376
+ id TEXT PRIMARY KEY NOT NULL,
1377
+ applied_at INTEGER NOT NULL
1378
+ )
1379
+ `);
1380
+ };
1381
+ var migrate = (sqlite, migrations) => {
1382
+ ensureMigrationsTable(sqlite);
1383
+ const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
1384
+ const pending = migrations.filter((migration) => !applied.has(migration.id));
1385
+ if (pending.length === 0)
1386
+ return;
1387
+ const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
1388
+ const now = Math.floor(Date.now() / 1e3);
1389
+ sqlite.transaction(() => {
1390
+ for (const migration of pending) {
1391
+ sqlite.exec(migration.sql);
1392
+ insert.run(migration.id, now);
1393
+ }
1394
+ });
1395
+ };
1396
+
1397
+ // ../../sqlite/dist/schema.js
1398
+ var CORE_MIGRATIONS = [
1399
+ {
1400
+ id: "20260322_core_records_sequences",
1401
+ sql: `
1402
+ CREATE TABLE IF NOT EXISTS mockingbird_records (
1403
+ namespace TEXT NOT NULL,
1404
+ collection TEXT NOT NULL,
1405
+ id TEXT NOT NULL,
1406
+ seq INTEGER NOT NULL,
1407
+ value TEXT NOT NULL,
1408
+ PRIMARY KEY (namespace, collection, id)
1409
+ );
1410
+ CREATE INDEX IF NOT EXISTS mockingbird_records_seq
1411
+ ON mockingbird_records (namespace, collection, seq);
1412
+ CREATE TABLE IF NOT EXISTS mockingbird_sequences (
1413
+ namespace TEXT NOT NULL,
1414
+ name TEXT NOT NULL,
1415
+ kind TEXT NOT NULL,
1416
+ value INTEGER NOT NULL,
1417
+ PRIMARY KEY (namespace, name, kind)
1418
+ );
1419
+ `
1420
+ }
1421
+ ];
1422
+ var migrateCore = (sqlite) => {
1423
+ migrate(sqlite, CORE_MIGRATIONS);
1424
+ };
1425
+ var clearNamespace = (sqlite, namespace) => {
1426
+ sqlite.transaction(() => {
1427
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1428
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1429
+ });
1430
+ };
1431
+
1432
+ // ../../openapi/metadata/dist/types.js
1433
+ var EXTENSION_KEYS = {
1434
+ operation: "x-mockingbird",
1435
+ resource: "x-mockingbird-resource",
1436
+ resourceRef: "x-mockingbird-resource-ref",
1437
+ volatile: "x-mockingbird-volatile",
1438
+ scope: "x-mockingbird-scope",
1439
+ unsupported: "x-mockingbird-unsupported",
1440
+ parityHeader: "x-mockingbird-parity-header"
1441
+ };
1442
+
1443
+ // ../../openapi/metadata/dist/read.js
1444
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1445
+ var extensionOf = (holder, key) => holder[key];
1446
+ var operationMetadata = (operation) => {
1447
+ const raw = extensionOf(operation, EXTENSION_KEYS.operation);
1448
+ const ext = isRecord2(raw) ? raw : {};
1449
+ const supported = ext.supported ?? true;
1450
+ const parity = ext.parity ?? {};
1451
+ return {
1452
+ supported,
1453
+ reason: typeof ext.reason === "string" ? ext.reason : void 0,
1454
+ parity: {
1455
+ enabled: supported && (parity.enabled ?? true),
1456
+ safe: parity.safe ?? true,
1457
+ reason: typeof parity.reason === "string" ? parity.reason : void 0
1458
+ }
1459
+ };
1460
+ };
1461
+
1462
+ // ../core/dist/service.js
1463
+ import { Hono } from "hono";
1464
+ var defineOperations = (handlers) => handlers;
1465
+ var OperationRegistryError = class extends Error {
1466
+ problems;
1467
+ constructor(problems) {
1468
+ super(`operation registry is inconsistent:
1469
+ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1470
+ this.problems = problems;
1471
+ this.name = "OperationRegistryError";
1472
+ }
1473
+ };
1474
+ var verifyOperations = (document2, handlers) => {
1475
+ const problems = [];
1476
+ const operations = listOperations(document2);
1477
+ const seen = /* @__PURE__ */ new Set();
1478
+ for (const operation of operations) {
1479
+ if (seen.has(operation.operationId))
1480
+ problems.push(`duplicate operationId ${operation.operationId}`);
1481
+ seen.add(operation.operationId);
1482
+ const supported = operationMetadata(operation.operation).supported;
1483
+ const handler = handlers[operation.operationId];
1484
+ if (supported && !handler)
1485
+ problems.push(`supported operation ${operation.operationId} has no handler`);
1486
+ if (!supported && handler)
1487
+ problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
1488
+ }
1489
+ for (const id of Object.keys(handlers)) {
1490
+ if (!seen.has(id))
1491
+ problems.push(`handler ${id} has no OpenAPI operation`);
1492
+ }
1493
+ return problems;
1494
+ };
1495
+ var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
1496
+ var routeOrder = (a, b) => {
1497
+ const sa = a.path.split("/");
1498
+ const sb = b.path.split("/");
1499
+ for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
1500
+ const x = sa[i] ?? "";
1501
+ const y = sb[i] ?? "";
1502
+ const px = x.startsWith("{");
1503
+ const py = y.startsWith("{");
1504
+ if (px !== py)
1505
+ return px ? 1 : -1;
1506
+ if (x !== y)
1507
+ return x < y ? -1 : 1;
1508
+ }
1509
+ return 0;
1510
+ };
1511
+ var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
1512
+ var bootSqlite = (sqlite) => {
1513
+ const client = resolveSqlite(sqlite);
1514
+ migrateCore(client);
1515
+ return client;
1516
+ };
1517
+ var createService = (options) => {
1518
+ const problems = verifyOperations(options.document, options.handlers);
1519
+ if (problems.length > 0)
1520
+ throw new OperationRegistryError(problems);
1521
+ migrateCore(options.sqlite);
1522
+ const now = options.now ?? (() => Date.now());
1523
+ const app = new Hono();
1524
+ app.notFound((c) => options.notFound(c.req.raw));
1525
+ app.onError((error, c) => options.onError(error, c.req.raw));
1526
+ const operations = [...listOperations(options.document)].sort(routeOrder);
1527
+ for (const operation of operations) {
1528
+ const metadata = operationMetadata(operation.operation);
1529
+ const handler = options.handlers[operation.operationId];
1530
+ const route = async (c) => {
1531
+ const request = c.req.raw;
1532
+ if (!metadata.supported || !handler) {
1533
+ return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
1534
+ }
1535
+ const url = new URL(request.url);
1536
+ const context = {
1537
+ request,
1538
+ url,
1539
+ params: c.req.param(),
1540
+ query: queryOf(url),
1541
+ body: await readBody(request),
1542
+ sqlite: options.sqlite,
1543
+ namespace: options.namespace,
1544
+ operation,
1545
+ document: options.document,
1546
+ now
1547
+ };
1548
+ const short = await options.before?.(context);
1549
+ if (short)
1550
+ return short;
1551
+ return handler(context);
1552
+ };
1553
+ app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
1554
+ }
1555
+ return {
1556
+ app,
1557
+ sqlite: options.sqlite,
1558
+ namespace: options.namespace,
1559
+ fetch: async (request) => app.fetch(request),
1560
+ reset: async () => {
1561
+ clearNamespace(options.sqlite, options.namespace);
1562
+ }
1563
+ };
1564
+ };
1565
+
1566
+ // ../core/dist/snapshot.js
1567
+ var snapshotNamespace = (sqlite, namespace) => ({
1568
+ namespace,
1569
+ records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
1570
+ sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
1571
+ });
1572
+ var restoreNamespace = (sqlite, namespace, snapshot) => {
1573
+ sqlite.transaction(() => {
1574
+ sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
1575
+ sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
1576
+ const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
1577
+ for (const row of snapshot.records) {
1578
+ record.run(namespace, row.collection, row.id, row.seq, row.value);
1579
+ }
1580
+ const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
1581
+ for (const row of snapshot.sequences) {
1582
+ sequence.run(namespace, row.name, row.kind, row.value);
1583
+ }
1584
+ });
1585
+ };
1586
+
1587
+ // ../core/dist/version.js
1588
+ var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
1589
+
1590
+ // ../core/dist/signing.js
1591
+ var encoder = new TextEncoder();
1592
+ var toBase64 = (bytes) => {
1593
+ let binary = "";
1594
+ for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {
1595
+ binary += String.fromCharCode(byte);
1596
+ }
1597
+ return btoa(binary);
1598
+ };
1599
+ var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
1600
+ var toHex = (bytes) => [...bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
1601
+ var keyBytes = (key) => typeof key === "string" ? encoder.encode(key) : key;
1602
+ var hmac = async (algorithm, key, message, encoding = "hex") => {
1603
+ const imported = await crypto.subtle.importKey("raw", keyBytes(key), { name: "HMAC", hash: algorithm }, false, ["sign"]);
1604
+ const signed = await crypto.subtle.sign("HMAC", imported, typeof message === "string" ? encoder.encode(message) : message);
1605
+ return encoding === "hex" ? toHex(signed) : toBase64(signed);
1606
+ };
1607
+ var svixSecretBytes = (secret) => {
1608
+ const raw = secret.replace(/^f?whsec_/, "");
1609
+ try {
1610
+ return fromBase64(raw);
1611
+ } catch {
1612
+ throw new TypeError("webhook secret must be whsec_<base64> (as Svix issues it)");
1613
+ }
1614
+ };
1615
+ var signSvix = async (secret, messageId, timestampSeconds, body) => `v1,${await hmac("SHA-256", svixSecretBytes(secret), `${messageId}.${timestampSeconds}.${body}`, "base64")}`;
1616
+ var signTimestamped = async (secret, timestampSeconds, body) => `t=${timestampSeconds},v1=${await hmac("SHA-256", secret, `${timestampSeconds}.${body}`, "hex")}`;
1617
+ var signTwilio = async (authToken, url, params) => {
1618
+ const payload = url + Object.keys(params).sort().map((key) => `${key}${params[key]}`).join("");
1619
+ return hmac("SHA-1", authToken, payload, "base64");
1620
+ };
1621
+
1622
+ // ../core/dist/webhooks.js
1623
+ var signers = {
1624
+ /** No signature. */
1625
+ none: () => () => ({}),
1626
+ /** Svix (`svix-id`, `svix-timestamp`, `svix-signature: v1,<b64>`): Junction, Flex, Resend. */
1627
+ svix: (options = {}) => async ({ messageId, body, timestampSeconds, secret }) => {
1628
+ if (!secret)
1629
+ return {};
1630
+ const prefix = options.prefix ?? "svix";
1631
+ return {
1632
+ [`${prefix}-id`]: messageId,
1633
+ [`${prefix}-timestamp`]: String(timestampSeconds),
1634
+ [`${prefix}-signature`]: await signSvix(secret, messageId, timestampSeconds, body)
1635
+ };
1636
+ },
1637
+ /** `<header>: t=<unix>,v1=<hex HMAC-SHA256(secret, "t.body")>`: Stripe, Persona, Fullscript. */
1638
+ timestamped: (header = "Stripe-Signature") => async ({ body, timestampSeconds, secret }) => secret ? { [header]: await signTimestamped(secret, timestampSeconds, body) } : {},
1639
+ /** `X-Twilio-Signature` over the public URL plus the sorted form parameters. */
1640
+ twilio: () => async ({ signUrl, form, secret }) => secret ? { "X-Twilio-Signature": await signTwilio(secret, signUrl, form ?? {}) } : {},
1641
+ /** The secret itself in a header (optionally templated): RxVortex, Pharmetika, AHA `Token <s>`. */
1642
+ header: (header, format = (s) => s) => ({ secret }) => secret ? { [header]: format(secret) } : {},
1643
+ /** Anything else: the service computes the headers itself. */
1644
+ custom: (sign) => sign
1645
+ };
1646
+ var DEFAULT_DELAYS = [0, 5e3, 3e5, 18e5, 72e5];
1647
+ var unref = (timer) => {
1648
+ ;
1649
+ timer.unref?.();
1650
+ };
1651
+ var randomId = (prefix) => `${prefix}${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`;
1652
+ var matchesEndpoint = (endpoint, message) => {
1653
+ const events = endpoint.events ?? ["*"];
1654
+ if (!events.includes("*") && !events.includes(message.type))
1655
+ return false;
1656
+ for (const [key, value] of Object.entries(endpoint.tags ?? {})) {
1657
+ if (message.tags[key] !== value)
1658
+ return false;
1659
+ }
1660
+ return true;
1661
+ };
1662
+ var createWebhookHub = (options) => {
1663
+ const delays = options.retryDelaysMs ?? DEFAULT_DELAYS;
1664
+ const timeoutMs = options.timeoutMs ?? 15e3;
1665
+ const delivered = options.delivered ?? ((status) => status >= 200 && status < 300);
1666
+ const send = options.fetch ?? ((request) => fetch(request));
1667
+ const keep = options.keep ?? 500;
1668
+ const now = options.now ?? Date.now;
1669
+ const id = options.id ?? randomId;
1670
+ const scheduleTimer = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
1671
+ const cancel = options.cancel ?? ((handle) => clearTimeout(handle));
1672
+ const global = (options.endpoints ?? []).map((e, i) => ({ ...e, id: e.id ?? `we_global_${i}` }));
1673
+ const own = /* @__PURE__ */ new Map();
1674
+ const messages = [];
1675
+ const deliveries = /* @__PURE__ */ new Map();
1676
+ const pending = /* @__PURE__ */ new Map();
1677
+ const payloads = /* @__PURE__ */ new Map();
1678
+ const faults = /* @__PURE__ */ new Map();
1679
+ const held = /* @__PURE__ */ new Map();
1680
+ const inFlight = /* @__PURE__ */ new Set();
1681
+ const track = (work) => {
1682
+ inFlight.add(work);
1683
+ void work.finally(() => inFlight.delete(work));
1684
+ };
1685
+ const attempt = async (delivery) => {
1686
+ const entry = payloads.get(delivery.id);
1687
+ if (!entry)
1688
+ return false;
1689
+ const { message, endpoint } = entry;
1690
+ const timestampSeconds = Math.floor(now() / 1e3);
1691
+ const started = now();
1692
+ const record = {
1693
+ attempt: delivery.attempts.length + 1,
1694
+ at: new Date(started).toISOString(),
1695
+ status: null,
1696
+ error: null,
1697
+ durationMs: 0,
1698
+ responseBody: null
1699
+ };
1700
+ const controller = new AbortController();
1701
+ const timer = scheduleTimer(() => controller.abort(), timeoutMs);
1702
+ try {
1703
+ const signed = await options.signer({
1704
+ messageId: message.id,
1705
+ body: message.body,
1706
+ timestampSeconds,
1707
+ url: endpoint.url,
1708
+ secret: endpoint.secret,
1709
+ signUrl: endpoint.signUrl ?? endpoint.url,
1710
+ form: message.contentType.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(message.body)) : void 0,
1711
+ type: message.type,
1712
+ tags: message.tags
1713
+ });
1714
+ const response = await send(new Request(endpoint.url, {
1715
+ method: "POST",
1716
+ headers: {
1717
+ "content-type": message.contentType,
1718
+ ...endpoint.headers,
1719
+ ...message.headers,
1720
+ ...signed
1721
+ },
1722
+ body: message.body,
1723
+ signal: controller.signal
1724
+ }));
1725
+ record.status = response.status;
1726
+ record.responseBody = await response.text();
1727
+ } catch (error) {
1728
+ record.error = controller.signal.aborted ? `timed out after ${timeoutMs}ms` : error instanceof Error ? error.message : String(error);
1729
+ } finally {
1730
+ cancel(timer);
1731
+ record.durationMs = now() - started;
1732
+ delivery.attempts.push(record);
1733
+ }
1734
+ return record.status !== null && delivered(record.status);
1735
+ };
1736
+ const schedule = (delivery) => {
1737
+ const index = delivery.attempts.length;
1738
+ if (index >= delays.length) {
1739
+ delivery.state = "failed";
1740
+ pending.delete(delivery.id);
1741
+ return;
1742
+ }
1743
+ const run = () => {
1744
+ pending.delete(delivery.id);
1745
+ track(attempt(delivery).then((ok) => {
1746
+ if (ok)
1747
+ delivery.state = "delivered";
1748
+ else
1749
+ schedule(delivery);
1750
+ }));
1751
+ };
1752
+ const delay = delays[index] ?? 0;
1753
+ if (delay <= 0) {
1754
+ pending.set(delivery.id, void 0);
1755
+ run();
1756
+ return;
1757
+ }
1758
+ const timer = scheduleTimer(run, delay);
1759
+ unref(timer);
1760
+ pending.set(delivery.id, timer);
1761
+ };
1762
+ const endpointsFor = (namespace) => [...own.get(namespace) ?? [], ...global];
1763
+ const fanOut = (message, state = "pending") => {
1764
+ for (const endpoint of endpointsFor(message.namespace)) {
1765
+ if (!matchesEndpoint(endpoint, message))
1766
+ continue;
1767
+ const delivery = {
1768
+ id: id("dlv_"),
1769
+ messageId: message.id,
1770
+ namespace: message.namespace,
1771
+ type: message.type,
1772
+ endpointId: endpoint.id ?? "we_unknown",
1773
+ url: endpoint.url,
1774
+ state,
1775
+ attempts: []
1776
+ };
1777
+ deliveries.set(delivery.id, delivery);
1778
+ payloads.set(delivery.id, { message, endpoint });
1779
+ if (state === "pending")
1780
+ schedule(delivery);
1781
+ }
1782
+ };
1783
+ const takeFault = (namespace) => {
1784
+ const queue = faults.get(namespace);
1785
+ const head = queue?.[0];
1786
+ if (!queue || !head)
1787
+ return void 0;
1788
+ head.remaining--;
1789
+ if (head.remaining <= 0)
1790
+ queue.shift();
1791
+ return head.mode;
1792
+ };
1793
+ const releaseHeld = (namespace) => {
1794
+ const waiting = held.get(namespace);
1795
+ if (!waiting)
1796
+ return;
1797
+ held.delete(namespace);
1798
+ for (const message of waiting)
1799
+ fanOut(message);
1800
+ };
1801
+ const hub = {
1802
+ publish(input) {
1803
+ const contentType = input.contentType ?? (input.form ? "application/x-www-form-urlencoded" : "application/json");
1804
+ const body = typeof input.body === "string" ? input.body : input.form ? new URLSearchParams(input.form).toString() : JSON.stringify(input.body);
1805
+ const message = {
1806
+ id: input.id ?? id("msg_"),
1807
+ namespace: input.namespace,
1808
+ type: input.type,
1809
+ body,
1810
+ contentType,
1811
+ tags: input.tags ?? {},
1812
+ headers: input.headers ?? {},
1813
+ publishedAt: new Date(now()).toISOString()
1814
+ };
1815
+ messages.push(message);
1816
+ const ofNamespace = messages.filter((m) => m.namespace === message.namespace);
1817
+ const oldest = ofNamespace[0];
1818
+ if (ofNamespace.length > keep && oldest)
1819
+ messages.splice(messages.indexOf(oldest), 1);
1820
+ options.onMessage?.(message);
1821
+ const fault = takeFault(message.namespace);
1822
+ if (fault === "drop") {
1823
+ fanOut(message, "dropped");
1824
+ return message;
1825
+ }
1826
+ if (fault === "reorder") {
1827
+ held.set(message.namespace, [...held.get(message.namespace) ?? [], message]);
1828
+ return message;
1829
+ }
1830
+ fanOut(message);
1831
+ if (fault === "duplicate")
1832
+ fanOut(message);
1833
+ releaseHeld(message.namespace);
1834
+ return message;
1835
+ },
1836
+ setEndpoints(namespace, endpoints) {
1837
+ const withIds = endpoints.map((e, i) => ({ ...e, id: e.id ?? `we_${namespace}_${i}` }));
1838
+ own.set(namespace, withIds);
1839
+ return withIds;
1840
+ },
1841
+ endpoints: endpointsFor,
1842
+ messages: (namespace) => namespace === void 0 ? [...messages] : messages.filter((m) => m.namespace === namespace),
1843
+ deliveries: (namespace) => [...deliveries.values()].filter((d) => namespace === void 0 || d.namespace === namespace),
1844
+ async replay(id2) {
1845
+ const delivery = deliveries.get(id2);
1846
+ if (!delivery)
1847
+ return void 0;
1848
+ const ok = await attempt(delivery);
1849
+ if (ok)
1850
+ delivery.state = "delivered";
1851
+ return delivery;
1852
+ },
1853
+ async flush() {
1854
+ for (const namespace of [...held.keys()])
1855
+ releaseHeld(namespace);
1856
+ const waiting = [...pending.entries()];
1857
+ for (const [id2, timer] of waiting) {
1858
+ if (timer === void 0)
1859
+ continue;
1860
+ cancel(timer);
1861
+ pending.delete(id2);
1862
+ const delivery = deliveries.get(id2);
1863
+ if (!delivery)
1864
+ continue;
1865
+ track(attempt(delivery).then((ok) => {
1866
+ if (ok)
1867
+ delivery.state = "delivered";
1868
+ else
1869
+ schedule(delivery);
1870
+ }));
1871
+ }
1872
+ await hub.idle();
1873
+ },
1874
+ async idle() {
1875
+ while (inFlight.size > 0)
1876
+ await Promise.allSettled([...inFlight]);
1877
+ },
1878
+ fault(namespace, fault) {
1879
+ const queue = faults.get(namespace) ?? [];
1880
+ queue.push({ mode: fault.mode, remaining: Math.max(1, fault.count ?? 1) });
1881
+ faults.set(namespace, queue);
1882
+ },
1883
+ clear(namespace) {
1884
+ for (const [id2, delivery] of deliveries) {
1885
+ if (namespace !== void 0 && delivery.namespace !== namespace)
1886
+ continue;
1887
+ const timer = pending.get(id2);
1888
+ if (timer !== void 0)
1889
+ cancel(timer);
1890
+ pending.delete(id2);
1891
+ deliveries.delete(id2);
1892
+ payloads.delete(id2);
1893
+ }
1894
+ for (let i = messages.length - 1; i >= 0; i--) {
1895
+ if (namespace === void 0 || messages[i]?.namespace === namespace)
1896
+ messages.splice(i, 1);
1897
+ }
1898
+ if (namespace === void 0) {
1899
+ held.clear();
1900
+ faults.clear();
1901
+ own.clear();
1902
+ } else {
1903
+ held.delete(namespace);
1904
+ faults.delete(namespace);
1905
+ own.delete(namespace);
1906
+ }
1907
+ }
1908
+ };
1909
+ return hub;
1910
+ };
1911
+ var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
1912
+ var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
1913
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1914
+ var parseEndpoint = (value) => {
1915
+ if (!isRecord3(value) || typeof value.url !== "string")
1916
+ return "each endpoint needs a url";
1917
+ try {
1918
+ new URL(value.url);
1919
+ } catch {
1920
+ return `not a URL: ${value.url}`;
1921
+ }
1922
+ const endpoint = { url: value.url };
1923
+ if (typeof value.id === "string")
1924
+ endpoint.id = value.id;
1925
+ if (typeof value.secret === "string")
1926
+ endpoint.secret = value.secret;
1927
+ if (typeof value.signUrl === "string")
1928
+ endpoint.signUrl = value.signUrl;
1929
+ const events = value.events ?? value.enabledEvents;
1930
+ if (Array.isArray(events))
1931
+ endpoint.events = events.map(String);
1932
+ if (isRecord3(value.tags)) {
1933
+ endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
1934
+ }
1935
+ if (typeof value.account === "string")
1936
+ endpoint.tags = { ...endpoint.tags, account: value.account };
1937
+ if (isRecord3(value.headers)) {
1938
+ endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
1939
+ }
1940
+ return endpoint;
1941
+ };
1942
+ var webhookAdminRoutes = (hub) => ({
1943
+ "GET /webhooks": ({ url, namespace }) => json3(200, {
1944
+ deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
1945
+ const type = url.searchParams.get("type");
1946
+ return type === null || d.type === type;
1947
+ })
1948
+ }),
1949
+ "GET /webhooks/events": ({ url, namespace }) => {
1950
+ const type = url.searchParams.get("type");
1951
+ return json3(200, {
1952
+ events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
1953
+ });
1954
+ },
1955
+ "POST /webhooks/:id/replay": async ({ params }) => {
1956
+ const replayed = await hub.replay(params.id);
1957
+ return replayed ? json3(200, replayed) : adminError2(404, `no delivery ${params.id}`);
1958
+ },
1959
+ "POST /webhooks/flush": async () => {
1960
+ await hub.flush();
1961
+ return json3(200, { status: "ok" });
1962
+ },
1963
+ "POST /webhooks/faults": ({ body, namespace }) => {
1964
+ if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
1965
+ return adminError2(400, "mode must be duplicate, reorder or drop");
1966
+ }
1967
+ const fault = { mode: body.mode };
1968
+ if (typeof body.count === "number")
1969
+ fault.count = body.count;
1970
+ hub.fault(namespace, fault);
1971
+ return json3(201, { namespace, ...fault });
1972
+ },
1973
+ "GET /webhook-endpoints": ({ namespace }) => json3(200, {
1974
+ endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
1975
+ ...rest,
1976
+ secret: secret ? "(set)" : null
1977
+ }))
1978
+ }),
1979
+ "PUT /webhook-endpoints": ({ body, namespace }) => {
1980
+ const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
1981
+ if (!Array.isArray(list))
1982
+ return adminError2(400, "expected [{url, secret?, events?}]");
1983
+ const parsed = [];
1984
+ for (const each of list) {
1985
+ const endpoint = parseEndpoint(each);
1986
+ if (typeof endpoint === "string")
1987
+ return adminError2(400, endpoint);
1988
+ parsed.push(endpoint);
1989
+ }
1990
+ const set = hub.setEndpoints(namespace, parsed);
1991
+ return json3(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
1992
+ },
1993
+ "DELETE /webhook-endpoints": ({ namespace }) => {
1994
+ hub.setEndpoints(namespace, []);
1995
+ return json3(200, { status: "ok" });
1996
+ }
1997
+ });
1998
+ var parsePayload = (message) => {
1999
+ if (message.contentType.startsWith("application/json")) {
2000
+ try {
2001
+ return JSON.parse(message.body);
2002
+ } catch {
2003
+ return message.body;
2004
+ }
2005
+ }
2006
+ if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
2007
+ return Object.fromEntries(new URLSearchParams(message.body));
2008
+ }
2009
+ return message.body;
2010
+ };
2011
+
2012
+ // ../core/dist/runtime.js
2013
+ var MOCKINGBIRD_HEADER = "x-mockingbird";
2014
+ var BRANCH_HEADER = "x-mockingbird-branch";
2015
+ var AT_HEADER = "x-mockingbird-at";
2016
+ var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
2017
+ var DEFAULT_NAMESPACE = "default";
2018
+ var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
2019
+ var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
2020
+ var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
2021
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
2022
+ var effects = /* @__PURE__ */ new WeakMap();
2023
+ var reuseSorted = (fresh, previous, compare, equal) => {
2024
+ if (!previous || previous.length === 0)
2025
+ return fresh.map((row) => Object.freeze(row));
2026
+ const result = new Array(fresh.length);
2027
+ let unchanged = fresh.length === previous.length;
2028
+ let oldIndex = 0;
2029
+ for (let index = 0; index < fresh.length; index++) {
2030
+ const row = fresh[index];
2031
+ while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
2032
+ oldIndex++;
2033
+ }
2034
+ const old = previous[oldIndex];
2035
+ result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
2036
+ if (result[index] !== previous[index])
2037
+ unchanged = false;
2038
+ }
2039
+ return unchanged ? previous : result;
2040
+ };
2041
+ var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
2042
+ var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
2043
+ var DroppedConnectionError = class extends TypeError {
2044
+ code = "MOCKINGBIRD_DROP";
2045
+ constructor() {
2046
+ super("fetch failed: connection dropped by Mockingbird fault");
2047
+ this.name = "TypeError";
2048
+ }
2049
+ };
2050
+ var operationMatcher = (document2) => {
2051
+ const matchers = listOperations(document2).map((operation) => ({
2052
+ operationId: operation.operationId,
2053
+ method: operation.method.toUpperCase(),
2054
+ pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
2055
+ params: (operation.path.match(/\{/g) ?? []).length
2056
+ })).sort((a, b) => a.params - b.params);
2057
+ return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
2058
+ };
2059
+ var createRuntime = (options) => {
2060
+ const sqlite = bootSqlite(options.sqlite);
2061
+ const clock = options.clock ?? createClock();
2062
+ const rng = createRng(options.seed ?? 0);
2063
+ const wallNow = options.io?.wallNow ?? Date.now;
2064
+ const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
2065
+ const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
2066
+ const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
2067
+ const metrics = createMetrics();
2068
+ const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
2069
+ const version = options.version ?? PACKAGE_VERSION;
2070
+ const instances = /* @__PURE__ */ new Map();
2071
+ const publicNamespaces = /* @__PURE__ */ new Set();
2072
+ const branchRngs = /* @__PURE__ */ new Map();
2073
+ const timelines = /* @__PURE__ */ new Map();
2074
+ const branchStorage = /* @__PURE__ */ new Map();
2075
+ const captured = /* @__PURE__ */ new Map();
2076
+ const credentials = createCredentialRegistry();
2077
+ const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
2078
+ const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
2079
+ const instanceFor = (key, publicNamespace = key, isolatedRng) => {
2080
+ const existing = instances.get(key);
2081
+ if (existing)
2082
+ return existing;
2083
+ if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
2084
+ throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
2085
+ }
2086
+ const created = options.create({
2087
+ namespace: storageNamespace(key),
2088
+ publicNamespace,
2089
+ sqlite,
2090
+ clock,
2091
+ rng: isolatedRng ?? rng
2092
+ });
2093
+ instances.set(key, created);
2094
+ publicNamespaces.add(publicNamespace);
2095
+ if (isolatedRng)
2096
+ branchRngs.set(key, isolatedRng);
2097
+ return created;
2098
+ };
2099
+ const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
2100
+ const capture = (storage) => {
2101
+ const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
2102
+ const previous = captured.get(storage);
2103
+ const snapshot2 = {
2104
+ namespace: fresh.namespace,
2105
+ 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),
2106
+ 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)
2107
+ };
2108
+ Object.freeze(snapshot2.records);
2109
+ Object.freeze(snapshot2.sequences);
2110
+ Object.freeze(snapshot2);
2111
+ captured.set(storage, snapshot2);
2112
+ return Object.freeze({
2113
+ snapshot: snapshot2,
2114
+ clock: Object.freeze(clock.state()),
2115
+ rngState: (branchRngs.get(storage) ?? rng).state()
2116
+ });
2117
+ };
2118
+ const timeline = (name = DEFAULT_NAMESPACE) => {
2119
+ let found = timelines.get(name);
2120
+ if (found)
2121
+ return found;
2122
+ instance(name);
2123
+ found = new Timeline({
2124
+ now: clock.now,
2125
+ ...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
2126
+ });
2127
+ found.commit(capture(name));
2128
+ timelines.set(name, found);
2129
+ return found;
2130
+ };
2131
+ const physicalBranch = (namespace, branch2) => {
2132
+ if (branch2 === "main")
2133
+ return namespace;
2134
+ const mapKey = `${namespace}\0${branch2}`;
2135
+ const existing = branchStorage.get(mapKey);
2136
+ if (existing)
2137
+ return existing;
2138
+ const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
2139
+ branchStorage.set(mapKey, key);
2140
+ return key;
2141
+ };
2142
+ const ensureBranch = (namespace, branch2, at) => {
2143
+ if (!BRANCH_PATTERN2.test(branch2))
2144
+ throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
2145
+ const history = timeline(namespace);
2146
+ if (branch2 === "main") {
2147
+ if (at !== void 0) {
2148
+ const point = history.checkout("main", at);
2149
+ restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
2150
+ captured.set(namespace, point.value.snapshot);
2151
+ rng.setState(point.value.rngState);
2152
+ clock.set(point.value.clock.now);
2153
+ if (point.value.clock.frozen)
2154
+ clock.freeze();
2155
+ else
2156
+ clock.unfreeze();
2157
+ }
2158
+ return namespace;
2159
+ }
2160
+ const storage = physicalBranch(namespace, branch2);
2161
+ if (!history.hasBranch(branch2)) {
2162
+ if (at === void 0)
2163
+ history.commit(capture(namespace));
2164
+ const point = history.fork(branch2, at === void 0 ? {} : { from: at });
2165
+ const branchRng = createRng(options.seed ?? 0);
2166
+ if (point)
2167
+ branchRng.setState(point.value.rngState);
2168
+ instanceFor(storage, namespace, branchRng);
2169
+ if (point)
2170
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2171
+ if (point)
2172
+ captured.set(storage, point.value.snapshot);
2173
+ } else if (at !== void 0 && history.head(branch2)?.id !== at) {
2174
+ const point = history.checkout(branch2, at);
2175
+ if (!instances.has(storage)) {
2176
+ const branchRng = createRng(options.seed ?? 0);
2177
+ branchRng.setState(point.value.rngState);
2178
+ instanceFor(storage, namespace, branchRng);
2179
+ }
2180
+ branchRngs.get(storage)?.setState(point.value.rngState);
2181
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2182
+ captured.set(storage, point.value.snapshot);
2183
+ } else {
2184
+ if (!instances.has(storage)) {
2185
+ const point = history.head(branch2);
2186
+ const branchRng = createRng(options.seed ?? 0);
2187
+ if (point)
2188
+ branchRng.setState(point.value.rngState);
2189
+ instanceFor(storage, namespace, branchRng);
2190
+ }
2191
+ }
2192
+ return storage;
2193
+ };
2194
+ const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
2195
+ const storage = ensureBranch(namespace, branch2);
2196
+ return timeline(namespace).commit(capture(storage), { branch: branch2 });
2197
+ };
2198
+ const branch = (name, branchOptions = {}) => {
2199
+ const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
2200
+ ensureBranch(namespace, name, branchOptions.at);
2201
+ const head = timeline(namespace).head(name);
2202
+ if (!head)
2203
+ throw new RangeError(`branch ${name} has no checkpoint`);
2204
+ return head;
2205
+ };
2206
+ const checkout = (checkpointId, checkoutOptions = {}) => {
2207
+ const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
2208
+ const branchName = checkoutOptions.branch ?? "main";
2209
+ const history = timeline(namespace);
2210
+ const point = history.checkout(branchName, checkpointId);
2211
+ const storage = ensureBranch(namespace, branchName);
2212
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2213
+ captured.set(storage, point.value.snapshot);
2214
+ clock.set(point.value.clock.now);
2215
+ if (point.value.clock.frozen)
2216
+ clock.freeze();
2217
+ else
2218
+ clock.unfreeze();
2219
+ (branchRngs.get(storage) ?? rng).setState(point.value.rngState);
2220
+ };
2221
+ const reset = async (name = DEFAULT_NAMESPACE) => {
2222
+ if (name === "*") {
2223
+ options.webhooks?.clear();
2224
+ for (const each of instances.values())
2225
+ await each.reset();
2226
+ timelines.clear();
2227
+ branchStorage.clear();
2228
+ branchRngs.clear();
2229
+ captured.clear();
2230
+ return;
2231
+ }
2232
+ options.webhooks?.clear(name);
2233
+ const target = instances.get(name);
2234
+ if (target)
2235
+ await target.reset();
2236
+ else
2237
+ clearNamespace(sqlite, storageNamespace(name));
2238
+ for (const [mapping, storage] of branchStorage) {
2239
+ if (!mapping.startsWith(`${name}\0`))
2240
+ continue;
2241
+ const branchInstance = instances.get(storage);
2242
+ if (branchInstance)
2243
+ await branchInstance.reset();
2244
+ else
2245
+ clearNamespace(sqlite, storageNamespace(storage));
2246
+ branchStorage.delete(mapping);
2247
+ branchRngs.delete(storage);
2248
+ captured.delete(storage);
2249
+ }
2250
+ timelines.delete(name);
2251
+ captured.delete(name);
2252
+ };
2253
+ const snapshot = (name = DEFAULT_NAMESPACE) => {
2254
+ return checkpoint(name, "main").value.snapshot;
2255
+ };
2256
+ const restore = (from, name = DEFAULT_NAMESPACE) => {
2257
+ instance(name);
2258
+ restoreNamespace(sqlite, storageNamespace(name), from);
2259
+ captured.set(name, from);
2260
+ const history = timelines.get(name);
2261
+ if (history)
2262
+ history.commit(capture(name), { branch: "main" });
2263
+ else
2264
+ timeline(name);
2265
+ };
2266
+ const runtime = {
2267
+ name: options.name,
2268
+ sqlite,
2269
+ clock,
2270
+ faults,
2271
+ metrics,
2272
+ journal,
2273
+ rng,
2274
+ credentials,
2275
+ webhooks: options.webhooks,
2276
+ applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
2277
+ const preset = options.presets?.[name];
2278
+ if (!preset)
2279
+ throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
2280
+ const added = (preset.rules ?? []).map((rule, index) => faults.add({
2281
+ namespace,
2282
+ ...rule,
2283
+ ...overrides,
2284
+ preset: name,
2285
+ id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
2286
+ }));
2287
+ if (preset.webhook && options.webhooks) {
2288
+ options.webhooks.fault(namespace, {
2289
+ ...preset.webhook,
2290
+ ...overrides.count !== void 0 ? { count: overrides.count } : {}
2291
+ });
2292
+ }
2293
+ return added;
2294
+ },
2295
+ instance,
2296
+ namespaces: () => [...publicNamespaces].sort(),
2297
+ reset,
2298
+ snapshot,
2299
+ restore,
2300
+ checkpoint,
2301
+ branch,
2302
+ checkout,
2303
+ timeline,
2304
+ fetch: async (incoming) => {
2305
+ let request = incoming;
2306
+ const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
2307
+ if (prefixed) {
2308
+ const url2 = new URL(request.url);
2309
+ url2.pathname = prefixed[2] ?? "/";
2310
+ const headers = new Headers(request.headers);
2311
+ if (!headers.has(NAMESPACE_HEADER)) {
2312
+ headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
2313
+ }
2314
+ const hasBody = request.method !== "GET" && request.method !== "HEAD";
2315
+ request = new Request(url2, {
2316
+ method: request.method,
2317
+ headers,
2318
+ ...hasBody ? { body: await request.arrayBuffer() } : {},
2319
+ signal: request.signal
2320
+ });
2321
+ }
2322
+ let namespace = control.namespaceOf(request);
2323
+ if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
2324
+ const credential = options.credential(request);
2325
+ const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
2326
+ if (mapped !== void 0)
2327
+ namespace = mapped;
2328
+ }
2329
+ const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
2330
+ const at = request.headers.get(AT_HEADER) ?? void 0;
2331
+ const stamp = (response2) => {
2332
+ const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
2333
+ try {
2334
+ response2.headers.set(MOCKINGBIRD_HEADER, value);
2335
+ return response2;
2336
+ } catch {
2337
+ const copy = new Response(response2.body, response2);
2338
+ copy.headers.set(MOCKINGBIRD_HEADER, value);
2339
+ return copy;
2340
+ }
2341
+ };
2342
+ const handled = await control.handle(request);
2343
+ if (handled)
2344
+ return stamp(handled);
2345
+ const started = monotonicNow();
2346
+ const url = new URL(request.url);
2347
+ const operationId = operationIdFor(request, url.pathname);
2348
+ const log = (status, faultId, response2) => {
2349
+ const noted = response2 ? responseNotes(response2) : void 0;
2350
+ const entry = {
2351
+ service: options.name,
2352
+ namespace,
2353
+ operationId,
2354
+ method: request.method,
2355
+ path: url.pathname,
2356
+ status,
2357
+ durationMs: Math.round((monotonicNow() - started) * 100) / 100,
2358
+ unmatched: options.document !== void 0 && operationId === void 0,
2359
+ ...faultId !== void 0 ? { faultId } : {},
2360
+ ...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
2361
+ ...noted?.adopted ? { adopted: true } : {}
2362
+ };
2363
+ metrics.record(entry);
2364
+ journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
2365
+ options.onLog?.(entry);
2366
+ };
2367
+ if (!NAMESPACE_PATTERN.test(namespace)) {
2368
+ log(400);
2369
+ return stamp(new Response(JSON.stringify({
2370
+ error: {
2371
+ type: "mockingbird_admin",
2372
+ message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
2373
+ }
2374
+ }), { status: 400, headers: { "content-type": "application/json" } }));
2375
+ }
2376
+ if (!BRANCH_PATTERN2.test(selectedBranch)) {
2377
+ log(400);
2378
+ return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
2379
+ }
2380
+ let storage;
2381
+ try {
2382
+ if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
2383
+ const point = timeline(namespace).get(at);
2384
+ storage = physicalBranch(namespace, `at_${at}`);
2385
+ let viewRng = branchRngs.get(storage);
2386
+ if (!viewRng) {
2387
+ viewRng = createRng(options.seed ?? 0);
2388
+ instanceFor(storage, namespace, viewRng);
2389
+ }
2390
+ viewRng.setState(point.value.rngState);
2391
+ restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
2392
+ captured.set(storage, point.value.snapshot);
2393
+ } else {
2394
+ storage = ensureBranch(namespace, selectedBranch, at);
2395
+ }
2396
+ } catch (error) {
2397
+ log(409);
2398
+ return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
2399
+ }
2400
+ const hits = await faults.take({
2401
+ operationId,
2402
+ method: request.method,
2403
+ path: url.pathname,
2404
+ namespace
2405
+ });
2406
+ const final = hits.find((hit) => hit.drop || hit.response);
2407
+ if (final?.drop) {
2408
+ log(0, final.id);
2409
+ throw new DroppedConnectionError();
2410
+ }
2411
+ if (final?.response) {
2412
+ log(final.response.status, final.id);
2413
+ return stamp(final.response);
2414
+ }
2415
+ const fired = hits.filter((hit) => hit.effect !== void 0);
2416
+ if (fired.length > 0)
2417
+ effects.set(request, fired.map((hit) => hit.effect));
2418
+ let response = await instanceFor(storage, namespace).fetch(request);
2419
+ if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
2420
+ const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
2421
+ response = mutableResponse(response);
2422
+ response.headers.set(CHECKPOINT_HEADER, point.id);
2423
+ }
2424
+ if (selectedBranch !== "main") {
2425
+ response = mutableResponse(response);
2426
+ response.headers.set(BRANCH_HEADER, selectedBranch);
2427
+ }
2428
+ if (at !== void 0) {
2429
+ response = mutableResponse(response);
2430
+ response.headers.set(AT_HEADER, at);
2431
+ }
2432
+ log(response.status, fired[0]?.id, response);
2433
+ return stamp(response);
2434
+ }
2435
+ };
2436
+ const control = createControlPlane({
2437
+ name: options.name,
2438
+ startedAt: wallNow(),
2439
+ wallNow,
2440
+ clock,
2441
+ faults,
2442
+ metrics,
2443
+ journal,
2444
+ defaultNamespace: DEFAULT_NAMESPACE,
2445
+ namespaces: runtime.namespaces,
2446
+ reset,
2447
+ timeTravel: {
2448
+ checkpoint: (name, branchName) => {
2449
+ const point = checkpoint(name, branchName);
2450
+ return {
2451
+ id: point.id,
2452
+ branch: point.branch,
2453
+ parent: point.parent,
2454
+ at: point.at,
2455
+ records: point.value.snapshot.records.length
2456
+ };
2457
+ },
2458
+ branch: (branchName, branchOptions) => {
2459
+ const point = branch(branchName, branchOptions);
2460
+ return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
2461
+ },
2462
+ checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
2463
+ retain: (name, checkpointId) => {
2464
+ timeline(name).retain(checkpointId);
2465
+ },
2466
+ release: (name, checkpointId) => timeline(name).release(checkpointId),
2467
+ inspect: (name) => {
2468
+ const history = timeline(name);
2469
+ return {
2470
+ branches: history.branches(),
2471
+ checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
2472
+ id,
2473
+ branch: branchName,
2474
+ parent,
2475
+ at
2476
+ }))
2477
+ };
2478
+ }
2479
+ },
2480
+ describe: options.describe ?? (() => ({})),
2481
+ ...options.presets ? {
2482
+ applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
2483
+ } : {},
2484
+ routes: {
2485
+ ...credentialRoutes(credentials),
2486
+ ...options.presets ? presetRoutes(options.presets, runtime) : {},
2487
+ ...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
2488
+ ...options.admin?.(runtime) ?? {}
2489
+ },
2490
+ adminKey: options.adminKey
2491
+ });
2492
+ return runtime;
2493
+ };
2494
+ var mutableResponse = (response) => {
2495
+ try {
2496
+ response.headers.set("x-mockingbird-mutable-probe", "1");
2497
+ response.headers.delete("x-mockingbird-mutable-probe");
2498
+ return response;
2499
+ } catch {
2500
+ return new Response(response.body, response);
2501
+ }
2502
+ };
2503
+ var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2504
+ var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
2505
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2506
+ var credentialRoutes = (registry) => ({
2507
+ "GET /credentials": () => adminJson(200, {
2508
+ credentials: registry.entries().map(({ credential, namespace }) => ({
2509
+ credential: maskCredential(credential),
2510
+ namespace
2511
+ }))
2512
+ }),
2513
+ "PUT /credentials": ({ body, namespace }) => {
2514
+ const pairs = [];
2515
+ const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
2516
+ if (Array.isArray(list)) {
2517
+ for (const each of list) {
2518
+ if (typeof each === "string")
2519
+ pairs.push([each, namespace]);
2520
+ else if (isObject(each) && typeof each.credential === "string") {
2521
+ pairs.push([
2522
+ each.credential,
2523
+ typeof each.namespace === "string" ? each.namespace : namespace
2524
+ ]);
2525
+ } else
2526
+ return adminFail(400, "each entry is a credential string or {credential, namespace}");
2527
+ }
2528
+ } else if (isObject(list)) {
2529
+ for (const [credential, target] of Object.entries(list)) {
2530
+ if (typeof target !== "string")
2531
+ return adminFail(400, `namespace for ${credential} must be a string`);
2532
+ pairs.push([credential, target]);
2533
+ }
2534
+ } else if (isObject(body) && typeof body.credential === "string") {
2535
+ pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
2536
+ } else {
2537
+ return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
2538
+ }
2539
+ for (const [credential, target] of pairs) {
2540
+ if (!NAMESPACE_PATTERN.test(target))
2541
+ return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
2542
+ registry.set(credential, target);
2543
+ }
2544
+ return adminJson(200, { mapped: pairs.length });
2545
+ },
2546
+ "DELETE /credentials": ({ url }) => {
2547
+ const credential = url.searchParams.get("credential");
2548
+ if (credential === null)
2549
+ registry.clear();
2550
+ else
2551
+ registry.remove(credential);
2552
+ return adminJson(200, { status: "ok" });
2553
+ }
2554
+ });
2555
+ var presetRoutes = (presets, runtime) => ({
2556
+ "GET /faults/presets": () => adminJson(200, {
2557
+ presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
2558
+ }),
2559
+ "POST /faults/presets/:name": ({ params, body, namespace }) => {
2560
+ const name = params.name;
2561
+ if (!presets[name])
2562
+ return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
2563
+ const overrides = isObject(body) ? body : {};
2564
+ return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
2565
+ }
2566
+ });
2567
+
2568
+ // ../core/dist/validation.js
2569
+ var bodyIssues = (context, contentType = "application/json") => {
2570
+ const requestBody = context.operation.operation.requestBody;
2571
+ if (!requestBody)
2572
+ return [];
2573
+ const resolved = deref(context.document, requestBody);
2574
+ const schema = resolved.content?.[contentType]?.schema;
2575
+ if (!schema)
2576
+ return [];
2577
+ const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
2578
+ if (context.body.kind === "invalid") {
2579
+ return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
2580
+ }
2581
+ if (value === void 0) {
2582
+ return resolved.required ? [{ path: "", message: "request body is required" }] : [];
2583
+ }
2584
+ return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
2585
+ };
2586
+
2587
+ // src/generated/openapi.ts
2588
+ var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Customer.io CDP + App API (Mockingbird subset)","description":"Stateful mock subset of Customer.io: the Segment-compatible CDP ingestion endpoints\\n(\`identify\`, \`track\`, \`batch\`, as \`@customerio/cdp-analytics-node\` posts them), the App API\\ntransactional sends (email, SMS, inbox message) and transactional-message catalog, and the\\nlink-tracking click endpoint. One process serves all three hosts (\`cdp.customer.io\`,\\n\`api.customer.io\`, the tracking domain); their paths do not collide.\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from Customer.io's CDP (Segment spec) and App API reference, trimmed to what our consumer sends: customer-io.client.service.ts / notification-adapter.ts / transactional-email-adapter.ts (backend), transactional-client.ts (notification-processor), customerio-trigger-name-validator.ts (notification-service) and mobile-links-click-reporter.service.ts."}},"servers":[{"url":"https://api.customer.io"},{"url":"https://cdp.customer.io"}],"paths":{"/v1/identify":{"post":{"operationId":"CdpIdentify","security":[{"cdpWriteKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IdentifyEvent"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpSuccess"}}}},"400":{"description":"Malformed event","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}},"401":{"description":"Missing or unknown write key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}}}}},"/v1/track":{"post":{"operationId":"CdpTrack","security":[{"cdpWriteKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TrackEvent"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpSuccess"}}}},"400":{"description":"Malformed event","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}},"401":{"description":"Missing or unknown write key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}}}}},"/v1/batch":{"post":{"operationId":"CdpBatch","description":"What \`@customerio/cdp-analytics-node\` posts: \`{batch: [...]}\`.","security":[{"cdpWriteKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["batch"],"properties":{"batch":{"type":"array","maxItems":5,"items":{"anyOf":[{"$ref":"#/components/schemas/IdentifyEvent"},{"$ref":"#/components/schemas/TrackEvent"}]}},"sentAt":{"type":"string"},"context":{"type":"object"}}}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpSuccess"}}}},"400":{"description":"Malformed batch","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}},"401":{"description":"Missing or unknown write key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}}}}},"/v1/send/email":{"post":{"operationId":"SendEmail","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendEmailRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/send/sms":{"post":{"operationId":"SendSms","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendSmsRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/send/inbox_message":{"post":{"operationId":"SendInboxMessage","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendInboxRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/transactional":{"get":{"operationId":"ListTransactionalMessages","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Every transactional message in the workspace (no pagination)","content":{"application/json":{"schema":{"type":"object","required":["messages"],"properties":{"messages":{"type":"array","items":{"$ref":"#/components/schemas/TransactionalMessage"}}}}}}},"401":{"$ref":"#/components/responses/AppError"}}}},"/v1/transactional/{transactional_id}":{"parameters":[{"name":"transactional_id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"transactional_message","missing":"999999"}}}],"get":{"operationId":"GetTransactionalMessage","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"One transactional message","content":{"application/json":{"schema":{"type":"object","required":["message"],"properties":{"message":{"$ref":"#/components/schemas/TransactionalMessage"}}}}}},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/click/{linkId}":{"parameters":[{"name":"linkId","in":"path","required":true,"schema":{"type":"string","pattern":"^[A-Za-z0-9_~-][A-Za-z0-9._~-]{0,63}$"}}],"post":{"operationId":"ReportClick","description":"Link-tracking click report on the tracking domain (our backend posts it when a smart\\nlink opens the app directly). Unauthenticated.\\n","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"200":{"description":"Click recorded (no body)"},"404":{"description":"Unknown link","content":{"text/plain":{"schema":{"type":"string"}}}}}},"get":{"operationId":"FollowClick","description":"A browser following a tracked link; redirects to the original URL.","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"302":{"description":"Redirect to the original URL"},"404":{"description":"Unknown link","content":{"text/plain":{"schema":{"type":"string"}}}}}}}},"components":{"securitySchemes":{"cdpWriteKey":{"type":"http","scheme":"basic","description":"\`Basic base64(<write key>:)\` (the CDP source write key as the username)."},"appApiKey":{"type":"http","scheme":"bearer","description":"\`Bearer <App API key>\`."}},"responses":{"Queued":{"description":"Queued for delivery","content":{"application/json":{"schema":{"type":"object","required":["delivery_id","queued_at"],"properties":{"delivery_id":{"type":"string","x-mockingbird-resource":{"type":"delivery","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"queued_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}}}}}}},"AppError":{"description":"An App API error","content":{"application/json":{"schema":{"type":"object","required":["meta"],"properties":{"meta":{"type":"object","required":["error"],"properties":{"error":{"type":"string"}}}}}}}}},"schemas":{"CdpSuccess":{"type":"object","required":["success"],"properties":{"success":{"type":"boolean"}}},"CdpError":{"type":"object","required":["error"],"properties":{"error":{"type":"string"}}},"IdentifyEvent":{"type":"object","properties":{"type":{"type":"string","enum":["identify"]},"userId":{"type":"string","minLength":1,"maxLength":64},"anonymousId":{"type":"string","minLength":1,"maxLength":64},"traits":{"type":"object","additionalProperties":true},"context":{"type":"object"},"integrations":{"type":"object"},"timestamp":{"type":"string"},"messageId":{"type":"string","maxLength":128},"_metadata":{"type":"object"}}},"TrackEvent":{"type":"object","required":["event"],"properties":{"type":{"type":"string","enum":["track"]},"userId":{"type":"string","minLength":1,"maxLength":64},"anonymousId":{"type":"string","minLength":1,"maxLength":64},"event":{"type":"string","minLength":1,"maxLength":150},"properties":{"type":"object","additionalProperties":true},"context":{"type":"object"},"integrations":{"type":"object"},"timestamp":{"type":"string"},"messageId":{"type":"string","maxLength":128},"_metadata":{"type":"object"}}},"Identifiers":{"type":"object","properties":{"id":{"type":"string","minLength":1,"maxLength":64},"email":{"type":"string","format":"email","maxLength":120},"cio_id":{"type":"string","maxLength":64}}},"TransactionalMessageId":{"oneOf":[{"type":"string","minLength":1,"maxLength":150},{"type":"integer","minimum":1}]},"SendEmailRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"to":{"type":"string","maxLength":200},"from":{"type":"string","maxLength":200},"subject":{"type":"string","maxLength":300},"body":{"type":"string"},"message_data":{"type":"object","additionalProperties":true},"send_to_unsubscribed":{"type":"boolean"},"tracked":{"type":"boolean"},"disable_message_retention":{"type":"boolean"},"headers":{"type":"object","additionalProperties":{"type":"string"}},"attachments":{"description":"Customer.io documents a \`{filename: base64}\` map; our backend sends an array of \`{filename, content, content_type}\`. Both are accepted.","oneOf":[{"type":"object","additionalProperties":{"type":"string"}},{"type":"array","items":{"type":"object","required":["filename","content"],"properties":{"filename":{"type":"string"},"content":{"type":"string"},"content_type":{"type":"string"}}}}]}}},"SendSmsRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"to":{"type":"string","maxLength":20},"message_data":{"type":"object","additionalProperties":true},"send_to_unsubscribed":{"type":"boolean"},"tracked":{"type":"boolean"},"disable_message_retention":{"type":"boolean"}}},"SendInboxRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"message_data":{"type":"object","additionalProperties":true}}},"TransactionalMessage":{"type":"object","required":["id","name"],"properties":{"id":{"type":"integer"},"name":{"type":"string"},"trigger_name":{"type":"string","x-mockingbird-resource":{"type":"transactional_message","identity":true}},"description":{"type":"string"},"send_to_unsubscribed":{"type":"boolean"},"link_tracking":{"type":"boolean"},"open_tracking":{"type":"boolean"},"hide_message_body":{"type":"boolean"},"queue_drafts":{"type":"boolean"},"created_at":{"type":"integer"},"updated_at":{"type":"integer"}}}}}}`);
2589
+ var operationIds = ["CdpIdentify", "CdpTrack", "CdpBatch", "SendEmail", "SendSms", "SendInboxMessage", "ListTransactionalMessages", "GetTransactionalMessage", "FollowClick", "ReportClick"];
2590
+ var supportedOperationIds = ["CdpIdentify", "CdpTrack", "CdpBatch", "SendEmail", "SendSms", "SendInboxMessage", "ListTransactionalMessages", "GetTransactionalMessage", "FollowClick", "ReportClick"];
2591
+
2592
+ // src/state.ts
2593
+ var DEFAULT_SETTINGS = {
2594
+ strictMessages: false,
2595
+ trackingBase: "https://links.customer.io",
2596
+ keys: []
2597
+ };
2598
+ var TRANSACTIONAL_EMAIL_KEYS = [
2599
+ "welcome",
2600
+ "bloodwork_reminder",
2601
+ "appointment",
2602
+ "keys",
2603
+ "forms",
2604
+ "billing",
2605
+ "bloodwork",
2606
+ "provider_bloodwork",
2607
+ "bloodwork_results",
2608
+ "payment_failed",
2609
+ "payment_charged",
2610
+ "subscription_renewal",
2611
+ "new_message_email",
2612
+ "requisition_pdf",
2613
+ "post_wellness_visit",
2614
+ "post_provider_visit",
2615
+ "post_bloodwork_review",
2616
+ "event_bloodwork_scheduled",
2617
+ "event_bloodwork_booth_location"
2618
+ ];
2619
+ var CATALOG_EPOCH = 1735689600;
2620
+ var DEFAULT_TRANSACTIONAL_MESSAGES = [
2621
+ ...TRANSACTIONAL_EMAIL_KEYS.map((key) => `geviti_${key}`),
2622
+ "geviti_inbox_message",
2623
+ "geviti_playground_notification"
2624
+ ].map((trigger, index) => ({
2625
+ id: index + 1,
2626
+ name: trigger.replace(/^geviti_/, "Geviti ").replace(/_/g, " "),
2627
+ trigger_name: trigger,
2628
+ description: "",
2629
+ send_to_unsubscribed: true,
2630
+ link_tracking: false,
2631
+ open_tracking: true,
2632
+ hide_message_body: false,
2633
+ queue_drafts: false,
2634
+ created_at: CATALOG_EPOCH,
2635
+ updated_at: CATALOG_EPOCH
2636
+ }));
2637
+ var CustomerIoState = class {
2638
+ constructor(sqlite, namespace, seed) {
2639
+ this.seed = seed;
2640
+ this.deliveries = new OutboxStore(sqlite, namespace, "deliveries");
2641
+ this.cdp = new Collection(sqlite, namespace, "cdp");
2642
+ this.profiles = new Collection(sqlite, namespace, "profiles");
2643
+ this.messages = new Collection(sqlite, namespace, "transactional");
2644
+ this.links = new Collection(sqlite, namespace, "links");
2645
+ this.settings = new Collection(sqlite, namespace, "settings");
2646
+ this.ids = new IdSequence(sqlite, namespace, "customerio");
2647
+ this.ensureSeeded();
2648
+ }
2649
+ seed;
2650
+ deliveries;
2651
+ cdp;
2652
+ profiles;
2653
+ messages;
2654
+ links;
2655
+ settings;
2656
+ ids;
2657
+ ensureSeeded() {
2658
+ if (this.messages.count() === 0) {
2659
+ for (const message of this.seed.messages) this.messages.insert(String(message.id), message);
2660
+ }
2661
+ if (!this.settings.has("settings")) {
2662
+ this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed.settings });
2663
+ }
2664
+ }
2665
+ current() {
2666
+ return this.settings.get("settings") ?? DEFAULT_SETTINGS;
2667
+ }
2668
+ update(patch) {
2669
+ const next = { ...this.current(), ...patch };
2670
+ this.settings.insert("settings", next);
2671
+ return next;
2672
+ }
2673
+ catalog() {
2674
+ return this.messages.list({ order: "oldest" }).map((row) => row.value);
2675
+ }
2676
+ /** A catalog message by numeric id or (case-insensitive) trigger name. */
2677
+ message(idOrTrigger) {
2678
+ const byId = /^\d+$/.test(idOrTrigger) ? this.messages.get(String(Number(idOrTrigger))) : void 0;
2679
+ if (byId) return byId;
2680
+ const lower = idOrTrigger.toLowerCase();
2681
+ return this.catalog().find((m) => m.trigger_name.toLowerCase() === lower);
2682
+ }
2683
+ profile(id) {
2684
+ return this.profiles.get(id);
2685
+ }
2686
+ /** The profile an App API `identifiers` object names (by id, else by email). */
2687
+ profileFor(identifiers) {
2688
+ if (identifiers.id) return this.profile(identifiers.id);
2689
+ if (identifiers.email) {
2690
+ const email = identifiers.email.toLowerCase();
2691
+ return this.profiles.list({ where: (p) => p.email?.toLowerCase() === email }).at(0)?.value;
2692
+ }
2693
+ return void 0;
2694
+ }
2695
+ upsertProfile(id, patch, at) {
2696
+ const existing = this.profile(id);
2697
+ const next = {
2698
+ id,
2699
+ email: existing?.email ?? null,
2700
+ traits: existing?.traits ?? {},
2701
+ unsubscribed: existing?.unsubscribed ?? false,
2702
+ channelsOff: existing?.channelsOff ?? [],
2703
+ ...patch,
2704
+ updatedAt: at
2705
+ };
2706
+ this.profiles.insert(id, next);
2707
+ return next;
2708
+ }
2709
+ deliveryId() {
2710
+ return this.ids.next("", 28);
2711
+ }
2712
+ linkId() {
2713
+ return this.ids.next("l", 15);
2714
+ }
2715
+ eventId() {
2716
+ return this.ids.next("01J", 23).toUpperCase();
2717
+ }
2718
+ };
2719
+
2720
+ // src/runtime.ts
2721
+ var REPORTING_WEBHOOK_PATH = "/v1/customer-io/reporting-webhook";
2722
+ var signReporting = (secret, timestampSeconds, body) => hmac("SHA-256", secret, `v0:${timestampSeconds}:${body}`, "hex");
2723
+ var SENDS = ["SendEmail", "SendSms", "SendInboxMessage"];
2724
+ var CDP = ["CdpIdentify", "CdpTrack", "CdpBatch"];
2725
+ var onSends = (rule) => SENDS.map((operationId) => ({ operationId, ...rule }));
2726
+ var onCdp = (rule) => CDP.map((operationId) => ({ operationId, ...rule }));
2727
+ var CUSTOMERIO_PRESETS = {
2728
+ transactional_message_missing: {
2729
+ description: 'Sends answer 400 {meta: {error: "transactional_message_id not found"}} (trigger_name_missing, then fallback)',
2730
+ rules: onSends({
2731
+ status: 400,
2732
+ body: { meta: { error: "transactional_message_id not found" } }
2733
+ })
2734
+ },
2735
+ transactional_404: {
2736
+ description: "Sends answer 404 (also read as trigger_name_missing)",
2737
+ rules: onSends({ status: 404, body: { meta: { error: "not found" } } })
2738
+ },
2739
+ request_timeout_408: {
2740
+ description: "Sends answer 408: ambiguous, the reservation is kept",
2741
+ rules: onSends({ status: 408, body: { meta: { error: "request timeout" } } })
2742
+ },
2743
+ server_error: {
2744
+ description: "Sends answer 500: ambiguous, the reservation is kept",
2745
+ rules: onSends({ status: 500, body: { meta: { error: "internal server error" } } })
2746
+ },
2747
+ accepted_but_500: {
2748
+ description: "Sends queue the message (it lands in the outbox), then answer 500",
2749
+ rules: SENDS.map((operationId) => ({ operationId, effect: "accepted_but_500" }))
2750
+ },
2751
+ rate_limited: {
2752
+ description: "Sends answer 429: definite, safe to re-POST on the next attempt",
2753
+ rules: onSends({
2754
+ status: 429,
2755
+ headers: { "retry-after": "1" },
2756
+ body: { meta: { error: "rate limit exceeded" } }
2757
+ })
2758
+ },
2759
+ invalid_app_key: {
2760
+ description: "App API calls answer 401",
2761
+ rules: [
2762
+ ...onSends({ status: 401, body: { meta: { error: "Unauthorized request" } } }),
2763
+ {
2764
+ pathPrefix: "/v1/transactional",
2765
+ status: 401,
2766
+ body: { meta: { error: "Unauthorized request" } }
2767
+ }
2768
+ ]
2769
+ },
2770
+ send_drop: {
2771
+ description: "Sends drop the connection mid-request: ambiguous (not ECONNREFUSED)",
2772
+ rules: SENDS.map((operationId) => ({ operationId, drop: true }))
2773
+ },
2774
+ cdp_unavailable: {
2775
+ description: "CDP calls answer 503 (the SDK retries, then fails the callback)",
2776
+ rules: onCdp({ status: 503, body: { error: "Service Unavailable" } })
2777
+ },
2778
+ cdp_bad_request: {
2779
+ description: "CDP calls answer 400 (the SDK does not retry; the callback fails)",
2780
+ rules: onCdp({ status: 400, body: { error: "Bad Request" } })
2781
+ },
2782
+ cdp_slow: {
2783
+ description: "CDP calls take 15 s (our 10 s delivery timeout fires first)",
2784
+ rules: onCdp({ latencyMs: 15e3 })
2785
+ },
2786
+ transactional_list_unavailable: {
2787
+ description: "GET /v1/transactional answers 503 (the trigger-name validator records an error)",
2788
+ rules: [
2789
+ {
2790
+ operationId: "ListTransactionalMessages",
2791
+ status: 503,
2792
+ body: { meta: { error: "service unavailable" } }
2793
+ }
2794
+ ]
2795
+ },
2796
+ omit_trigger_names: {
2797
+ description: "GET /v1/transactional lists messages without trigger_name (the validator reads each by id)",
2798
+ rules: [{ operationId: "ListTransactionalMessages", effect: "omit_trigger_names" }]
2799
+ },
2800
+ webhook_duplicate: {
2801
+ description: "The next reporting event is delivered twice (same event_id)",
2802
+ webhook: { mode: "duplicate" }
2803
+ },
2804
+ webhook_drop: {
2805
+ description: "The next reporting event is never delivered",
2806
+ webhook: { mode: "drop" }
2807
+ }
2808
+ };
2809
+ var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2810
+ var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
2811
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2812
+ var adminRoutes = (runtime) => ({
2813
+ ...outboxAdminRoutes(
2814
+ runtime,
2815
+ (api) => api.state.deliveries,
2816
+ (params) => {
2817
+ const channel = params.get("channel");
2818
+ const message = params.get("transactional_message_id");
2819
+ const userId = params.get("userId");
2820
+ if (channel === null && message === null && userId === null) return void 0;
2821
+ return (item) => (channel === null || item.channel === channel) && (message === null || item.transactionalMessageId === message) && (userId === null || item.identifiers.id === userId);
2822
+ }
2823
+ ),
2824
+ "GET /cdp/events": ({ url, namespace }) => {
2825
+ const userId = url.searchParams.get("userId");
2826
+ const type = url.searchParams.get("type");
2827
+ const event = url.searchParams.get("event");
2828
+ return json4(200, {
2829
+ events: runtime.instance(namespace).state.cdp.list({
2830
+ order: "oldest",
2831
+ where: (e) => (userId === null || e.userId === userId) && (type === null || e.type === type) && (event === null || e.event === event)
2832
+ }).map((row) => row.value)
2833
+ });
2834
+ },
2835
+ "GET /profiles": ({ namespace }) => json4(200, { profiles: runtime.instance(namespace).profiles() }),
2836
+ "GET /profiles/:id": ({ params, namespace }) => {
2837
+ const profile = runtime.instance(namespace).state.profile(params.id);
2838
+ return profile ? json4(200, profile) : adminError3(404, `no profile ${params.id}`);
2839
+ },
2840
+ "POST /reporting-events": ({ body, namespace }) => {
2841
+ if (!isRecord4(body) || typeof body.metric !== "string") {
2842
+ return adminError3(
2843
+ 400,
2844
+ 'expected {"metric": "unsubscribed"|"subscribed"|"spammed"|"cio_subscription_preferences_changed"|\u2026, "userId"?, "email"?, "deliveryId"?, "objectType"?, "preferences"?}'
2845
+ );
2846
+ }
2847
+ const text = (key) => typeof body[key] === "string" ? body[key] : void 0;
2848
+ const input = { metric: body.metric };
2849
+ for (const key of ["objectType", "userId", "email", "deliveryId", "href", "linkId"]) {
2850
+ const value = text(key);
2851
+ if (value !== void 0) input[key] = value;
2852
+ }
2853
+ if (isRecord4(body.preferences))
2854
+ input.preferences = body.preferences;
2855
+ const event = runtime.instance(namespace).report(input);
2856
+ return typeof event === "string" ? adminError3(404, event) : json4(201, event);
2857
+ },
2858
+ "GET /transactional": ({ namespace }) => json4(200, { messages: runtime.instance(namespace).state.catalog() }),
2859
+ "PUT /transactional": ({ body, namespace }) => {
2860
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.messages : void 0;
2861
+ if (!Array.isArray(list)) return adminError3(400, "expected [{id, name, trigger_name, \u2026}]");
2862
+ const state = runtime.instance(namespace).state;
2863
+ for (const row of state.catalog()) state.messages.delete(String(row.id));
2864
+ for (const [index, raw] of list.entries()) {
2865
+ if (!isRecord4(raw) || typeof raw.trigger_name !== "string") {
2866
+ return adminError3(400, `messages[${index}]: trigger_name is required`);
2867
+ }
2868
+ const id = typeof raw.id === "number" ? raw.id : index + 1;
2869
+ state.messages.insert(String(id), {
2870
+ id,
2871
+ name: typeof raw.name === "string" ? raw.name : raw.trigger_name,
2872
+ trigger_name: raw.trigger_name,
2873
+ description: typeof raw.description === "string" ? raw.description : "",
2874
+ send_to_unsubscribed: raw.send_to_unsubscribed !== false,
2875
+ link_tracking: raw.link_tracking === true,
2876
+ open_tracking: raw.open_tracking !== false,
2877
+ hide_message_body: raw.hide_message_body === true,
2878
+ queue_drafts: false,
2879
+ created_at: 1735689600,
2880
+ updated_at: 1735689600
2881
+ });
2882
+ }
2883
+ return json4(200, { messages: state.catalog() });
2884
+ },
2885
+ "GET /settings": ({ namespace }) => json4(200, runtime.instance(namespace).state.current()),
2886
+ "PUT /settings": ({ body, namespace }) => {
2887
+ if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
2888
+ const patch = {};
2889
+ if (typeof body.strictMessages === "boolean") patch.strictMessages = body.strictMessages;
2890
+ if (typeof body.trackingBase === "string") patch.trackingBase = body.trackingBase;
2891
+ if (Array.isArray(body.keys)) patch.keys = body.keys.map(String);
2892
+ return json4(200, runtime.instance(namespace).state.update(patch));
2893
+ }
2894
+ });
2895
+ var createRuntime2 = (options = {}) => {
2896
+ const { retryDelaysMs, fetch: send, ...endpoint } = options.webhooks ?? { url: "" };
2897
+ const hub = createWebhookHub({
2898
+ signer: signers.custom(
2899
+ async ({ body, timestampSeconds, secret }) => secret ? {
2900
+ "x-cio-timestamp": String(timestampSeconds),
2901
+ "x-cio-signature": await signReporting(secret, timestampSeconds, body)
2902
+ } : {}
2903
+ ),
2904
+ ...retryDelaysMs ? { retryDelaysMs } : {},
2905
+ ...send ? { fetch: send } : {},
2906
+ ...options.wallClock ? { now: options.wallClock } : {},
2907
+ endpoints: options.webhooks ? [endpoint] : []
2908
+ });
2909
+ const runtime = createRuntime({
2910
+ name: CUSTOMERIO_NAMESPACE,
2911
+ document,
2912
+ ...options.sqlite ? { sqlite: options.sqlite } : {},
2913
+ ...options.clock ? { clock: options.clock } : {},
2914
+ ...options.seed !== void 0 ? { seed: options.seed } : {},
2915
+ ...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
2916
+ ...options.onLog ? { onLog: options.onLog } : {},
2917
+ credential: customerIoCredential,
2918
+ presets: CUSTOMERIO_PRESETS,
2919
+ webhooks: hub,
2920
+ create: ({ sqlite, namespace, publicNamespace, clock }) => new CustomerIoAPI({
2921
+ sqlite,
2922
+ namespace,
2923
+ now: clock.now,
2924
+ ...options.wallClock ? { wallClock: options.wallClock } : {},
2925
+ ...options.messages ? { messages: options.messages } : {},
2926
+ ...options.settings ? { settings: options.settings } : {},
2927
+ onReport: (event) => hub.publish({
2928
+ namespace: publicNamespace,
2929
+ type: event.metric,
2930
+ body: event,
2931
+ id: event.event_id
2932
+ })
2933
+ }),
2934
+ describe: () => ({ webhooks: hub.endpoints("default").length > 0 ? "on" : "off" }),
2935
+ admin: adminRoutes
2936
+ });
2937
+ return Object.assign(runtime, { webhooks: hub });
2938
+ };
2939
+
2940
+ // src/index.ts
2941
+ var CUSTOMERIO_NAMESPACE = "customerio";
2942
+ var customerIoCredential = (request) => basicAuth(request)?.username || bearerToken(request);
2943
+ var CDP_OPERATIONS = /* @__PURE__ */ new Set(["CdpIdentify", "CdpTrack", "CdpBatch"]);
2944
+ var APP_OPERATIONS = /* @__PURE__ */ new Set([
2945
+ "SendEmail",
2946
+ "SendSms",
2947
+ "SendInboxMessage",
2948
+ "ListTransactionalMessages",
2949
+ "GetTransactionalMessage"
2950
+ ]);
2951
+ var clickNotFound = () => new Response("404 page not found", { status: 404, headers: { "content-type": "text/plain" } });
2952
+ var cdpError = (status, error) => jsonRes(status, { error });
2953
+ var appError = (status, error) => jsonRes(status, { meta: { error } });
2954
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2955
+ var URL_PATTERN = /https?:\/\/[^\s"'<>]+/g;
2956
+ var urlsIn = (value, out = []) => {
2957
+ if (typeof value === "string") {
2958
+ for (const url of [...extractLinks(value), ...value.match(URL_PATTERN) ?? []]) {
2959
+ if (/^https?:\/\//.test(url) && !out.includes(url)) out.push(url);
2960
+ }
2961
+ } else if (Array.isArray(value)) {
2962
+ for (const item of value) urlsIn(item, out);
2963
+ } else if (isRecord5(value)) {
2964
+ for (const item of Object.values(value)) urlsIn(item, out);
2965
+ }
2966
+ return out;
2967
+ };
2968
+ var CustomerIoAPI = class {
2969
+ app;
2970
+ sqlite;
2971
+ state;
2972
+ service;
2973
+ now;
2974
+ wallClock;
2975
+ onReport;
2976
+ constructor(options = {}) {
2977
+ const sqlite = bootSqlite(options.sqlite);
2978
+ const namespace = options.namespace ?? CUSTOMERIO_NAMESPACE;
2979
+ this.now = options.now ?? (() => Date.now());
2980
+ this.wallClock = options.wallClock ?? Date.now;
2981
+ this.onReport = options.onReport;
2982
+ this.state = new CustomerIoState(sqlite, namespace, {
2983
+ messages: options.messages ?? DEFAULT_TRANSACTIONAL_MESSAGES,
2984
+ settings: options.settings ?? {}
2985
+ });
2986
+ const handlers = defineOperations({
2987
+ CdpIdentify: (context) => this.cdp(context, "identify"),
2988
+ CdpTrack: (context) => this.cdp(context, "track"),
2989
+ CdpBatch: (context) => this.cdp(context, "batch"),
2990
+ SendEmail: (context) => this.send(context, "email"),
2991
+ SendSms: (context) => this.send(context, "sms"),
2992
+ SendInboxMessage: (context) => this.send(context, "inbox"),
2993
+ ListTransactionalMessages: (context) => jsonRes(200, {
2994
+ messages: this.state.catalog().map(
2995
+ (m) => faultEffect(context.request, "omit_trigger_names") !== void 0 ? { ...m, trigger_name: void 0 } : m
2996
+ )
2997
+ }),
2998
+ GetTransactionalMessage: (context) => {
2999
+ const message = this.state.message(context.params.transactional_id ?? "");
3000
+ return message ? jsonRes(200, { message }) : appError(404, "not found");
3001
+ },
3002
+ ReportClick: (context) => this.click(context, "post"),
3003
+ FollowClick: (context) => this.click(context, "get")
3004
+ });
3005
+ this.service = createService({
3006
+ document,
3007
+ handlers,
3008
+ sqlite,
3009
+ namespace,
3010
+ now: this.now,
3011
+ notFound: (request) => new URL(request.url).pathname.startsWith("/click") ? clickNotFound() : appError(404, "not found"),
3012
+ onError: (error) => {
3013
+ if (error instanceof HttpError) return error.toResponse();
3014
+ throw error;
3015
+ },
3016
+ before: (context) => {
3017
+ const id = context.operation.operationId;
3018
+ const keys = this.state.current().keys;
3019
+ if (CDP_OPERATIONS.has(id)) {
3020
+ const key = basicAuth(context.request)?.username;
3021
+ if (!key || keys.length > 0 && !keys.includes(key)) {
3022
+ return cdpError(401, "Unauthorized");
3023
+ }
3024
+ }
3025
+ if (APP_OPERATIONS.has(id)) {
3026
+ const key = bearerToken(context.request);
3027
+ if (!key || keys.length > 0 && !keys.includes(key)) {
3028
+ return appError(401, "Unauthorized request");
3029
+ }
3030
+ }
3031
+ return void 0;
3032
+ }
3033
+ });
3034
+ this.app = this.service.app;
3035
+ this.sqlite = this.service.sqlite;
3036
+ }
3037
+ fetch(request) {
3038
+ return this.service.fetch(request);
3039
+ }
3040
+ async reset() {
3041
+ await this.service.reset();
3042
+ this.state.ensureSeeded();
3043
+ }
3044
+ iso() {
3045
+ return new Date(this.now()).toISOString();
3046
+ }
3047
+ // ---------------------------------------------------------------- CDP
3048
+ cdp(context, kind) {
3049
+ if (context.body.kind !== "json" || !isRecord5(context.body.value)) {
3050
+ return cdpError(400, "Invalid JSON body");
3051
+ }
3052
+ const issue = bodyIssues(context)[0];
3053
+ if (issue) return cdpError(400, `${issue.path || "body"}: ${issue.message}`);
3054
+ const body = context.body.value;
3055
+ const items = kind === "batch" ? body.batch : [{ ...body, type: kind }];
3056
+ for (const [index, item] of items.entries()) {
3057
+ const type = item.type;
3058
+ if (type !== "identify" && type !== "track") {
3059
+ return cdpError(400, `batch.${index}.type: must be identify or track`);
3060
+ }
3061
+ if (typeof item.userId !== "string" && typeof item.anonymousId !== "string") {
3062
+ return cdpError(400, "userId or anonymousId is required");
3063
+ }
3064
+ }
3065
+ const ids = [];
3066
+ for (const item of items) ids.push(this.ingest(item));
3067
+ return annotateResponse(jsonRes(200, { success: true }), {
3068
+ ids: { messageIds: ids.join(",") }
3069
+ });
3070
+ }
3071
+ /** Apply one CDP event; a repeated `messageId` is recorded as a duplicate and not re-applied. */
3072
+ ingest(item) {
3073
+ const at = this.iso();
3074
+ const messageId = typeof item.messageId === "string" && item.messageId ? item.messageId : `mb-${this.state.ids.next("m", 20)}`;
3075
+ const duplicate = this.state.cdp.has(messageId);
3076
+ const event = {
3077
+ messageId,
3078
+ type: item.type,
3079
+ userId: typeof item.userId === "string" ? item.userId : null,
3080
+ anonymousId: typeof item.anonymousId === "string" ? item.anonymousId : null,
3081
+ event: typeof item.event === "string" ? item.event : null,
3082
+ traits: isRecord5(item.traits) ? item.traits : {},
3083
+ properties: isRecord5(item.properties) ? item.properties : {},
3084
+ timestamp: typeof item.timestamp === "string" ? item.timestamp : null,
3085
+ receivedAt: at,
3086
+ duplicate
3087
+ };
3088
+ this.state.cdp.insert(duplicate ? `${messageId}#${this.state.cdp.count()}` : messageId, event);
3089
+ if (duplicate || event.type !== "identify") return messageId;
3090
+ const id = event.userId ?? event.anonymousId ?? "";
3091
+ const existing = this.state.profile(id);
3092
+ const traits = { ...existing?.traits ?? {}, ...event.traits };
3093
+ this.state.upsertProfile(
3094
+ id,
3095
+ {
3096
+ traits,
3097
+ ...typeof traits.email === "string" ? { email: traits.email } : {},
3098
+ ...typeof event.traits.unsubscribed === "boolean" ? { unsubscribed: event.traits.unsubscribed } : {}
3099
+ },
3100
+ at
3101
+ );
3102
+ return messageId;
3103
+ }
3104
+ // ---------------------------------------------------------------- App API sends
3105
+ send(context, channel) {
3106
+ if (context.body.kind !== "json" || !isRecord5(context.body.value)) {
3107
+ return appError(400, "invalid JSON body");
3108
+ }
3109
+ const issue = bodyIssues(context)[0];
3110
+ if (issue) {
3111
+ const missing = /^missing required property (.+)$/.exec(issue.message);
3112
+ return appError(
3113
+ 400,
3114
+ missing ? `${[issue.path, missing[1]].filter(Boolean).join(".")}: is required` : `${issue.path || "body"}: ${issue.message}`
3115
+ );
3116
+ }
3117
+ const body = context.body.value;
3118
+ const identifiers = body.identifiers;
3119
+ if (!identifiers.id && !identifiers.email && !identifiers.cio_id) {
3120
+ return appError(400, "identifiers: must contain exactly one of id, email or cio_id");
3121
+ }
3122
+ const rawId = String(body.transactional_message_id);
3123
+ const message = this.state.message(rawId);
3124
+ if (!message && this.state.current().strictMessages) {
3125
+ return appError(400, "transactional_message_id not found");
3126
+ }
3127
+ const profile = this.state.profileFor(identifiers);
3128
+ let to = typeof body.to === "string" ? body.to : null;
3129
+ if (channel === "email") to ??= identifiers.email ?? profile?.email ?? null;
3130
+ if (channel === "sms") {
3131
+ const phone = profile?.traits.phone;
3132
+ to ??= typeof phone === "string" ? phone : null;
3133
+ }
3134
+ if (channel === "inbox") to = identifiers.id ?? identifiers.cio_id ?? identifiers.email ?? null;
3135
+ if (!to) {
3136
+ return appError(
3137
+ 400,
3138
+ channel === "email" ? "to: is required when the profile has no email attribute" : "to: is required when the profile has no phone attribute"
3139
+ );
3140
+ }
3141
+ const tracked = body.tracked === true || body.tracked === void 0 && !!message?.link_tracking;
3142
+ const deliveryId = this.state.deliveryId();
3143
+ const messageData = isRecord5(body.message_data) ? body.message_data : {};
3144
+ const retain = body.disable_message_retention !== true;
3145
+ const links = urlsIn([messageData, body.body ?? ""]).map((url) => {
3146
+ if (!tracked) return url;
3147
+ const linkId = this.state.linkId();
3148
+ this.state.links.insert(linkId, { linkId, deliveryId, url });
3149
+ return `${this.state.current().trackingBase.replace(/\/$/, "")}/click/${linkId}`;
3150
+ });
3151
+ const sendToUnsubscribed = body.send_to_unsubscribed === true || body.send_to_unsubscribed === void 0 && !!message?.send_to_unsubscribed;
3152
+ const channelOff = channel !== "inbox" && !!profile?.channelsOff.includes(channel === "sms" ? "sms" : "email");
3153
+ const suppressed = !sendToUnsubscribed && (!!profile?.unsubscribed || channelOff);
3154
+ const attachments = Array.isArray(body.attachments) ? body.attachments.map((a) => a.filename) : isRecord5(body.attachments) ? Object.keys(body.attachments) : [];
3155
+ const queuedAt = Math.floor(this.now() / 1e3);
3156
+ const delivery = {
3157
+ id: deliveryId,
3158
+ to,
3159
+ createdAt: this.iso(),
3160
+ channel,
3161
+ transactionalMessageId: rawId,
3162
+ messageId: message?.id ?? null,
3163
+ identifiers,
3164
+ from: typeof body.from === "string" ? body.from : null,
3165
+ subject: typeof body.subject === "string" ? body.subject : null,
3166
+ messageData: retain ? messageData : null,
3167
+ links: retain ? links : [],
3168
+ tracked,
3169
+ sendToUnsubscribed,
3170
+ disableMessageRetention: !retain,
3171
+ headers: isRecord5(body.headers) ? body.headers : {},
3172
+ attachments,
3173
+ state: suppressed ? "suppressed" : "sent",
3174
+ queuedAt,
3175
+ clicks: 0
3176
+ };
3177
+ this.state.deliveries.record(delivery);
3178
+ const ids = { deliveryId, transactionalMessageId: rawId };
3179
+ if (faultEffect(context.request, "accepted_but_500") !== void 0) {
3180
+ return annotateResponse(appError(500, "internal server error"), { ids });
3181
+ }
3182
+ return annotateResponse(jsonRes(200, { delivery_id: deliveryId, queued_at: queuedAt }), {
3183
+ ids
3184
+ });
3185
+ }
3186
+ // ---------------------------------------------------------------- link tracking
3187
+ click(context, mode) {
3188
+ const link = this.state.links.get(context.params.linkId ?? "");
3189
+ if (!link) return clickNotFound();
3190
+ const delivery = this.state.deliveries.get(link.deliveryId);
3191
+ if (delivery) {
3192
+ this.state.deliveries.update(delivery.id, { ...delivery, clicks: delivery.clicks + 1 });
3193
+ this.report({
3194
+ metric: "clicked",
3195
+ objectType: delivery.channel === "sms" ? "sms" : "email",
3196
+ deliveryId: delivery.id,
3197
+ href: link.url,
3198
+ linkId: link.linkId
3199
+ });
3200
+ }
3201
+ const ids = { linkId: link.linkId, deliveryId: link.deliveryId };
3202
+ if (mode === "get") {
3203
+ return annotateResponse(
3204
+ new Response(null, { status: 302, headers: { location: link.url } }),
3205
+ {
3206
+ ids
3207
+ }
3208
+ );
3209
+ }
3210
+ return annotateResponse(new Response(null, { status: 200 }), { ids });
3211
+ }
3212
+ // ---------------------------------------------------------------- reporting
3213
+ /**
3214
+ * Emit a reporting event and apply what it means to the profile (unsubscribed / subscribed /
3215
+ * spammed / subscription preferences). Returns the event, or a reason it could not be built.
3216
+ */
3217
+ report(input) {
3218
+ const delivery = input.deliveryId ? this.state.deliveries.get(input.deliveryId) : void 0;
3219
+ if (input.deliveryId && !delivery) return `no delivery ${input.deliveryId}`;
3220
+ const userId = input.userId ?? delivery?.identifiers.id ?? null;
3221
+ const profile = userId ? this.state.profile(userId) : input.email ? this.state.profileFor({ email: input.email }) : void 0;
3222
+ const email = input.email ?? delivery?.identifiers.email ?? (delivery?.channel === "email" && typeof delivery.to === "string" ? delivery.to : null) ?? profile?.email ?? null;
3223
+ const at = this.iso();
3224
+ const id = userId ?? profile?.id ?? null;
3225
+ if (id) {
3226
+ if (input.metric === "unsubscribed") this.state.upsertProfile(id, { unsubscribed: true }, at);
3227
+ if (input.metric === "subscribed") {
3228
+ this.state.upsertProfile(id, { unsubscribed: false, channelsOff: [] }, at);
3229
+ }
3230
+ if (input.metric === "spammed") {
3231
+ const off = /* @__PURE__ */ new Set([...profile?.channelsOff ?? [], "email"]);
3232
+ this.state.upsertProfile(id, { channelsOff: [...off] }, at);
3233
+ }
3234
+ if (input.metric === "cio_subscription_preferences_changed" && input.preferences) {
3235
+ const off = new Set(profile?.channelsOff ?? []);
3236
+ for (const [channel, on] of Object.entries(input.preferences.channels ?? {})) {
3237
+ if (channel !== "email" && channel !== "sms") continue;
3238
+ if (on) off.delete(channel);
3239
+ else off.add(channel);
3240
+ }
3241
+ this.state.upsertProfile(id, { channelsOff: [...off] }, at);
3242
+ }
3243
+ }
3244
+ const event = {
3245
+ event_id: this.state.eventId(),
3246
+ object_type: input.objectType ?? (delivery ? delivery.channel : "customer"),
3247
+ metric: input.metric,
3248
+ // Our receiver rejects timestamps more than 5 min ahead of its wall clock.
3249
+ timestamp: Math.floor(Math.min(this.now(), this.wallClock()) / 1e3),
3250
+ data: {
3251
+ identifiers: { id, email, cio_id: null },
3252
+ customer_id: id,
3253
+ email_address: email,
3254
+ ...delivery ? { delivery_id: delivery.id } : {},
3255
+ ...delivery?.messageId ? { transactional_message_id: delivery.messageId } : {},
3256
+ ...input.href ? { href: input.href } : {},
3257
+ ...input.linkId ? { link_id: input.linkId } : {},
3258
+ ...input.preferences ? { content: JSON.stringify(input.preferences) } : {}
3259
+ }
3260
+ };
3261
+ this.onReport?.(event);
3262
+ return event;
3263
+ }
3264
+ profiles() {
3265
+ return this.state.profiles.list({ order: "oldest" }).map((row) => row.value);
3266
+ }
3267
+ };
3268
+
3269
+ export {
3270
+ document,
3271
+ operationIds,
3272
+ supportedOperationIds,
3273
+ DEFAULT_SETTINGS,
3274
+ TRANSACTIONAL_EMAIL_KEYS,
3275
+ DEFAULT_TRANSACTIONAL_MESSAGES,
3276
+ REPORTING_WEBHOOK_PATH,
3277
+ signReporting,
3278
+ CUSTOMERIO_PRESETS,
3279
+ createRuntime2 as createRuntime,
3280
+ CUSTOMERIO_NAMESPACE,
3281
+ customerIoCredential,
3282
+ CustomerIoAPI
3283
+ };
3284
+ //# sourceMappingURL=chunk-UZHOLS6M.js.map