@crvouga/mockingbird-service-odx 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.
- package/CHANGELOG.md +5 -0
- package/README.md +145 -0
- package/dist/chunk-23TC3WDO.js +359 -0
- package/dist/chunk-23TC3WDO.js.map +7 -0
- package/dist/chunk-OYDT3HEE.js +3242 -0
- package/dist/chunk-OYDT3HEE.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +1015 -0
- package/dist/index.js +35 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1306 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +88 -0
|
@@ -0,0 +1,3242 @@
|
|
|
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, message2) => json(status, { error: { type: "mockingbird_admin", message: message2 } });
|
|
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 text2 = await request.text();
|
|
165
|
+
if (text2.trim() === "")
|
|
166
|
+
return void 0;
|
|
167
|
+
return JSON.parse(text2);
|
|
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 createCredentialRegistry = () => {
|
|
393
|
+
const map = /* @__PURE__ */ new Map();
|
|
394
|
+
return {
|
|
395
|
+
set: (credential, namespace) => {
|
|
396
|
+
map.set(credential, namespace);
|
|
397
|
+
},
|
|
398
|
+
get: (credential) => map.get(credential),
|
|
399
|
+
remove: (credential) => map.delete(credential),
|
|
400
|
+
clear: () => map.clear(),
|
|
401
|
+
entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
|
|
402
|
+
};
|
|
403
|
+
};
|
|
404
|
+
var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
|
|
405
|
+
|
|
406
|
+
// ../core/dist/rng.js
|
|
407
|
+
var seedFrom = (value) => {
|
|
408
|
+
let hash = 2166136261;
|
|
409
|
+
for (let i = 0; i < value.length; i++) {
|
|
410
|
+
hash ^= value.charCodeAt(i);
|
|
411
|
+
hash = Math.imul(hash, 16777619);
|
|
412
|
+
}
|
|
413
|
+
return hash >>> 0;
|
|
414
|
+
};
|
|
415
|
+
var createRng = (seed = 0) => {
|
|
416
|
+
const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
|
|
417
|
+
let state = numeric;
|
|
418
|
+
const next = () => {
|
|
419
|
+
state = state + 1831565813 >>> 0;
|
|
420
|
+
let t = state;
|
|
421
|
+
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
422
|
+
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
423
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
424
|
+
};
|
|
425
|
+
return {
|
|
426
|
+
next,
|
|
427
|
+
int: (min, max) => min + Math.floor(next() * (max - min + 1)),
|
|
428
|
+
reset: () => {
|
|
429
|
+
state = numeric;
|
|
430
|
+
},
|
|
431
|
+
state: () => state,
|
|
432
|
+
setState: (next2) => {
|
|
433
|
+
if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
|
|
434
|
+
throw new RangeError("rng state must be an unsigned 32-bit integer");
|
|
435
|
+
}
|
|
436
|
+
state = next2 >>> 0;
|
|
437
|
+
},
|
|
438
|
+
seed: numeric
|
|
439
|
+
};
|
|
440
|
+
};
|
|
441
|
+
|
|
442
|
+
// ../core/dist/faults.js
|
|
443
|
+
var matches = (rule, candidate) => {
|
|
444
|
+
if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
|
|
445
|
+
return false;
|
|
446
|
+
}
|
|
447
|
+
if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
|
|
448
|
+
return false;
|
|
449
|
+
if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
|
|
450
|
+
return false;
|
|
451
|
+
}
|
|
452
|
+
if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
|
|
453
|
+
return false;
|
|
454
|
+
return true;
|
|
455
|
+
};
|
|
456
|
+
var faultResponse = (rule) => {
|
|
457
|
+
const status = rule.status ?? 500;
|
|
458
|
+
const headers = { "content-type": "application/json", ...rule.headers };
|
|
459
|
+
if (typeof rule.body === "string")
|
|
460
|
+
return new Response(rule.body, { status, headers });
|
|
461
|
+
if (rule.body === null)
|
|
462
|
+
return new Response(null, { status, headers: rule.headers ?? {} });
|
|
463
|
+
const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
|
|
464
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
465
|
+
};
|
|
466
|
+
var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
|
|
467
|
+
const entries = [];
|
|
468
|
+
return {
|
|
469
|
+
add(rule) {
|
|
470
|
+
const existing = entries.findIndex((e) => e.rule.id === rule.id);
|
|
471
|
+
const entry = { rule, remaining: rule.count ?? null, hits: 0 };
|
|
472
|
+
if (existing >= 0)
|
|
473
|
+
entries[existing] = entry;
|
|
474
|
+
else
|
|
475
|
+
entries.push(entry);
|
|
476
|
+
return rule;
|
|
477
|
+
},
|
|
478
|
+
list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
|
|
479
|
+
remove(id) {
|
|
480
|
+
const index = entries.findIndex((e) => e.rule.id === id);
|
|
481
|
+
if (index < 0)
|
|
482
|
+
return false;
|
|
483
|
+
entries.splice(index, 1);
|
|
484
|
+
return true;
|
|
485
|
+
},
|
|
486
|
+
clear() {
|
|
487
|
+
entries.length = 0;
|
|
488
|
+
},
|
|
489
|
+
async take(candidate) {
|
|
490
|
+
const hits = [];
|
|
491
|
+
for (const entry of entries) {
|
|
492
|
+
if (entry.remaining === 0)
|
|
493
|
+
continue;
|
|
494
|
+
if (!matches(entry.rule, candidate))
|
|
495
|
+
continue;
|
|
496
|
+
const rate = entry.rule.rate ?? 1;
|
|
497
|
+
if (rng.next() >= rate)
|
|
498
|
+
continue;
|
|
499
|
+
entry.hits++;
|
|
500
|
+
if (entry.remaining !== null)
|
|
501
|
+
entry.remaining--;
|
|
502
|
+
const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
|
|
503
|
+
if (delay !== void 0 && delay > 0) {
|
|
504
|
+
await sleep(delay);
|
|
505
|
+
}
|
|
506
|
+
const hit = { id: entry.rule.id };
|
|
507
|
+
if (entry.rule.effect !== void 0) {
|
|
508
|
+
hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
|
|
509
|
+
}
|
|
510
|
+
if (entry.rule.drop === true)
|
|
511
|
+
hit.drop = true;
|
|
512
|
+
else if (entry.rule.status !== void 0)
|
|
513
|
+
hit.response = faultResponse(entry.rule);
|
|
514
|
+
hits.push(hit);
|
|
515
|
+
if (hit.drop || hit.response)
|
|
516
|
+
break;
|
|
517
|
+
}
|
|
518
|
+
return hits;
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
// ../../openapi/core/dist/refs.js
|
|
524
|
+
var OpenAPIReferenceError = class extends Error {
|
|
525
|
+
ref;
|
|
526
|
+
constructor(ref) {
|
|
527
|
+
super(`unresolvable $ref: ${ref}`);
|
|
528
|
+
this.ref = ref;
|
|
529
|
+
this.name = "OpenAPIReferenceError";
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
533
|
+
var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
|
|
534
|
+
var resolveRef = (document2, ref) => {
|
|
535
|
+
if (!ref.startsWith("#/"))
|
|
536
|
+
throw new OpenAPIReferenceError(ref);
|
|
537
|
+
let cursor = document2;
|
|
538
|
+
for (const raw of ref.slice(2).split("/")) {
|
|
539
|
+
const segment = unescapePointer(raw);
|
|
540
|
+
if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
|
|
541
|
+
throw new OpenAPIReferenceError(ref);
|
|
542
|
+
}
|
|
543
|
+
cursor = cursor[segment];
|
|
544
|
+
}
|
|
545
|
+
if (cursor === void 0)
|
|
546
|
+
throw new OpenAPIReferenceError(ref);
|
|
547
|
+
return cursor;
|
|
548
|
+
};
|
|
549
|
+
var deref = (document2, value) => {
|
|
550
|
+
let current = value;
|
|
551
|
+
const seen = /* @__PURE__ */ new Set();
|
|
552
|
+
while (isReference(current)) {
|
|
553
|
+
if (seen.has(current.$ref))
|
|
554
|
+
throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
|
|
555
|
+
seen.add(current.$ref);
|
|
556
|
+
current = resolveRef(document2, current.$ref);
|
|
557
|
+
}
|
|
558
|
+
return current;
|
|
559
|
+
};
|
|
560
|
+
|
|
561
|
+
// ../../openapi/core/dist/types.js
|
|
562
|
+
var HTTP_METHODS = [
|
|
563
|
+
"get",
|
|
564
|
+
"put",
|
|
565
|
+
"post",
|
|
566
|
+
"delete",
|
|
567
|
+
"options",
|
|
568
|
+
"head",
|
|
569
|
+
"patch",
|
|
570
|
+
"trace"
|
|
571
|
+
];
|
|
572
|
+
|
|
573
|
+
// ../../openapi/core/dist/document.js
|
|
574
|
+
var mergeParameters = (document2, item, own) => {
|
|
575
|
+
const merged = /* @__PURE__ */ new Map();
|
|
576
|
+
for (const raw of item.parameters ?? []) {
|
|
577
|
+
const parameter = deref(document2, raw);
|
|
578
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
579
|
+
}
|
|
580
|
+
for (const raw of own ?? []) {
|
|
581
|
+
const parameter = deref(document2, raw);
|
|
582
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
583
|
+
}
|
|
584
|
+
return [...merged.values()];
|
|
585
|
+
};
|
|
586
|
+
var listOperations = (document2) => {
|
|
587
|
+
const operations = [];
|
|
588
|
+
for (const [path, item] of Object.entries(document2.paths)) {
|
|
589
|
+
for (const method of HTTP_METHODS) {
|
|
590
|
+
const operation = item[method];
|
|
591
|
+
if (operation?.operationId === void 0)
|
|
592
|
+
continue;
|
|
593
|
+
const responses = {};
|
|
594
|
+
for (const [status, response] of Object.entries(operation.responses)) {
|
|
595
|
+
responses[status] = deref(document2, response);
|
|
596
|
+
}
|
|
597
|
+
operations.push({
|
|
598
|
+
operationId: operation.operationId,
|
|
599
|
+
method,
|
|
600
|
+
path,
|
|
601
|
+
operation,
|
|
602
|
+
parameters: mergeParameters(document2, item, operation.parameters),
|
|
603
|
+
requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
|
|
604
|
+
responses
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
return operations;
|
|
609
|
+
};
|
|
610
|
+
|
|
611
|
+
// ../../http/codec/dist/form.js
|
|
612
|
+
var parsePath = (rawKey) => {
|
|
613
|
+
const open = rawKey.indexOf("[");
|
|
614
|
+
if (open === -1)
|
|
615
|
+
return [rawKey];
|
|
616
|
+
const path = [rawKey.slice(0, open)];
|
|
617
|
+
const rest = rawKey.slice(open);
|
|
618
|
+
const pattern = /\[([^\]]*)\]/g;
|
|
619
|
+
let match = pattern.exec(rest);
|
|
620
|
+
let consumed = 0;
|
|
621
|
+
while (match !== null) {
|
|
622
|
+
if (match.index !== consumed)
|
|
623
|
+
return [rawKey];
|
|
624
|
+
path.push(match[1] ?? "");
|
|
625
|
+
consumed = match.index + match[0].length;
|
|
626
|
+
match = pattern.exec(rest);
|
|
627
|
+
}
|
|
628
|
+
if (consumed !== rest.length)
|
|
629
|
+
return [rawKey];
|
|
630
|
+
return path;
|
|
631
|
+
};
|
|
632
|
+
var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
|
|
633
|
+
var put = (target, key, value) => {
|
|
634
|
+
if (key === "__proto__") {
|
|
635
|
+
Object.defineProperty(target, key, {
|
|
636
|
+
value,
|
|
637
|
+
enumerable: true,
|
|
638
|
+
writable: true,
|
|
639
|
+
configurable: true
|
|
640
|
+
});
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
;
|
|
644
|
+
target[key] = value;
|
|
645
|
+
};
|
|
646
|
+
var assign = (target, path, value) => {
|
|
647
|
+
let cursor = target;
|
|
648
|
+
for (let i = 0; i < path.length; i++) {
|
|
649
|
+
const segment = path[i];
|
|
650
|
+
const last = i === path.length - 1;
|
|
651
|
+
if (Array.isArray(cursor)) {
|
|
652
|
+
const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
|
|
653
|
+
if (index === void 0)
|
|
654
|
+
return;
|
|
655
|
+
if (last) {
|
|
656
|
+
put(cursor, index, value);
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
|
|
660
|
+
if (next === void 0 || typeof next === "string") {
|
|
661
|
+
const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
|
|
662
|
+
put(cursor, index, created);
|
|
663
|
+
cursor = created;
|
|
664
|
+
} else {
|
|
665
|
+
cursor = next;
|
|
666
|
+
}
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
if (typeof cursor === "string")
|
|
670
|
+
return;
|
|
671
|
+
if (last) {
|
|
672
|
+
put(cursor, segment, value);
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
const nextSegment = path[i + 1];
|
|
676
|
+
const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
|
|
677
|
+
if (existing === void 0 || typeof existing === "string") {
|
|
678
|
+
const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
|
|
679
|
+
put(cursor, segment, created);
|
|
680
|
+
cursor = created;
|
|
681
|
+
} else {
|
|
682
|
+
cursor = existing;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
var decodeFormPairs = (pairs) => {
|
|
687
|
+
const out = {};
|
|
688
|
+
for (const [rawKey, value] of pairs)
|
|
689
|
+
assign(out, parsePath(rawKey), value);
|
|
690
|
+
return densify(out);
|
|
691
|
+
};
|
|
692
|
+
var densify = (value) => {
|
|
693
|
+
if (typeof value === "string")
|
|
694
|
+
return value;
|
|
695
|
+
if (Array.isArray(value))
|
|
696
|
+
return value.filter((item) => item !== void 0).map(densify);
|
|
697
|
+
const out = {};
|
|
698
|
+
for (const [key, item] of Object.entries(value))
|
|
699
|
+
put(out, key, densify(item));
|
|
700
|
+
return out;
|
|
701
|
+
};
|
|
702
|
+
var decodeForm = (text2) => {
|
|
703
|
+
const source = text2.startsWith("?") ? text2.slice(1) : text2;
|
|
704
|
+
return decodeFormPairs(new URLSearchParams(source).entries());
|
|
705
|
+
};
|
|
706
|
+
|
|
707
|
+
// ../../http/codec/dist/content.js
|
|
708
|
+
var JSON_MEDIA_TYPE = "application/json";
|
|
709
|
+
var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
|
|
710
|
+
var mediaTypeOf = (contentType) => {
|
|
711
|
+
if (!contentType)
|
|
712
|
+
return void 0;
|
|
713
|
+
const essence = contentType.split(";")[0]?.trim().toLowerCase();
|
|
714
|
+
return essence ? essence : void 0;
|
|
715
|
+
};
|
|
716
|
+
var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
|
|
717
|
+
var utf8 = new TextDecoder("utf-8", { fatal: false });
|
|
718
|
+
var decodeBody = (contentType, bytes) => {
|
|
719
|
+
if (bytes.byteLength === 0)
|
|
720
|
+
return { kind: "empty" };
|
|
721
|
+
const mediaType = mediaTypeOf(contentType);
|
|
722
|
+
if (mediaType === void 0)
|
|
723
|
+
return { kind: "bytes", value: bytes };
|
|
724
|
+
if (isJsonMediaType(mediaType)) {
|
|
725
|
+
const text2 = utf8.decode(bytes);
|
|
726
|
+
try {
|
|
727
|
+
return { kind: "json", value: JSON.parse(text2) };
|
|
728
|
+
} catch (error) {
|
|
729
|
+
return {
|
|
730
|
+
kind: "invalid",
|
|
731
|
+
mediaType,
|
|
732
|
+
text: text2,
|
|
733
|
+
error: error instanceof Error ? error.message : String(error)
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
if (mediaType === FORM_MEDIA_TYPE) {
|
|
738
|
+
return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
|
|
739
|
+
}
|
|
740
|
+
if (mediaType.startsWith("text/"))
|
|
741
|
+
return { kind: "text", value: utf8.decode(bytes) };
|
|
742
|
+
return { kind: "bytes", value: bytes };
|
|
743
|
+
};
|
|
744
|
+
var readBody = async (message2) => {
|
|
745
|
+
const bytes = new Uint8Array(await message2.arrayBuffer());
|
|
746
|
+
return decodeBody(message2.headers.get("content-type"), bytes);
|
|
747
|
+
};
|
|
748
|
+
|
|
749
|
+
// ../core/dist/http.js
|
|
750
|
+
var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
|
|
751
|
+
status,
|
|
752
|
+
headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
|
|
753
|
+
});
|
|
754
|
+
|
|
755
|
+
// ../core/dist/ids.js
|
|
756
|
+
var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
757
|
+
var mix = (input) => {
|
|
758
|
+
let hash = 2166136261;
|
|
759
|
+
for (let i = 0; i < input.length; i++) {
|
|
760
|
+
hash ^= input.charCodeAt(i);
|
|
761
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
762
|
+
}
|
|
763
|
+
hash ^= hash >>> 16;
|
|
764
|
+
hash = Math.imul(hash, 2246822507) >>> 0;
|
|
765
|
+
hash ^= hash >>> 13;
|
|
766
|
+
return hash >>> 0;
|
|
767
|
+
};
|
|
768
|
+
var opaqueToken = (input, length) => {
|
|
769
|
+
let out = "";
|
|
770
|
+
let round2 = 0;
|
|
771
|
+
while (out.length < length) {
|
|
772
|
+
let hash = mix(`${input}:${round2++}`);
|
|
773
|
+
for (let i = 0; i < 5 && out.length < length; i++) {
|
|
774
|
+
out += ALPHABET.charAt(hash % ALPHABET.length);
|
|
775
|
+
hash = Math.floor(hash / ALPHABET.length);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
return out;
|
|
779
|
+
};
|
|
780
|
+
|
|
781
|
+
// ../core/dist/journal.js
|
|
782
|
+
var DEFAULT_JOURNAL_SIZE = 1e3;
|
|
783
|
+
var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
|
|
784
|
+
const capacity = Math.max(0, Math.floor(size));
|
|
785
|
+
const rings = /* @__PURE__ */ new Map();
|
|
786
|
+
let sequence = 0;
|
|
787
|
+
const order = /* @__PURE__ */ new WeakMap();
|
|
788
|
+
const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
|
|
789
|
+
return {
|
|
790
|
+
size: capacity,
|
|
791
|
+
record(entry) {
|
|
792
|
+
if (capacity === 0)
|
|
793
|
+
return;
|
|
794
|
+
order.set(entry, sequence++);
|
|
795
|
+
let ring = rings.get(entry.namespace);
|
|
796
|
+
if (!ring) {
|
|
797
|
+
ring = { entries: [], next: 0 };
|
|
798
|
+
rings.set(entry.namespace, ring);
|
|
799
|
+
}
|
|
800
|
+
if (ring.entries.length < capacity)
|
|
801
|
+
ring.entries.push(entry);
|
|
802
|
+
else {
|
|
803
|
+
ring.entries[ring.next] = entry;
|
|
804
|
+
ring.next = (ring.next + 1) % capacity;
|
|
805
|
+
}
|
|
806
|
+
},
|
|
807
|
+
list(query = {}) {
|
|
808
|
+
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));
|
|
809
|
+
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));
|
|
810
|
+
return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
|
|
811
|
+
},
|
|
812
|
+
clear(namespace) {
|
|
813
|
+
if (namespace === void 0)
|
|
814
|
+
rings.clear();
|
|
815
|
+
else
|
|
816
|
+
rings.delete(namespace);
|
|
817
|
+
}
|
|
818
|
+
};
|
|
819
|
+
};
|
|
820
|
+
var notes = /* @__PURE__ */ new WeakMap();
|
|
821
|
+
var annotateResponse = (response, extra) => {
|
|
822
|
+
const existing = notes.get(response);
|
|
823
|
+
notes.set(response, {
|
|
824
|
+
...existing,
|
|
825
|
+
...extra,
|
|
826
|
+
...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
|
|
827
|
+
});
|
|
828
|
+
return response;
|
|
829
|
+
};
|
|
830
|
+
var responseNotes = (response) => notes.get(response);
|
|
831
|
+
|
|
832
|
+
// ../core/dist/metrics.js
|
|
833
|
+
var createMetrics = () => {
|
|
834
|
+
let requests = 0;
|
|
835
|
+
let faults = 0;
|
|
836
|
+
let totalDurationMs = 0;
|
|
837
|
+
const byOperation = /* @__PURE__ */ new Map();
|
|
838
|
+
const unmatched = /* @__PURE__ */ new Map();
|
|
839
|
+
return {
|
|
840
|
+
record(entry) {
|
|
841
|
+
requests++;
|
|
842
|
+
totalDurationMs += entry.durationMs;
|
|
843
|
+
if (entry.faultId !== void 0)
|
|
844
|
+
faults++;
|
|
845
|
+
const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
|
|
846
|
+
byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
|
|
847
|
+
if (entry.unmatched) {
|
|
848
|
+
const route = `${entry.method} ${entry.path}`;
|
|
849
|
+
unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
|
|
850
|
+
}
|
|
851
|
+
},
|
|
852
|
+
report: () => ({
|
|
853
|
+
requests,
|
|
854
|
+
byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
|
|
855
|
+
unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
|
|
856
|
+
const space = route.indexOf(" ");
|
|
857
|
+
return { method: route.slice(0, space), path: route.slice(space + 1), count };
|
|
858
|
+
}),
|
|
859
|
+
faults,
|
|
860
|
+
totalDurationMs
|
|
861
|
+
}),
|
|
862
|
+
reset() {
|
|
863
|
+
requests = 0;
|
|
864
|
+
faults = 0;
|
|
865
|
+
totalDurationMs = 0;
|
|
866
|
+
byOperation.clear();
|
|
867
|
+
unmatched.clear();
|
|
868
|
+
}
|
|
869
|
+
};
|
|
870
|
+
};
|
|
871
|
+
|
|
872
|
+
// ../../core/dist/timeline.js
|
|
873
|
+
var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
874
|
+
var Timeline = class {
|
|
875
|
+
maxCheckpoints;
|
|
876
|
+
now;
|
|
877
|
+
makeId;
|
|
878
|
+
nodes = /* @__PURE__ */ new Map();
|
|
879
|
+
heads = /* @__PURE__ */ new Map();
|
|
880
|
+
/** Unreferenced nodes in the exact order they became collectible. */
|
|
881
|
+
evictable = /* @__PURE__ */ new Set();
|
|
882
|
+
/** Branch heads plus explicit retainers. Absent means zero. */
|
|
883
|
+
references = /* @__PURE__ */ new Map();
|
|
884
|
+
explicitPins = /* @__PURE__ */ new Map();
|
|
885
|
+
sequence = 0;
|
|
886
|
+
constructor(options = {}) {
|
|
887
|
+
const max = options.maxCheckpoints ?? 1e3;
|
|
888
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
889
|
+
throw new RangeError("maxCheckpoints must be a positive integer");
|
|
890
|
+
this.maxCheckpoints = max;
|
|
891
|
+
this.now = options.now ?? (() => this.sequence);
|
|
892
|
+
this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
|
|
893
|
+
}
|
|
894
|
+
/** Capture a new immutable value and move `branch` to it. */
|
|
895
|
+
commit(value, options = {}) {
|
|
896
|
+
const branch = options.branch ?? "main";
|
|
897
|
+
this.assertBranch(branch);
|
|
898
|
+
const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
|
|
899
|
+
if (parent !== null && !this.nodes.has(parent))
|
|
900
|
+
throw new RangeError(`no checkpoint ${parent}`);
|
|
901
|
+
const id = this.makeId(++this.sequence);
|
|
902
|
+
if (this.nodes.has(id))
|
|
903
|
+
throw new RangeError(`duplicate checkpoint id ${id}`);
|
|
904
|
+
const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
|
|
905
|
+
this.nodes.set(id, checkpoint);
|
|
906
|
+
this.moveHead(branch, id);
|
|
907
|
+
this.collect(this.maxCheckpoints);
|
|
908
|
+
return checkpoint;
|
|
909
|
+
}
|
|
910
|
+
/** Create a branch pointer without copying its checkpoint value. */
|
|
911
|
+
fork(branch, options = {}) {
|
|
912
|
+
this.assertBranch(branch);
|
|
913
|
+
if (this.heads.has(branch))
|
|
914
|
+
throw new RangeError(`branch already exists: ${branch}`);
|
|
915
|
+
const from = options.from ?? this.heads.get("main");
|
|
916
|
+
if (from === void 0)
|
|
917
|
+
return void 0;
|
|
918
|
+
const checkpoint = this.get(from);
|
|
919
|
+
this.moveHead(branch, checkpoint.id);
|
|
920
|
+
return checkpoint;
|
|
921
|
+
}
|
|
922
|
+
/** Move a branch pointer to an existing checkpoint. */
|
|
923
|
+
checkout(branch, id) {
|
|
924
|
+
this.assertBranch(branch);
|
|
925
|
+
const checkpoint = this.get(id);
|
|
926
|
+
this.moveHead(branch, checkpoint.id);
|
|
927
|
+
return checkpoint;
|
|
928
|
+
}
|
|
929
|
+
get(id) {
|
|
930
|
+
const checkpoint = this.nodes.get(id);
|
|
931
|
+
if (!checkpoint)
|
|
932
|
+
throw new RangeError(`no checkpoint ${id}`);
|
|
933
|
+
return checkpoint;
|
|
934
|
+
}
|
|
935
|
+
head(branch = "main") {
|
|
936
|
+
const id = this.heads.get(branch);
|
|
937
|
+
return id === void 0 ? void 0 : this.get(id);
|
|
938
|
+
}
|
|
939
|
+
hasBranch(branch) {
|
|
940
|
+
return this.heads.has(branch);
|
|
941
|
+
}
|
|
942
|
+
branches() {
|
|
943
|
+
return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
|
|
944
|
+
}
|
|
945
|
+
checkpoints() {
|
|
946
|
+
return [...this.nodes.values()];
|
|
947
|
+
}
|
|
948
|
+
/** Number of retained checkpoints without allocating an array. */
|
|
949
|
+
get size() {
|
|
950
|
+
return this.nodes.size;
|
|
951
|
+
}
|
|
952
|
+
/** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
|
|
953
|
+
retain(id) {
|
|
954
|
+
const checkpoint = this.get(id);
|
|
955
|
+
this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
|
|
956
|
+
this.addReference(id);
|
|
957
|
+
return checkpoint;
|
|
958
|
+
}
|
|
959
|
+
/** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
|
|
960
|
+
release(id) {
|
|
961
|
+
if (!this.nodes.has(id))
|
|
962
|
+
return false;
|
|
963
|
+
const pins = this.explicitPins.get(id) ?? 0;
|
|
964
|
+
if (pins === 0)
|
|
965
|
+
return false;
|
|
966
|
+
if (pins === 1)
|
|
967
|
+
this.explicitPins.delete(id);
|
|
968
|
+
else
|
|
969
|
+
this.explicitPins.set(id, pins - 1);
|
|
970
|
+
this.removeReference(id);
|
|
971
|
+
this.collect(this.maxCheckpoints);
|
|
972
|
+
return true;
|
|
973
|
+
}
|
|
974
|
+
deleteBranch(branch) {
|
|
975
|
+
if (branch === "main")
|
|
976
|
+
throw new RangeError("cannot delete main branch");
|
|
977
|
+
const previous = this.heads.get(branch);
|
|
978
|
+
const deleted = this.heads.delete(branch);
|
|
979
|
+
if (previous !== void 0)
|
|
980
|
+
this.removeReference(previous);
|
|
981
|
+
this.collect(this.maxCheckpoints);
|
|
982
|
+
return deleted;
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
|
|
986
|
+
* commits never scan pinned nodes or the retained history. Parents are metadata rather than a
|
|
987
|
+
* storage dependency, so a retained node remains usable after pruning.
|
|
988
|
+
*/
|
|
989
|
+
gc(max = this.maxCheckpoints) {
|
|
990
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
991
|
+
throw new RangeError("max must be a positive integer");
|
|
992
|
+
const removed = [];
|
|
993
|
+
this.collect(max, removed);
|
|
994
|
+
return removed;
|
|
995
|
+
}
|
|
996
|
+
collect(max, removed) {
|
|
997
|
+
while (this.nodes.size > max && this.evictable.size > 0) {
|
|
998
|
+
const id = this.evictable.values().next().value;
|
|
999
|
+
this.evictable.delete(id);
|
|
1000
|
+
this.nodes.delete(id);
|
|
1001
|
+
removed?.push(id);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
moveHead(branch, id) {
|
|
1005
|
+
const previous = this.heads.get(branch);
|
|
1006
|
+
if (previous === id)
|
|
1007
|
+
return;
|
|
1008
|
+
if (previous !== void 0)
|
|
1009
|
+
this.removeReference(previous);
|
|
1010
|
+
this.heads.set(branch, id);
|
|
1011
|
+
this.addReference(id);
|
|
1012
|
+
}
|
|
1013
|
+
addReference(id) {
|
|
1014
|
+
this.references.set(id, (this.references.get(id) ?? 0) + 1);
|
|
1015
|
+
this.evictable.delete(id);
|
|
1016
|
+
}
|
|
1017
|
+
removeReference(id) {
|
|
1018
|
+
const next = (this.references.get(id) ?? 0) - 1;
|
|
1019
|
+
if (next > 0)
|
|
1020
|
+
this.references.set(id, next);
|
|
1021
|
+
else {
|
|
1022
|
+
this.references.delete(id);
|
|
1023
|
+
if (this.nodes.has(id))
|
|
1024
|
+
this.evictable.add(id);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
assertBranch(branch) {
|
|
1028
|
+
if (!BRANCH_PATTERN.test(branch))
|
|
1029
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
|
|
1030
|
+
}
|
|
1031
|
+
};
|
|
1032
|
+
|
|
1033
|
+
// ../../sqlite/dist/default.js
|
|
1034
|
+
import { Database } from "@crvouga/mockingbird-service-sqlite";
|
|
1035
|
+
var createDefaultSqlite = () => new Database();
|
|
1036
|
+
var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
|
|
1037
|
+
|
|
1038
|
+
// ../../sqlite/dist/migrate.js
|
|
1039
|
+
var ensureMigrationsTable = (sqlite) => {
|
|
1040
|
+
sqlite.exec(`
|
|
1041
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
1042
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
1043
|
+
applied_at INTEGER NOT NULL
|
|
1044
|
+
)
|
|
1045
|
+
`);
|
|
1046
|
+
};
|
|
1047
|
+
var migrate = (sqlite, migrations) => {
|
|
1048
|
+
ensureMigrationsTable(sqlite);
|
|
1049
|
+
const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
|
|
1050
|
+
const pending = migrations.filter((migration) => !applied.has(migration.id));
|
|
1051
|
+
if (pending.length === 0)
|
|
1052
|
+
return;
|
|
1053
|
+
const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
|
|
1054
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1055
|
+
sqlite.transaction(() => {
|
|
1056
|
+
for (const migration of pending) {
|
|
1057
|
+
sqlite.exec(migration.sql);
|
|
1058
|
+
insert.run(migration.id, now);
|
|
1059
|
+
}
|
|
1060
|
+
});
|
|
1061
|
+
};
|
|
1062
|
+
|
|
1063
|
+
// ../../sqlite/dist/schema.js
|
|
1064
|
+
var CORE_MIGRATIONS = [
|
|
1065
|
+
{
|
|
1066
|
+
id: "20260322_core_records_sequences",
|
|
1067
|
+
sql: `
|
|
1068
|
+
CREATE TABLE IF NOT EXISTS mockingbird_records (
|
|
1069
|
+
namespace TEXT NOT NULL,
|
|
1070
|
+
collection TEXT NOT NULL,
|
|
1071
|
+
id TEXT NOT NULL,
|
|
1072
|
+
seq INTEGER NOT NULL,
|
|
1073
|
+
value TEXT NOT NULL,
|
|
1074
|
+
PRIMARY KEY (namespace, collection, id)
|
|
1075
|
+
);
|
|
1076
|
+
CREATE INDEX IF NOT EXISTS mockingbird_records_seq
|
|
1077
|
+
ON mockingbird_records (namespace, collection, seq);
|
|
1078
|
+
CREATE TABLE IF NOT EXISTS mockingbird_sequences (
|
|
1079
|
+
namespace TEXT NOT NULL,
|
|
1080
|
+
name TEXT NOT NULL,
|
|
1081
|
+
kind TEXT NOT NULL,
|
|
1082
|
+
value INTEGER NOT NULL,
|
|
1083
|
+
PRIMARY KEY (namespace, name, kind)
|
|
1084
|
+
);
|
|
1085
|
+
`
|
|
1086
|
+
}
|
|
1087
|
+
];
|
|
1088
|
+
var migrateCore = (sqlite) => {
|
|
1089
|
+
migrate(sqlite, CORE_MIGRATIONS);
|
|
1090
|
+
};
|
|
1091
|
+
var clearNamespace = (sqlite, namespace) => {
|
|
1092
|
+
sqlite.transaction(() => {
|
|
1093
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1094
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1095
|
+
});
|
|
1096
|
+
};
|
|
1097
|
+
|
|
1098
|
+
// ../../openapi/metadata/dist/types.js
|
|
1099
|
+
var EXTENSION_KEYS = {
|
|
1100
|
+
operation: "x-mockingbird",
|
|
1101
|
+
resource: "x-mockingbird-resource",
|
|
1102
|
+
resourceRef: "x-mockingbird-resource-ref",
|
|
1103
|
+
volatile: "x-mockingbird-volatile",
|
|
1104
|
+
scope: "x-mockingbird-scope",
|
|
1105
|
+
unsupported: "x-mockingbird-unsupported",
|
|
1106
|
+
parityHeader: "x-mockingbird-parity-header"
|
|
1107
|
+
};
|
|
1108
|
+
|
|
1109
|
+
// ../../openapi/metadata/dist/read.js
|
|
1110
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1111
|
+
var extensionOf = (holder, key) => holder[key];
|
|
1112
|
+
var operationMetadata = (operation) => {
|
|
1113
|
+
const raw = extensionOf(operation, EXTENSION_KEYS.operation);
|
|
1114
|
+
const ext = isRecord2(raw) ? raw : {};
|
|
1115
|
+
const supported = ext.supported ?? true;
|
|
1116
|
+
const parity = ext.parity ?? {};
|
|
1117
|
+
return {
|
|
1118
|
+
supported,
|
|
1119
|
+
reason: typeof ext.reason === "string" ? ext.reason : void 0,
|
|
1120
|
+
parity: {
|
|
1121
|
+
enabled: supported && (parity.enabled ?? true),
|
|
1122
|
+
safe: parity.safe ?? true,
|
|
1123
|
+
reason: typeof parity.reason === "string" ? parity.reason : void 0
|
|
1124
|
+
}
|
|
1125
|
+
};
|
|
1126
|
+
};
|
|
1127
|
+
|
|
1128
|
+
// ../core/dist/service.js
|
|
1129
|
+
import { Hono } from "hono";
|
|
1130
|
+
var defineOperations = (handlers) => handlers;
|
|
1131
|
+
var OperationRegistryError = class extends Error {
|
|
1132
|
+
problems;
|
|
1133
|
+
constructor(problems) {
|
|
1134
|
+
super(`operation registry is inconsistent:
|
|
1135
|
+
${problems.map((p) => ` - ${p}`).join("\n")}`);
|
|
1136
|
+
this.problems = problems;
|
|
1137
|
+
this.name = "OperationRegistryError";
|
|
1138
|
+
}
|
|
1139
|
+
};
|
|
1140
|
+
var verifyOperations = (document2, handlers) => {
|
|
1141
|
+
const problems = [];
|
|
1142
|
+
const operations = listOperations(document2);
|
|
1143
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1144
|
+
for (const operation of operations) {
|
|
1145
|
+
if (seen.has(operation.operationId))
|
|
1146
|
+
problems.push(`duplicate operationId ${operation.operationId}`);
|
|
1147
|
+
seen.add(operation.operationId);
|
|
1148
|
+
const supported = operationMetadata(operation.operation).supported;
|
|
1149
|
+
const handler = handlers[operation.operationId];
|
|
1150
|
+
if (supported && !handler)
|
|
1151
|
+
problems.push(`supported operation ${operation.operationId} has no handler`);
|
|
1152
|
+
if (!supported && handler)
|
|
1153
|
+
problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
|
|
1154
|
+
}
|
|
1155
|
+
for (const id of Object.keys(handlers)) {
|
|
1156
|
+
if (!seen.has(id))
|
|
1157
|
+
problems.push(`handler ${id} has no OpenAPI operation`);
|
|
1158
|
+
}
|
|
1159
|
+
return problems;
|
|
1160
|
+
};
|
|
1161
|
+
var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
|
|
1162
|
+
var routeOrder = (a, b) => {
|
|
1163
|
+
const sa = a.path.split("/");
|
|
1164
|
+
const sb = b.path.split("/");
|
|
1165
|
+
for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
|
|
1166
|
+
const x = sa[i] ?? "";
|
|
1167
|
+
const y = sb[i] ?? "";
|
|
1168
|
+
const px = x.startsWith("{");
|
|
1169
|
+
const py = y.startsWith("{");
|
|
1170
|
+
if (px !== py)
|
|
1171
|
+
return px ? 1 : -1;
|
|
1172
|
+
if (x !== y)
|
|
1173
|
+
return x < y ? -1 : 1;
|
|
1174
|
+
}
|
|
1175
|
+
return 0;
|
|
1176
|
+
};
|
|
1177
|
+
var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
|
|
1178
|
+
var bootSqlite = (sqlite) => {
|
|
1179
|
+
const client = resolveSqlite(sqlite);
|
|
1180
|
+
migrateCore(client);
|
|
1181
|
+
return client;
|
|
1182
|
+
};
|
|
1183
|
+
var createService = (options) => {
|
|
1184
|
+
const problems = verifyOperations(options.document, options.handlers);
|
|
1185
|
+
if (problems.length > 0)
|
|
1186
|
+
throw new OperationRegistryError(problems);
|
|
1187
|
+
migrateCore(options.sqlite);
|
|
1188
|
+
const now = options.now ?? (() => Date.now());
|
|
1189
|
+
const app = new Hono();
|
|
1190
|
+
app.notFound((c) => options.notFound(c.req.raw));
|
|
1191
|
+
app.onError((error, c) => options.onError(error, c.req.raw));
|
|
1192
|
+
const operations = [...listOperations(options.document)].sort(routeOrder);
|
|
1193
|
+
for (const operation of operations) {
|
|
1194
|
+
const metadata = operationMetadata(operation.operation);
|
|
1195
|
+
const handler = options.handlers[operation.operationId];
|
|
1196
|
+
const route = async (c) => {
|
|
1197
|
+
const request = c.req.raw;
|
|
1198
|
+
if (!metadata.supported || !handler) {
|
|
1199
|
+
return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
|
|
1200
|
+
}
|
|
1201
|
+
const url = new URL(request.url);
|
|
1202
|
+
const context = {
|
|
1203
|
+
request,
|
|
1204
|
+
url,
|
|
1205
|
+
params: c.req.param(),
|
|
1206
|
+
query: queryOf(url),
|
|
1207
|
+
body: await readBody(request),
|
|
1208
|
+
sqlite: options.sqlite,
|
|
1209
|
+
namespace: options.namespace,
|
|
1210
|
+
operation,
|
|
1211
|
+
document: options.document,
|
|
1212
|
+
now
|
|
1213
|
+
};
|
|
1214
|
+
const short = await options.before?.(context);
|
|
1215
|
+
if (short)
|
|
1216
|
+
return short;
|
|
1217
|
+
return handler(context);
|
|
1218
|
+
};
|
|
1219
|
+
app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
|
|
1220
|
+
}
|
|
1221
|
+
return {
|
|
1222
|
+
app,
|
|
1223
|
+
sqlite: options.sqlite,
|
|
1224
|
+
namespace: options.namespace,
|
|
1225
|
+
fetch: async (request) => app.fetch(request),
|
|
1226
|
+
reset: async () => {
|
|
1227
|
+
clearNamespace(options.sqlite, options.namespace);
|
|
1228
|
+
}
|
|
1229
|
+
};
|
|
1230
|
+
};
|
|
1231
|
+
|
|
1232
|
+
// ../core/dist/snapshot.js
|
|
1233
|
+
var snapshotNamespace = (sqlite, namespace) => ({
|
|
1234
|
+
namespace,
|
|
1235
|
+
records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
|
|
1236
|
+
sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
|
|
1237
|
+
});
|
|
1238
|
+
var restoreNamespace = (sqlite, namespace, snapshot) => {
|
|
1239
|
+
sqlite.transaction(() => {
|
|
1240
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1241
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1242
|
+
const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
|
|
1243
|
+
for (const row of snapshot.records) {
|
|
1244
|
+
record.run(namespace, row.collection, row.id, row.seq, row.value);
|
|
1245
|
+
}
|
|
1246
|
+
const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
|
|
1247
|
+
for (const row of snapshot.sequences) {
|
|
1248
|
+
sequence.run(namespace, row.name, row.kind, row.value);
|
|
1249
|
+
}
|
|
1250
|
+
});
|
|
1251
|
+
};
|
|
1252
|
+
|
|
1253
|
+
// ../core/dist/version.js
|
|
1254
|
+
var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
|
|
1255
|
+
|
|
1256
|
+
// ../core/dist/signing.js
|
|
1257
|
+
var encoder = new TextEncoder();
|
|
1258
|
+
var toBase64 = (bytes) => {
|
|
1259
|
+
let binary = "";
|
|
1260
|
+
for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {
|
|
1261
|
+
binary += String.fromCharCode(byte);
|
|
1262
|
+
}
|
|
1263
|
+
return btoa(binary);
|
|
1264
|
+
};
|
|
1265
|
+
var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
|
|
1266
|
+
var toHex = (bytes) => [...bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1267
|
+
var keyBytes = (key) => typeof key === "string" ? encoder.encode(key) : key;
|
|
1268
|
+
var hmac = async (algorithm, key, message2, encoding = "hex") => {
|
|
1269
|
+
const imported = await crypto.subtle.importKey("raw", keyBytes(key), { name: "HMAC", hash: algorithm }, false, ["sign"]);
|
|
1270
|
+
const signed = await crypto.subtle.sign("HMAC", imported, typeof message2 === "string" ? encoder.encode(message2) : message2);
|
|
1271
|
+
return encoding === "hex" ? toHex(signed) : toBase64(signed);
|
|
1272
|
+
};
|
|
1273
|
+
var svixSecretBytes = (secret) => {
|
|
1274
|
+
const raw = secret.replace(/^f?whsec_/, "");
|
|
1275
|
+
try {
|
|
1276
|
+
return fromBase64(raw);
|
|
1277
|
+
} catch {
|
|
1278
|
+
throw new TypeError("webhook secret must be whsec_<base64> (as Svix issues it)");
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
var signSvix = async (secret, messageId, timestampSeconds, body) => `v1,${await hmac("SHA-256", svixSecretBytes(secret), `${messageId}.${timestampSeconds}.${body}`, "base64")}`;
|
|
1282
|
+
var signTimestamped = async (secret, timestampSeconds, body) => `t=${timestampSeconds},v1=${await hmac("SHA-256", secret, `${timestampSeconds}.${body}`, "hex")}`;
|
|
1283
|
+
var signTwilio = async (authToken, url, params) => {
|
|
1284
|
+
const payload = url + Object.keys(params).sort().map((key) => `${key}${params[key]}`).join("");
|
|
1285
|
+
return hmac("SHA-1", authToken, payload, "base64");
|
|
1286
|
+
};
|
|
1287
|
+
|
|
1288
|
+
// ../core/dist/webhooks.js
|
|
1289
|
+
var signers = {
|
|
1290
|
+
/** No signature. */
|
|
1291
|
+
none: () => () => ({}),
|
|
1292
|
+
/** Svix (`svix-id`, `svix-timestamp`, `svix-signature: v1,<b64>`): Junction, Flex, Resend. */
|
|
1293
|
+
svix: (options = {}) => async ({ messageId, body, timestampSeconds, secret }) => {
|
|
1294
|
+
if (!secret)
|
|
1295
|
+
return {};
|
|
1296
|
+
const prefix = options.prefix ?? "svix";
|
|
1297
|
+
return {
|
|
1298
|
+
[`${prefix}-id`]: messageId,
|
|
1299
|
+
[`${prefix}-timestamp`]: String(timestampSeconds),
|
|
1300
|
+
[`${prefix}-signature`]: await signSvix(secret, messageId, timestampSeconds, body)
|
|
1301
|
+
};
|
|
1302
|
+
},
|
|
1303
|
+
/** `<header>: t=<unix>,v1=<hex HMAC-SHA256(secret, "t.body")>`: Stripe, Persona, Fullscript. */
|
|
1304
|
+
timestamped: (header = "Stripe-Signature") => async ({ body, timestampSeconds, secret }) => secret ? { [header]: await signTimestamped(secret, timestampSeconds, body) } : {},
|
|
1305
|
+
/** `X-Twilio-Signature` over the public URL plus the sorted form parameters. */
|
|
1306
|
+
twilio: () => async ({ signUrl, form, secret }) => secret ? { "X-Twilio-Signature": await signTwilio(secret, signUrl, form ?? {}) } : {},
|
|
1307
|
+
/** The secret itself in a header (optionally templated): RxVortex, Pharmetika, AHA `Token <s>`. */
|
|
1308
|
+
header: (header, format = (s) => s) => ({ secret }) => secret ? { [header]: format(secret) } : {},
|
|
1309
|
+
/** Anything else: the service computes the headers itself. */
|
|
1310
|
+
custom: (sign) => sign
|
|
1311
|
+
};
|
|
1312
|
+
var DEFAULT_DELAYS = [0, 5e3, 3e5, 18e5, 72e5];
|
|
1313
|
+
var unref = (timer) => {
|
|
1314
|
+
;
|
|
1315
|
+
timer.unref?.();
|
|
1316
|
+
};
|
|
1317
|
+
var randomId = (prefix) => `${prefix}${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`;
|
|
1318
|
+
var matchesEndpoint = (endpoint, message2) => {
|
|
1319
|
+
const events = endpoint.events ?? ["*"];
|
|
1320
|
+
if (!events.includes("*") && !events.includes(message2.type))
|
|
1321
|
+
return false;
|
|
1322
|
+
for (const [key, value] of Object.entries(endpoint.tags ?? {})) {
|
|
1323
|
+
if (message2.tags[key] !== value)
|
|
1324
|
+
return false;
|
|
1325
|
+
}
|
|
1326
|
+
return true;
|
|
1327
|
+
};
|
|
1328
|
+
var createWebhookHub = (options) => {
|
|
1329
|
+
const delays = options.retryDelaysMs ?? DEFAULT_DELAYS;
|
|
1330
|
+
const timeoutMs = options.timeoutMs ?? 15e3;
|
|
1331
|
+
const delivered = options.delivered ?? ((status) => status >= 200 && status < 300);
|
|
1332
|
+
const send = options.fetch ?? ((request) => fetch(request));
|
|
1333
|
+
const keep = options.keep ?? 500;
|
|
1334
|
+
const now = options.now ?? Date.now;
|
|
1335
|
+
const id = options.id ?? randomId;
|
|
1336
|
+
const scheduleTimer = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
|
|
1337
|
+
const cancel = options.cancel ?? ((handle) => clearTimeout(handle));
|
|
1338
|
+
const global = (options.endpoints ?? []).map((e, i) => ({ ...e, id: e.id ?? `we_global_${i}` }));
|
|
1339
|
+
const own = /* @__PURE__ */ new Map();
|
|
1340
|
+
const messages = [];
|
|
1341
|
+
const deliveries = /* @__PURE__ */ new Map();
|
|
1342
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1343
|
+
const payloads = /* @__PURE__ */ new Map();
|
|
1344
|
+
const faults = /* @__PURE__ */ new Map();
|
|
1345
|
+
const held = /* @__PURE__ */ new Map();
|
|
1346
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
1347
|
+
const track = (work) => {
|
|
1348
|
+
inFlight.add(work);
|
|
1349
|
+
void work.finally(() => inFlight.delete(work));
|
|
1350
|
+
};
|
|
1351
|
+
const attempt = async (delivery) => {
|
|
1352
|
+
const entry = payloads.get(delivery.id);
|
|
1353
|
+
if (!entry)
|
|
1354
|
+
return false;
|
|
1355
|
+
const { message: message2, endpoint } = entry;
|
|
1356
|
+
const timestampSeconds = Math.floor(now() / 1e3);
|
|
1357
|
+
const started = now();
|
|
1358
|
+
const record = {
|
|
1359
|
+
attempt: delivery.attempts.length + 1,
|
|
1360
|
+
at: new Date(started).toISOString(),
|
|
1361
|
+
status: null,
|
|
1362
|
+
error: null,
|
|
1363
|
+
durationMs: 0,
|
|
1364
|
+
responseBody: null
|
|
1365
|
+
};
|
|
1366
|
+
const controller = new AbortController();
|
|
1367
|
+
const timer = scheduleTimer(() => controller.abort(), timeoutMs);
|
|
1368
|
+
try {
|
|
1369
|
+
const signed = await options.signer({
|
|
1370
|
+
messageId: message2.id,
|
|
1371
|
+
body: message2.body,
|
|
1372
|
+
timestampSeconds,
|
|
1373
|
+
url: endpoint.url,
|
|
1374
|
+
secret: endpoint.secret,
|
|
1375
|
+
signUrl: endpoint.signUrl ?? endpoint.url,
|
|
1376
|
+
form: message2.contentType.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(message2.body)) : void 0,
|
|
1377
|
+
type: message2.type,
|
|
1378
|
+
tags: message2.tags
|
|
1379
|
+
});
|
|
1380
|
+
const response = await send(new Request(endpoint.url, {
|
|
1381
|
+
method: "POST",
|
|
1382
|
+
headers: {
|
|
1383
|
+
"content-type": message2.contentType,
|
|
1384
|
+
...endpoint.headers,
|
|
1385
|
+
...message2.headers,
|
|
1386
|
+
...signed
|
|
1387
|
+
},
|
|
1388
|
+
body: message2.body,
|
|
1389
|
+
signal: controller.signal
|
|
1390
|
+
}));
|
|
1391
|
+
record.status = response.status;
|
|
1392
|
+
record.responseBody = await response.text();
|
|
1393
|
+
} catch (error) {
|
|
1394
|
+
record.error = controller.signal.aborted ? `timed out after ${timeoutMs}ms` : error instanceof Error ? error.message : String(error);
|
|
1395
|
+
} finally {
|
|
1396
|
+
cancel(timer);
|
|
1397
|
+
record.durationMs = now() - started;
|
|
1398
|
+
delivery.attempts.push(record);
|
|
1399
|
+
}
|
|
1400
|
+
return record.status !== null && delivered(record.status);
|
|
1401
|
+
};
|
|
1402
|
+
const schedule = (delivery) => {
|
|
1403
|
+
const index = delivery.attempts.length;
|
|
1404
|
+
if (index >= delays.length) {
|
|
1405
|
+
delivery.state = "failed";
|
|
1406
|
+
pending.delete(delivery.id);
|
|
1407
|
+
return;
|
|
1408
|
+
}
|
|
1409
|
+
const run = () => {
|
|
1410
|
+
pending.delete(delivery.id);
|
|
1411
|
+
track(attempt(delivery).then((ok) => {
|
|
1412
|
+
if (ok)
|
|
1413
|
+
delivery.state = "delivered";
|
|
1414
|
+
else
|
|
1415
|
+
schedule(delivery);
|
|
1416
|
+
}));
|
|
1417
|
+
};
|
|
1418
|
+
const delay = delays[index] ?? 0;
|
|
1419
|
+
if (delay <= 0) {
|
|
1420
|
+
pending.set(delivery.id, void 0);
|
|
1421
|
+
run();
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
const timer = scheduleTimer(run, delay);
|
|
1425
|
+
unref(timer);
|
|
1426
|
+
pending.set(delivery.id, timer);
|
|
1427
|
+
};
|
|
1428
|
+
const endpointsFor = (namespace) => [...own.get(namespace) ?? [], ...global];
|
|
1429
|
+
const fanOut = (message2, state = "pending") => {
|
|
1430
|
+
for (const endpoint of endpointsFor(message2.namespace)) {
|
|
1431
|
+
if (!matchesEndpoint(endpoint, message2))
|
|
1432
|
+
continue;
|
|
1433
|
+
const delivery = {
|
|
1434
|
+
id: id("dlv_"),
|
|
1435
|
+
messageId: message2.id,
|
|
1436
|
+
namespace: message2.namespace,
|
|
1437
|
+
type: message2.type,
|
|
1438
|
+
endpointId: endpoint.id ?? "we_unknown",
|
|
1439
|
+
url: endpoint.url,
|
|
1440
|
+
state,
|
|
1441
|
+
attempts: []
|
|
1442
|
+
};
|
|
1443
|
+
deliveries.set(delivery.id, delivery);
|
|
1444
|
+
payloads.set(delivery.id, { message: message2, endpoint });
|
|
1445
|
+
if (state === "pending")
|
|
1446
|
+
schedule(delivery);
|
|
1447
|
+
}
|
|
1448
|
+
};
|
|
1449
|
+
const takeFault = (namespace) => {
|
|
1450
|
+
const queue = faults.get(namespace);
|
|
1451
|
+
const head = queue?.[0];
|
|
1452
|
+
if (!queue || !head)
|
|
1453
|
+
return void 0;
|
|
1454
|
+
head.remaining--;
|
|
1455
|
+
if (head.remaining <= 0)
|
|
1456
|
+
queue.shift();
|
|
1457
|
+
return head.mode;
|
|
1458
|
+
};
|
|
1459
|
+
const releaseHeld = (namespace) => {
|
|
1460
|
+
const waiting = held.get(namespace);
|
|
1461
|
+
if (!waiting)
|
|
1462
|
+
return;
|
|
1463
|
+
held.delete(namespace);
|
|
1464
|
+
for (const message2 of waiting)
|
|
1465
|
+
fanOut(message2);
|
|
1466
|
+
};
|
|
1467
|
+
const hub = {
|
|
1468
|
+
publish(input) {
|
|
1469
|
+
const contentType = input.contentType ?? (input.form ? "application/x-www-form-urlencoded" : "application/json");
|
|
1470
|
+
const body = typeof input.body === "string" ? input.body : input.form ? new URLSearchParams(input.form).toString() : JSON.stringify(input.body);
|
|
1471
|
+
const message2 = {
|
|
1472
|
+
id: input.id ?? id("msg_"),
|
|
1473
|
+
namespace: input.namespace,
|
|
1474
|
+
type: input.type,
|
|
1475
|
+
body,
|
|
1476
|
+
contentType,
|
|
1477
|
+
tags: input.tags ?? {},
|
|
1478
|
+
headers: input.headers ?? {},
|
|
1479
|
+
publishedAt: new Date(now()).toISOString()
|
|
1480
|
+
};
|
|
1481
|
+
messages.push(message2);
|
|
1482
|
+
const ofNamespace = messages.filter((m) => m.namespace === message2.namespace);
|
|
1483
|
+
const oldest = ofNamespace[0];
|
|
1484
|
+
if (ofNamespace.length > keep && oldest)
|
|
1485
|
+
messages.splice(messages.indexOf(oldest), 1);
|
|
1486
|
+
options.onMessage?.(message2);
|
|
1487
|
+
const fault = takeFault(message2.namespace);
|
|
1488
|
+
if (fault === "drop") {
|
|
1489
|
+
fanOut(message2, "dropped");
|
|
1490
|
+
return message2;
|
|
1491
|
+
}
|
|
1492
|
+
if (fault === "reorder") {
|
|
1493
|
+
held.set(message2.namespace, [...held.get(message2.namespace) ?? [], message2]);
|
|
1494
|
+
return message2;
|
|
1495
|
+
}
|
|
1496
|
+
fanOut(message2);
|
|
1497
|
+
if (fault === "duplicate")
|
|
1498
|
+
fanOut(message2);
|
|
1499
|
+
releaseHeld(message2.namespace);
|
|
1500
|
+
return message2;
|
|
1501
|
+
},
|
|
1502
|
+
setEndpoints(namespace, endpoints) {
|
|
1503
|
+
const withIds = endpoints.map((e, i) => ({ ...e, id: e.id ?? `we_${namespace}_${i}` }));
|
|
1504
|
+
own.set(namespace, withIds);
|
|
1505
|
+
return withIds;
|
|
1506
|
+
},
|
|
1507
|
+
endpoints: endpointsFor,
|
|
1508
|
+
messages: (namespace) => namespace === void 0 ? [...messages] : messages.filter((m) => m.namespace === namespace),
|
|
1509
|
+
deliveries: (namespace) => [...deliveries.values()].filter((d) => namespace === void 0 || d.namespace === namespace),
|
|
1510
|
+
async replay(id2) {
|
|
1511
|
+
const delivery = deliveries.get(id2);
|
|
1512
|
+
if (!delivery)
|
|
1513
|
+
return void 0;
|
|
1514
|
+
const ok = await attempt(delivery);
|
|
1515
|
+
if (ok)
|
|
1516
|
+
delivery.state = "delivered";
|
|
1517
|
+
return delivery;
|
|
1518
|
+
},
|
|
1519
|
+
async flush() {
|
|
1520
|
+
for (const namespace of [...held.keys()])
|
|
1521
|
+
releaseHeld(namespace);
|
|
1522
|
+
const waiting = [...pending.entries()];
|
|
1523
|
+
for (const [id2, timer] of waiting) {
|
|
1524
|
+
if (timer === void 0)
|
|
1525
|
+
continue;
|
|
1526
|
+
cancel(timer);
|
|
1527
|
+
pending.delete(id2);
|
|
1528
|
+
const delivery = deliveries.get(id2);
|
|
1529
|
+
if (!delivery)
|
|
1530
|
+
continue;
|
|
1531
|
+
track(attempt(delivery).then((ok) => {
|
|
1532
|
+
if (ok)
|
|
1533
|
+
delivery.state = "delivered";
|
|
1534
|
+
else
|
|
1535
|
+
schedule(delivery);
|
|
1536
|
+
}));
|
|
1537
|
+
}
|
|
1538
|
+
await hub.idle();
|
|
1539
|
+
},
|
|
1540
|
+
async idle() {
|
|
1541
|
+
while (inFlight.size > 0)
|
|
1542
|
+
await Promise.allSettled([...inFlight]);
|
|
1543
|
+
},
|
|
1544
|
+
fault(namespace, fault) {
|
|
1545
|
+
const queue = faults.get(namespace) ?? [];
|
|
1546
|
+
queue.push({ mode: fault.mode, remaining: Math.max(1, fault.count ?? 1) });
|
|
1547
|
+
faults.set(namespace, queue);
|
|
1548
|
+
},
|
|
1549
|
+
clear(namespace) {
|
|
1550
|
+
for (const [id2, delivery] of deliveries) {
|
|
1551
|
+
if (namespace !== void 0 && delivery.namespace !== namespace)
|
|
1552
|
+
continue;
|
|
1553
|
+
const timer = pending.get(id2);
|
|
1554
|
+
if (timer !== void 0)
|
|
1555
|
+
cancel(timer);
|
|
1556
|
+
pending.delete(id2);
|
|
1557
|
+
deliveries.delete(id2);
|
|
1558
|
+
payloads.delete(id2);
|
|
1559
|
+
}
|
|
1560
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1561
|
+
if (namespace === void 0 || messages[i]?.namespace === namespace)
|
|
1562
|
+
messages.splice(i, 1);
|
|
1563
|
+
}
|
|
1564
|
+
if (namespace === void 0) {
|
|
1565
|
+
held.clear();
|
|
1566
|
+
faults.clear();
|
|
1567
|
+
own.clear();
|
|
1568
|
+
} else {
|
|
1569
|
+
held.delete(namespace);
|
|
1570
|
+
faults.delete(namespace);
|
|
1571
|
+
own.delete(namespace);
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
};
|
|
1575
|
+
return hub;
|
|
1576
|
+
};
|
|
1577
|
+
var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1578
|
+
var adminError2 = (status, message2) => json2(status, { error: { type: "mockingbird_admin", message: message2 } });
|
|
1579
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1580
|
+
var parseEndpoint = (value) => {
|
|
1581
|
+
if (!isRecord3(value) || typeof value.url !== "string")
|
|
1582
|
+
return "each endpoint needs a url";
|
|
1583
|
+
try {
|
|
1584
|
+
new URL(value.url);
|
|
1585
|
+
} catch {
|
|
1586
|
+
return `not a URL: ${value.url}`;
|
|
1587
|
+
}
|
|
1588
|
+
const endpoint = { url: value.url };
|
|
1589
|
+
if (typeof value.id === "string")
|
|
1590
|
+
endpoint.id = value.id;
|
|
1591
|
+
if (typeof value.secret === "string")
|
|
1592
|
+
endpoint.secret = value.secret;
|
|
1593
|
+
if (typeof value.signUrl === "string")
|
|
1594
|
+
endpoint.signUrl = value.signUrl;
|
|
1595
|
+
const events = value.events ?? value.enabledEvents;
|
|
1596
|
+
if (Array.isArray(events))
|
|
1597
|
+
endpoint.events = events.map(String);
|
|
1598
|
+
if (isRecord3(value.tags)) {
|
|
1599
|
+
endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
|
|
1600
|
+
}
|
|
1601
|
+
if (typeof value.account === "string")
|
|
1602
|
+
endpoint.tags = { ...endpoint.tags, account: value.account };
|
|
1603
|
+
if (isRecord3(value.headers)) {
|
|
1604
|
+
endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
|
|
1605
|
+
}
|
|
1606
|
+
return endpoint;
|
|
1607
|
+
};
|
|
1608
|
+
var webhookAdminRoutes = (hub) => ({
|
|
1609
|
+
"GET /webhooks": ({ url, namespace }) => json2(200, {
|
|
1610
|
+
deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
|
|
1611
|
+
const type = url.searchParams.get("type");
|
|
1612
|
+
return type === null || d.type === type;
|
|
1613
|
+
})
|
|
1614
|
+
}),
|
|
1615
|
+
"GET /webhooks/events": ({ url, namespace }) => {
|
|
1616
|
+
const type = url.searchParams.get("type");
|
|
1617
|
+
return json2(200, {
|
|
1618
|
+
events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
|
|
1619
|
+
});
|
|
1620
|
+
},
|
|
1621
|
+
"POST /webhooks/:id/replay": async ({ params }) => {
|
|
1622
|
+
const replayed = await hub.replay(params.id);
|
|
1623
|
+
return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
|
|
1624
|
+
},
|
|
1625
|
+
"POST /webhooks/flush": async () => {
|
|
1626
|
+
await hub.flush();
|
|
1627
|
+
return json2(200, { status: "ok" });
|
|
1628
|
+
},
|
|
1629
|
+
"POST /webhooks/faults": ({ body, namespace }) => {
|
|
1630
|
+
if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
|
|
1631
|
+
return adminError2(400, "mode must be duplicate, reorder or drop");
|
|
1632
|
+
}
|
|
1633
|
+
const fault = { mode: body.mode };
|
|
1634
|
+
if (typeof body.count === "number")
|
|
1635
|
+
fault.count = body.count;
|
|
1636
|
+
hub.fault(namespace, fault);
|
|
1637
|
+
return json2(201, { namespace, ...fault });
|
|
1638
|
+
},
|
|
1639
|
+
"GET /webhook-endpoints": ({ namespace }) => json2(200, {
|
|
1640
|
+
endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
|
|
1641
|
+
...rest,
|
|
1642
|
+
secret: secret ? "(set)" : null
|
|
1643
|
+
}))
|
|
1644
|
+
}),
|
|
1645
|
+
"PUT /webhook-endpoints": ({ body, namespace }) => {
|
|
1646
|
+
const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
|
|
1647
|
+
if (!Array.isArray(list))
|
|
1648
|
+
return adminError2(400, "expected [{url, secret?, events?}]");
|
|
1649
|
+
const parsed = [];
|
|
1650
|
+
for (const each of list) {
|
|
1651
|
+
const endpoint = parseEndpoint(each);
|
|
1652
|
+
if (typeof endpoint === "string")
|
|
1653
|
+
return adminError2(400, endpoint);
|
|
1654
|
+
parsed.push(endpoint);
|
|
1655
|
+
}
|
|
1656
|
+
const set = hub.setEndpoints(namespace, parsed);
|
|
1657
|
+
return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
|
|
1658
|
+
},
|
|
1659
|
+
"DELETE /webhook-endpoints": ({ namespace }) => {
|
|
1660
|
+
hub.setEndpoints(namespace, []);
|
|
1661
|
+
return json2(200, { status: "ok" });
|
|
1662
|
+
}
|
|
1663
|
+
});
|
|
1664
|
+
var parsePayload = (message2) => {
|
|
1665
|
+
if (message2.contentType.startsWith("application/json")) {
|
|
1666
|
+
try {
|
|
1667
|
+
return JSON.parse(message2.body);
|
|
1668
|
+
} catch {
|
|
1669
|
+
return message2.body;
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
if (message2.contentType.startsWith("application/x-www-form-urlencoded")) {
|
|
1673
|
+
return Object.fromEntries(new URLSearchParams(message2.body));
|
|
1674
|
+
}
|
|
1675
|
+
return message2.body;
|
|
1676
|
+
};
|
|
1677
|
+
|
|
1678
|
+
// ../core/dist/runtime.js
|
|
1679
|
+
var MOCKINGBIRD_HEADER = "x-mockingbird";
|
|
1680
|
+
var BRANCH_HEADER = "x-mockingbird-branch";
|
|
1681
|
+
var AT_HEADER = "x-mockingbird-at";
|
|
1682
|
+
var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
|
|
1683
|
+
var DEFAULT_NAMESPACE = "default";
|
|
1684
|
+
var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1685
|
+
var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
|
|
1686
|
+
var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1687
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
1688
|
+
var effects = /* @__PURE__ */ new WeakMap();
|
|
1689
|
+
var reuseSorted = (fresh, previous, compare, equal) => {
|
|
1690
|
+
if (!previous || previous.length === 0)
|
|
1691
|
+
return fresh.map((row) => Object.freeze(row));
|
|
1692
|
+
const result = new Array(fresh.length);
|
|
1693
|
+
let unchanged = fresh.length === previous.length;
|
|
1694
|
+
let oldIndex = 0;
|
|
1695
|
+
for (let index = 0; index < fresh.length; index++) {
|
|
1696
|
+
const row = fresh[index];
|
|
1697
|
+
while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
|
|
1698
|
+
oldIndex++;
|
|
1699
|
+
}
|
|
1700
|
+
const old = previous[oldIndex];
|
|
1701
|
+
result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
|
|
1702
|
+
if (result[index] !== previous[index])
|
|
1703
|
+
unchanged = false;
|
|
1704
|
+
}
|
|
1705
|
+
return unchanged ? previous : result;
|
|
1706
|
+
};
|
|
1707
|
+
var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
|
|
1708
|
+
var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
|
|
1709
|
+
var DroppedConnectionError = class extends TypeError {
|
|
1710
|
+
code = "MOCKINGBIRD_DROP";
|
|
1711
|
+
constructor() {
|
|
1712
|
+
super("fetch failed: connection dropped by Mockingbird fault");
|
|
1713
|
+
this.name = "TypeError";
|
|
1714
|
+
}
|
|
1715
|
+
};
|
|
1716
|
+
var operationMatcher = (document2) => {
|
|
1717
|
+
const matchers = listOperations(document2).map((operation) => ({
|
|
1718
|
+
operationId: operation.operationId,
|
|
1719
|
+
method: operation.method.toUpperCase(),
|
|
1720
|
+
pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
|
|
1721
|
+
params: (operation.path.match(/\{/g) ?? []).length
|
|
1722
|
+
})).sort((a, b) => a.params - b.params);
|
|
1723
|
+
return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
|
|
1724
|
+
};
|
|
1725
|
+
var createRuntime = (options) => {
|
|
1726
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
1727
|
+
const clock = options.clock ?? createClock();
|
|
1728
|
+
const rng = createRng(options.seed ?? 0);
|
|
1729
|
+
const wallNow = options.io?.wallNow ?? Date.now;
|
|
1730
|
+
const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
|
|
1731
|
+
const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1732
|
+
const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
|
|
1733
|
+
const metrics = createMetrics();
|
|
1734
|
+
const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
|
|
1735
|
+
const version = options.version ?? PACKAGE_VERSION;
|
|
1736
|
+
const instances = /* @__PURE__ */ new Map();
|
|
1737
|
+
const publicNamespaces = /* @__PURE__ */ new Set();
|
|
1738
|
+
const branchRngs = /* @__PURE__ */ new Map();
|
|
1739
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
1740
|
+
const branchStorage = /* @__PURE__ */ new Map();
|
|
1741
|
+
const captured = /* @__PURE__ */ new Map();
|
|
1742
|
+
const credentials = createCredentialRegistry();
|
|
1743
|
+
const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
|
|
1744
|
+
const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
|
|
1745
|
+
const instanceFor = (key, publicNamespace = key, isolatedRng) => {
|
|
1746
|
+
const existing = instances.get(key);
|
|
1747
|
+
if (existing)
|
|
1748
|
+
return existing;
|
|
1749
|
+
if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
|
|
1750
|
+
throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
|
|
1751
|
+
}
|
|
1752
|
+
const created = options.create({
|
|
1753
|
+
namespace: storageNamespace(key),
|
|
1754
|
+
publicNamespace,
|
|
1755
|
+
sqlite,
|
|
1756
|
+
clock,
|
|
1757
|
+
rng: isolatedRng ?? rng
|
|
1758
|
+
});
|
|
1759
|
+
instances.set(key, created);
|
|
1760
|
+
publicNamespaces.add(publicNamespace);
|
|
1761
|
+
if (isolatedRng)
|
|
1762
|
+
branchRngs.set(key, isolatedRng);
|
|
1763
|
+
return created;
|
|
1764
|
+
};
|
|
1765
|
+
const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
|
|
1766
|
+
const capture = (storage) => {
|
|
1767
|
+
const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
|
|
1768
|
+
const previous = captured.get(storage);
|
|
1769
|
+
const snapshot2 = {
|
|
1770
|
+
namespace: fresh.namespace,
|
|
1771
|
+
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),
|
|
1772
|
+
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)
|
|
1773
|
+
};
|
|
1774
|
+
Object.freeze(snapshot2.records);
|
|
1775
|
+
Object.freeze(snapshot2.sequences);
|
|
1776
|
+
Object.freeze(snapshot2);
|
|
1777
|
+
captured.set(storage, snapshot2);
|
|
1778
|
+
return Object.freeze({
|
|
1779
|
+
snapshot: snapshot2,
|
|
1780
|
+
clock: Object.freeze(clock.state()),
|
|
1781
|
+
rngState: (branchRngs.get(storage) ?? rng).state()
|
|
1782
|
+
});
|
|
1783
|
+
};
|
|
1784
|
+
const timeline = (name = DEFAULT_NAMESPACE) => {
|
|
1785
|
+
let found = timelines.get(name);
|
|
1786
|
+
if (found)
|
|
1787
|
+
return found;
|
|
1788
|
+
instance(name);
|
|
1789
|
+
found = new Timeline({
|
|
1790
|
+
now: clock.now,
|
|
1791
|
+
...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
|
|
1792
|
+
});
|
|
1793
|
+
found.commit(capture(name));
|
|
1794
|
+
timelines.set(name, found);
|
|
1795
|
+
return found;
|
|
1796
|
+
};
|
|
1797
|
+
const physicalBranch = (namespace, branch2) => {
|
|
1798
|
+
if (branch2 === "main")
|
|
1799
|
+
return namespace;
|
|
1800
|
+
const mapKey = `${namespace}\0${branch2}`;
|
|
1801
|
+
const existing = branchStorage.get(mapKey);
|
|
1802
|
+
if (existing)
|
|
1803
|
+
return existing;
|
|
1804
|
+
const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
|
|
1805
|
+
branchStorage.set(mapKey, key);
|
|
1806
|
+
return key;
|
|
1807
|
+
};
|
|
1808
|
+
const ensureBranch = (namespace, branch2, at) => {
|
|
1809
|
+
if (!BRANCH_PATTERN2.test(branch2))
|
|
1810
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
|
|
1811
|
+
const history = timeline(namespace);
|
|
1812
|
+
if (branch2 === "main") {
|
|
1813
|
+
if (at !== void 0) {
|
|
1814
|
+
const point = history.checkout("main", at);
|
|
1815
|
+
restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
|
|
1816
|
+
captured.set(namespace, point.value.snapshot);
|
|
1817
|
+
rng.setState(point.value.rngState);
|
|
1818
|
+
clock.set(point.value.clock.now);
|
|
1819
|
+
if (point.value.clock.frozen)
|
|
1820
|
+
clock.freeze();
|
|
1821
|
+
else
|
|
1822
|
+
clock.unfreeze();
|
|
1823
|
+
}
|
|
1824
|
+
return namespace;
|
|
1825
|
+
}
|
|
1826
|
+
const storage = physicalBranch(namespace, branch2);
|
|
1827
|
+
if (!history.hasBranch(branch2)) {
|
|
1828
|
+
if (at === void 0)
|
|
1829
|
+
history.commit(capture(namespace));
|
|
1830
|
+
const point = history.fork(branch2, at === void 0 ? {} : { from: at });
|
|
1831
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1832
|
+
if (point)
|
|
1833
|
+
branchRng.setState(point.value.rngState);
|
|
1834
|
+
instanceFor(storage, namespace, branchRng);
|
|
1835
|
+
if (point)
|
|
1836
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1837
|
+
if (point)
|
|
1838
|
+
captured.set(storage, point.value.snapshot);
|
|
1839
|
+
} else if (at !== void 0 && history.head(branch2)?.id !== at) {
|
|
1840
|
+
const point = history.checkout(branch2, at);
|
|
1841
|
+
if (!instances.has(storage)) {
|
|
1842
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1843
|
+
branchRng.setState(point.value.rngState);
|
|
1844
|
+
instanceFor(storage, namespace, branchRng);
|
|
1845
|
+
}
|
|
1846
|
+
branchRngs.get(storage)?.setState(point.value.rngState);
|
|
1847
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1848
|
+
captured.set(storage, point.value.snapshot);
|
|
1849
|
+
} else {
|
|
1850
|
+
if (!instances.has(storage)) {
|
|
1851
|
+
const point = history.head(branch2);
|
|
1852
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1853
|
+
if (point)
|
|
1854
|
+
branchRng.setState(point.value.rngState);
|
|
1855
|
+
instanceFor(storage, namespace, branchRng);
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
return storage;
|
|
1859
|
+
};
|
|
1860
|
+
const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
|
|
1861
|
+
const storage = ensureBranch(namespace, branch2);
|
|
1862
|
+
return timeline(namespace).commit(capture(storage), { branch: branch2 });
|
|
1863
|
+
};
|
|
1864
|
+
const branch = (name, branchOptions = {}) => {
|
|
1865
|
+
const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1866
|
+
ensureBranch(namespace, name, branchOptions.at);
|
|
1867
|
+
const head = timeline(namespace).head(name);
|
|
1868
|
+
if (!head)
|
|
1869
|
+
throw new RangeError(`branch ${name} has no checkpoint`);
|
|
1870
|
+
return head;
|
|
1871
|
+
};
|
|
1872
|
+
const checkout = (checkpointId, checkoutOptions = {}) => {
|
|
1873
|
+
const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1874
|
+
const branchName = checkoutOptions.branch ?? "main";
|
|
1875
|
+
const history = timeline(namespace);
|
|
1876
|
+
const point = history.checkout(branchName, checkpointId);
|
|
1877
|
+
const storage = ensureBranch(namespace, branchName);
|
|
1878
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1879
|
+
captured.set(storage, point.value.snapshot);
|
|
1880
|
+
clock.set(point.value.clock.now);
|
|
1881
|
+
if (point.value.clock.frozen)
|
|
1882
|
+
clock.freeze();
|
|
1883
|
+
else
|
|
1884
|
+
clock.unfreeze();
|
|
1885
|
+
(branchRngs.get(storage) ?? rng).setState(point.value.rngState);
|
|
1886
|
+
};
|
|
1887
|
+
const reset = async (name = DEFAULT_NAMESPACE) => {
|
|
1888
|
+
if (name === "*") {
|
|
1889
|
+
options.webhooks?.clear();
|
|
1890
|
+
for (const each of instances.values())
|
|
1891
|
+
await each.reset();
|
|
1892
|
+
timelines.clear();
|
|
1893
|
+
branchStorage.clear();
|
|
1894
|
+
branchRngs.clear();
|
|
1895
|
+
captured.clear();
|
|
1896
|
+
return;
|
|
1897
|
+
}
|
|
1898
|
+
options.webhooks?.clear(name);
|
|
1899
|
+
const target = instances.get(name);
|
|
1900
|
+
if (target)
|
|
1901
|
+
await target.reset();
|
|
1902
|
+
else
|
|
1903
|
+
clearNamespace(sqlite, storageNamespace(name));
|
|
1904
|
+
for (const [mapping, storage] of branchStorage) {
|
|
1905
|
+
if (!mapping.startsWith(`${name}\0`))
|
|
1906
|
+
continue;
|
|
1907
|
+
const branchInstance = instances.get(storage);
|
|
1908
|
+
if (branchInstance)
|
|
1909
|
+
await branchInstance.reset();
|
|
1910
|
+
else
|
|
1911
|
+
clearNamespace(sqlite, storageNamespace(storage));
|
|
1912
|
+
branchStorage.delete(mapping);
|
|
1913
|
+
branchRngs.delete(storage);
|
|
1914
|
+
captured.delete(storage);
|
|
1915
|
+
}
|
|
1916
|
+
timelines.delete(name);
|
|
1917
|
+
captured.delete(name);
|
|
1918
|
+
};
|
|
1919
|
+
const snapshot = (name = DEFAULT_NAMESPACE) => {
|
|
1920
|
+
return checkpoint(name, "main").value.snapshot;
|
|
1921
|
+
};
|
|
1922
|
+
const restore = (from, name = DEFAULT_NAMESPACE) => {
|
|
1923
|
+
instance(name);
|
|
1924
|
+
restoreNamespace(sqlite, storageNamespace(name), from);
|
|
1925
|
+
captured.set(name, from);
|
|
1926
|
+
const history = timelines.get(name);
|
|
1927
|
+
if (history)
|
|
1928
|
+
history.commit(capture(name), { branch: "main" });
|
|
1929
|
+
else
|
|
1930
|
+
timeline(name);
|
|
1931
|
+
};
|
|
1932
|
+
const runtime = {
|
|
1933
|
+
name: options.name,
|
|
1934
|
+
sqlite,
|
|
1935
|
+
clock,
|
|
1936
|
+
faults,
|
|
1937
|
+
metrics,
|
|
1938
|
+
journal,
|
|
1939
|
+
rng,
|
|
1940
|
+
credentials,
|
|
1941
|
+
webhooks: options.webhooks,
|
|
1942
|
+
applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
|
|
1943
|
+
const preset = options.presets?.[name];
|
|
1944
|
+
if (!preset)
|
|
1945
|
+
throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
|
|
1946
|
+
const added = (preset.rules ?? []).map((rule, index) => faults.add({
|
|
1947
|
+
namespace,
|
|
1948
|
+
...rule,
|
|
1949
|
+
...overrides,
|
|
1950
|
+
preset: name,
|
|
1951
|
+
id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
|
|
1952
|
+
}));
|
|
1953
|
+
if (preset.webhook && options.webhooks) {
|
|
1954
|
+
options.webhooks.fault(namespace, {
|
|
1955
|
+
...preset.webhook,
|
|
1956
|
+
...overrides.count !== void 0 ? { count: overrides.count } : {}
|
|
1957
|
+
});
|
|
1958
|
+
}
|
|
1959
|
+
return added;
|
|
1960
|
+
},
|
|
1961
|
+
instance,
|
|
1962
|
+
namespaces: () => [...publicNamespaces].sort(),
|
|
1963
|
+
reset,
|
|
1964
|
+
snapshot,
|
|
1965
|
+
restore,
|
|
1966
|
+
checkpoint,
|
|
1967
|
+
branch,
|
|
1968
|
+
checkout,
|
|
1969
|
+
timeline,
|
|
1970
|
+
fetch: async (incoming) => {
|
|
1971
|
+
let request = incoming;
|
|
1972
|
+
const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
|
|
1973
|
+
if (prefixed) {
|
|
1974
|
+
const url2 = new URL(request.url);
|
|
1975
|
+
url2.pathname = prefixed[2] ?? "/";
|
|
1976
|
+
const headers = new Headers(request.headers);
|
|
1977
|
+
if (!headers.has(NAMESPACE_HEADER)) {
|
|
1978
|
+
headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
|
|
1979
|
+
}
|
|
1980
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
|
1981
|
+
request = new Request(url2, {
|
|
1982
|
+
method: request.method,
|
|
1983
|
+
headers,
|
|
1984
|
+
...hasBody ? { body: await request.arrayBuffer() } : {},
|
|
1985
|
+
signal: request.signal
|
|
1986
|
+
});
|
|
1987
|
+
}
|
|
1988
|
+
let namespace = control.namespaceOf(request);
|
|
1989
|
+
if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
|
|
1990
|
+
const credential = options.credential(request);
|
|
1991
|
+
const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
|
|
1992
|
+
if (mapped !== void 0)
|
|
1993
|
+
namespace = mapped;
|
|
1994
|
+
}
|
|
1995
|
+
const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
|
|
1996
|
+
const at = request.headers.get(AT_HEADER) ?? void 0;
|
|
1997
|
+
const stamp = (response2) => {
|
|
1998
|
+
const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
|
|
1999
|
+
try {
|
|
2000
|
+
response2.headers.set(MOCKINGBIRD_HEADER, value);
|
|
2001
|
+
return response2;
|
|
2002
|
+
} catch {
|
|
2003
|
+
const copy = new Response(response2.body, response2);
|
|
2004
|
+
copy.headers.set(MOCKINGBIRD_HEADER, value);
|
|
2005
|
+
return copy;
|
|
2006
|
+
}
|
|
2007
|
+
};
|
|
2008
|
+
const handled = await control.handle(request);
|
|
2009
|
+
if (handled)
|
|
2010
|
+
return stamp(handled);
|
|
2011
|
+
const started = monotonicNow();
|
|
2012
|
+
const url = new URL(request.url);
|
|
2013
|
+
const operationId = operationIdFor(request, url.pathname);
|
|
2014
|
+
const log = (status, faultId, response2) => {
|
|
2015
|
+
const noted = response2 ? responseNotes(response2) : void 0;
|
|
2016
|
+
const entry = {
|
|
2017
|
+
service: options.name,
|
|
2018
|
+
namespace,
|
|
2019
|
+
operationId,
|
|
2020
|
+
method: request.method,
|
|
2021
|
+
path: url.pathname,
|
|
2022
|
+
status,
|
|
2023
|
+
durationMs: Math.round((monotonicNow() - started) * 100) / 100,
|
|
2024
|
+
unmatched: options.document !== void 0 && operationId === void 0,
|
|
2025
|
+
...faultId !== void 0 ? { faultId } : {},
|
|
2026
|
+
...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
|
|
2027
|
+
...noted?.adopted ? { adopted: true } : {}
|
|
2028
|
+
};
|
|
2029
|
+
metrics.record(entry);
|
|
2030
|
+
journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
|
|
2031
|
+
options.onLog?.(entry);
|
|
2032
|
+
};
|
|
2033
|
+
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
2034
|
+
log(400);
|
|
2035
|
+
return stamp(new Response(JSON.stringify({
|
|
2036
|
+
error: {
|
|
2037
|
+
type: "mockingbird_admin",
|
|
2038
|
+
message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
|
|
2039
|
+
}
|
|
2040
|
+
}), { status: 400, headers: { "content-type": "application/json" } }));
|
|
2041
|
+
}
|
|
2042
|
+
if (!BRANCH_PATTERN2.test(selectedBranch)) {
|
|
2043
|
+
log(400);
|
|
2044
|
+
return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
|
|
2045
|
+
}
|
|
2046
|
+
let storage;
|
|
2047
|
+
try {
|
|
2048
|
+
if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
|
|
2049
|
+
const point = timeline(namespace).get(at);
|
|
2050
|
+
storage = physicalBranch(namespace, `at_${at}`);
|
|
2051
|
+
let viewRng = branchRngs.get(storage);
|
|
2052
|
+
if (!viewRng) {
|
|
2053
|
+
viewRng = createRng(options.seed ?? 0);
|
|
2054
|
+
instanceFor(storage, namespace, viewRng);
|
|
2055
|
+
}
|
|
2056
|
+
viewRng.setState(point.value.rngState);
|
|
2057
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2058
|
+
captured.set(storage, point.value.snapshot);
|
|
2059
|
+
} else {
|
|
2060
|
+
storage = ensureBranch(namespace, selectedBranch, at);
|
|
2061
|
+
}
|
|
2062
|
+
} catch (error) {
|
|
2063
|
+
log(409);
|
|
2064
|
+
return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
|
|
2065
|
+
}
|
|
2066
|
+
const hits = await faults.take({
|
|
2067
|
+
operationId,
|
|
2068
|
+
method: request.method,
|
|
2069
|
+
path: url.pathname,
|
|
2070
|
+
namespace
|
|
2071
|
+
});
|
|
2072
|
+
const final = hits.find((hit) => hit.drop || hit.response);
|
|
2073
|
+
if (final?.drop) {
|
|
2074
|
+
log(0, final.id);
|
|
2075
|
+
throw new DroppedConnectionError();
|
|
2076
|
+
}
|
|
2077
|
+
if (final?.response) {
|
|
2078
|
+
log(final.response.status, final.id);
|
|
2079
|
+
return stamp(final.response);
|
|
2080
|
+
}
|
|
2081
|
+
const fired = hits.filter((hit) => hit.effect !== void 0);
|
|
2082
|
+
if (fired.length > 0)
|
|
2083
|
+
effects.set(request, fired.map((hit) => hit.effect));
|
|
2084
|
+
let response = await instanceFor(storage, namespace).fetch(request);
|
|
2085
|
+
if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
|
|
2086
|
+
const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
|
|
2087
|
+
response = mutableResponse(response);
|
|
2088
|
+
response.headers.set(CHECKPOINT_HEADER, point.id);
|
|
2089
|
+
}
|
|
2090
|
+
if (selectedBranch !== "main") {
|
|
2091
|
+
response = mutableResponse(response);
|
|
2092
|
+
response.headers.set(BRANCH_HEADER, selectedBranch);
|
|
2093
|
+
}
|
|
2094
|
+
if (at !== void 0) {
|
|
2095
|
+
response = mutableResponse(response);
|
|
2096
|
+
response.headers.set(AT_HEADER, at);
|
|
2097
|
+
}
|
|
2098
|
+
log(response.status, fired[0]?.id, response);
|
|
2099
|
+
return stamp(response);
|
|
2100
|
+
}
|
|
2101
|
+
};
|
|
2102
|
+
const control = createControlPlane({
|
|
2103
|
+
name: options.name,
|
|
2104
|
+
startedAt: wallNow(),
|
|
2105
|
+
wallNow,
|
|
2106
|
+
clock,
|
|
2107
|
+
faults,
|
|
2108
|
+
metrics,
|
|
2109
|
+
journal,
|
|
2110
|
+
defaultNamespace: DEFAULT_NAMESPACE,
|
|
2111
|
+
namespaces: runtime.namespaces,
|
|
2112
|
+
reset,
|
|
2113
|
+
timeTravel: {
|
|
2114
|
+
checkpoint: (name, branchName) => {
|
|
2115
|
+
const point = checkpoint(name, branchName);
|
|
2116
|
+
return {
|
|
2117
|
+
id: point.id,
|
|
2118
|
+
branch: point.branch,
|
|
2119
|
+
parent: point.parent,
|
|
2120
|
+
at: point.at,
|
|
2121
|
+
records: point.value.snapshot.records.length
|
|
2122
|
+
};
|
|
2123
|
+
},
|
|
2124
|
+
branch: (branchName, branchOptions) => {
|
|
2125
|
+
const point = branch(branchName, branchOptions);
|
|
2126
|
+
return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
|
|
2127
|
+
},
|
|
2128
|
+
checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
|
|
2129
|
+
retain: (name, checkpointId) => {
|
|
2130
|
+
timeline(name).retain(checkpointId);
|
|
2131
|
+
},
|
|
2132
|
+
release: (name, checkpointId) => timeline(name).release(checkpointId),
|
|
2133
|
+
inspect: (name) => {
|
|
2134
|
+
const history = timeline(name);
|
|
2135
|
+
return {
|
|
2136
|
+
branches: history.branches(),
|
|
2137
|
+
checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
|
|
2138
|
+
id,
|
|
2139
|
+
branch: branchName,
|
|
2140
|
+
parent,
|
|
2141
|
+
at
|
|
2142
|
+
}))
|
|
2143
|
+
};
|
|
2144
|
+
}
|
|
2145
|
+
},
|
|
2146
|
+
describe: options.describe ?? (() => ({})),
|
|
2147
|
+
...options.presets ? {
|
|
2148
|
+
applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
|
|
2149
|
+
} : {},
|
|
2150
|
+
routes: {
|
|
2151
|
+
...credentialRoutes(credentials),
|
|
2152
|
+
...options.presets ? presetRoutes(options.presets, runtime) : {},
|
|
2153
|
+
...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
|
|
2154
|
+
...options.admin?.(runtime) ?? {}
|
|
2155
|
+
},
|
|
2156
|
+
adminKey: options.adminKey
|
|
2157
|
+
});
|
|
2158
|
+
return runtime;
|
|
2159
|
+
};
|
|
2160
|
+
var mutableResponse = (response) => {
|
|
2161
|
+
try {
|
|
2162
|
+
response.headers.set("x-mockingbird-mutable-probe", "1");
|
|
2163
|
+
response.headers.delete("x-mockingbird-mutable-probe");
|
|
2164
|
+
return response;
|
|
2165
|
+
} catch {
|
|
2166
|
+
return new Response(response.body, response);
|
|
2167
|
+
}
|
|
2168
|
+
};
|
|
2169
|
+
var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2170
|
+
var adminFail = (status, message2) => adminJson(status, { error: { type: "mockingbird_admin", message: message2 } });
|
|
2171
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2172
|
+
var credentialRoutes = (registry) => ({
|
|
2173
|
+
"GET /credentials": () => adminJson(200, {
|
|
2174
|
+
credentials: registry.entries().map(({ credential, namespace }) => ({
|
|
2175
|
+
credential: maskCredential(credential),
|
|
2176
|
+
namespace
|
|
2177
|
+
}))
|
|
2178
|
+
}),
|
|
2179
|
+
"PUT /credentials": ({ body, namespace }) => {
|
|
2180
|
+
const pairs = [];
|
|
2181
|
+
const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
|
|
2182
|
+
if (Array.isArray(list)) {
|
|
2183
|
+
for (const each of list) {
|
|
2184
|
+
if (typeof each === "string")
|
|
2185
|
+
pairs.push([each, namespace]);
|
|
2186
|
+
else if (isObject(each) && typeof each.credential === "string") {
|
|
2187
|
+
pairs.push([
|
|
2188
|
+
each.credential,
|
|
2189
|
+
typeof each.namespace === "string" ? each.namespace : namespace
|
|
2190
|
+
]);
|
|
2191
|
+
} else
|
|
2192
|
+
return adminFail(400, "each entry is a credential string or {credential, namespace}");
|
|
2193
|
+
}
|
|
2194
|
+
} else if (isObject(list)) {
|
|
2195
|
+
for (const [credential, target] of Object.entries(list)) {
|
|
2196
|
+
if (typeof target !== "string")
|
|
2197
|
+
return adminFail(400, `namespace for ${credential} must be a string`);
|
|
2198
|
+
pairs.push([credential, target]);
|
|
2199
|
+
}
|
|
2200
|
+
} else if (isObject(body) && typeof body.credential === "string") {
|
|
2201
|
+
pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
|
|
2202
|
+
} else {
|
|
2203
|
+
return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
|
|
2204
|
+
}
|
|
2205
|
+
for (const [credential, target] of pairs) {
|
|
2206
|
+
if (!NAMESPACE_PATTERN.test(target))
|
|
2207
|
+
return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
|
|
2208
|
+
registry.set(credential, target);
|
|
2209
|
+
}
|
|
2210
|
+
return adminJson(200, { mapped: pairs.length });
|
|
2211
|
+
},
|
|
2212
|
+
"DELETE /credentials": ({ url }) => {
|
|
2213
|
+
const credential = url.searchParams.get("credential");
|
|
2214
|
+
if (credential === null)
|
|
2215
|
+
registry.clear();
|
|
2216
|
+
else
|
|
2217
|
+
registry.remove(credential);
|
|
2218
|
+
return adminJson(200, { status: "ok" });
|
|
2219
|
+
}
|
|
2220
|
+
});
|
|
2221
|
+
var presetRoutes = (presets, runtime) => ({
|
|
2222
|
+
"GET /faults/presets": () => adminJson(200, {
|
|
2223
|
+
presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
|
|
2224
|
+
}),
|
|
2225
|
+
"POST /faults/presets/:name": ({ params, body, namespace }) => {
|
|
2226
|
+
const name = params.name;
|
|
2227
|
+
if (!presets[name])
|
|
2228
|
+
return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
|
|
2229
|
+
const overrides = isObject(body) ? body : {};
|
|
2230
|
+
return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
|
|
2231
|
+
}
|
|
2232
|
+
});
|
|
2233
|
+
|
|
2234
|
+
// src/catalog.ts
|
|
2235
|
+
var LABS = [
|
|
2236
|
+
{ labId: 1, name: "Access Health Alliance (AHA)", isCurrentLab: true },
|
|
2237
|
+
{ labId: 2, name: "Quest Diagnostics", isCurrentLab: false },
|
|
2238
|
+
{ labId: 3, name: "LabCorp", isCurrentLab: false }
|
|
2239
|
+
];
|
|
2240
|
+
var ELEMENTS = [
|
|
2241
|
+
{
|
|
2242
|
+
elementId: 460,
|
|
2243
|
+
elementName: "Total Cholesterol",
|
|
2244
|
+
elementGenderType: "Both",
|
|
2245
|
+
cuUnit: "mg/dL",
|
|
2246
|
+
siUnit: "mmol/L",
|
|
2247
|
+
cuToSiConversionFactor: 0.0259,
|
|
2248
|
+
codes: ["2093-3"],
|
|
2249
|
+
optimal: [160, 199],
|
|
2250
|
+
standard: [125, 199]
|
|
2251
|
+
},
|
|
2252
|
+
{
|
|
2253
|
+
elementId: 494,
|
|
2254
|
+
elementName: "Glucose Fasting",
|
|
2255
|
+
elementGenderType: "Both",
|
|
2256
|
+
cuUnit: "mg/dL",
|
|
2257
|
+
siUnit: "mmol/L",
|
|
2258
|
+
cuToSiConversionFactor: 0.0555,
|
|
2259
|
+
codes: ["2345-7", "1558-6"],
|
|
2260
|
+
optimal: [75, 86],
|
|
2261
|
+
standard: [65, 99]
|
|
2262
|
+
},
|
|
2263
|
+
{
|
|
2264
|
+
elementId: 496,
|
|
2265
|
+
elementName: "Creatinine",
|
|
2266
|
+
elementGenderType: "Both",
|
|
2267
|
+
cuUnit: "mg/dL",
|
|
2268
|
+
siUnit: "\xB5mol/L",
|
|
2269
|
+
cuToSiConversionFactor: 88.4,
|
|
2270
|
+
codes: ["2160-0"],
|
|
2271
|
+
optimal: [0.8, 1.1],
|
|
2272
|
+
standard: [0.6, 1.3]
|
|
2273
|
+
},
|
|
2274
|
+
{
|
|
2275
|
+
elementId: 506,
|
|
2276
|
+
elementName: "Albumin",
|
|
2277
|
+
elementGenderType: "Both",
|
|
2278
|
+
cuUnit: "g/dL",
|
|
2279
|
+
siUnit: "g/L",
|
|
2280
|
+
cuToSiConversionFactor: 10,
|
|
2281
|
+
codes: ["1751-7"],
|
|
2282
|
+
optimal: [4, 5],
|
|
2283
|
+
standard: [3.5, 5.5]
|
|
2284
|
+
},
|
|
2285
|
+
{
|
|
2286
|
+
elementId: 511,
|
|
2287
|
+
elementName: "Alk Phos",
|
|
2288
|
+
elementGenderType: "Both",
|
|
2289
|
+
cuUnit: "U/L",
|
|
2290
|
+
siUnit: "U/L",
|
|
2291
|
+
cuToSiConversionFactor: 1,
|
|
2292
|
+
codes: ["6768-6"],
|
|
2293
|
+
optimal: [70, 100],
|
|
2294
|
+
standard: [40, 129]
|
|
2295
|
+
},
|
|
2296
|
+
{
|
|
2297
|
+
elementId: 537,
|
|
2298
|
+
elementName: "Hs CRP - Male",
|
|
2299
|
+
elementGenderType: "Male",
|
|
2300
|
+
cuUnit: "mg/L",
|
|
2301
|
+
siUnit: "mg/L",
|
|
2302
|
+
cuToSiConversionFactor: 1,
|
|
2303
|
+
codes: ["30522-7"],
|
|
2304
|
+
optimal: [0, 0.55],
|
|
2305
|
+
standard: [0, 3]
|
|
2306
|
+
},
|
|
2307
|
+
{
|
|
2308
|
+
elementId: 538,
|
|
2309
|
+
elementName: "Hs CRP - Female",
|
|
2310
|
+
elementGenderType: "Female",
|
|
2311
|
+
cuUnit: "mg/L",
|
|
2312
|
+
siUnit: "mg/L",
|
|
2313
|
+
cuToSiConversionFactor: 1,
|
|
2314
|
+
codes: ["30522-7"],
|
|
2315
|
+
optimal: [0, 1.5],
|
|
2316
|
+
standard: [0, 3]
|
|
2317
|
+
},
|
|
2318
|
+
{
|
|
2319
|
+
elementId: 556,
|
|
2320
|
+
elementName: "Total WBCs",
|
|
2321
|
+
elementGenderType: "Both",
|
|
2322
|
+
cuUnit: "k/cumm",
|
|
2323
|
+
siUnit: "10E9/L",
|
|
2324
|
+
cuToSiConversionFactor: 1,
|
|
2325
|
+
codes: ["6690-2"],
|
|
2326
|
+
optimal: [5, 8],
|
|
2327
|
+
standard: [3.8, 10.8]
|
|
2328
|
+
},
|
|
2329
|
+
{
|
|
2330
|
+
elementId: 564,
|
|
2331
|
+
elementName: "MCV",
|
|
2332
|
+
elementGenderType: "Both",
|
|
2333
|
+
cuUnit: "fL",
|
|
2334
|
+
siUnit: "fL",
|
|
2335
|
+
cuToSiConversionFactor: 1,
|
|
2336
|
+
codes: ["787-2"],
|
|
2337
|
+
optimal: [82, 89.9],
|
|
2338
|
+
standard: [80, 100]
|
|
2339
|
+
},
|
|
2340
|
+
{
|
|
2341
|
+
elementId: 568,
|
|
2342
|
+
elementName: "RDW",
|
|
2343
|
+
elementGenderType: "Both",
|
|
2344
|
+
cuUnit: "%",
|
|
2345
|
+
siUnit: "%",
|
|
2346
|
+
cuToSiConversionFactor: 1,
|
|
2347
|
+
codes: ["788-0"],
|
|
2348
|
+
optimal: [11.7, 13],
|
|
2349
|
+
standard: [11, 15]
|
|
2350
|
+
},
|
|
2351
|
+
{
|
|
2352
|
+
elementId: 571,
|
|
2353
|
+
elementName: "Lymphocytes - %",
|
|
2354
|
+
elementGenderType: "Both",
|
|
2355
|
+
cuUnit: "%",
|
|
2356
|
+
siUnit: "%",
|
|
2357
|
+
cuToSiConversionFactor: 1,
|
|
2358
|
+
codes: ["736-9"],
|
|
2359
|
+
optimal: [25, 40],
|
|
2360
|
+
standard: [20, 40]
|
|
2361
|
+
},
|
|
2362
|
+
{
|
|
2363
|
+
elementId: 580,
|
|
2364
|
+
elementName: "Testosterone Total - Male",
|
|
2365
|
+
elementGenderType: "Male",
|
|
2366
|
+
cuUnit: "ng/dL",
|
|
2367
|
+
siUnit: "nmol/L",
|
|
2368
|
+
cuToSiConversionFactor: 0.0347,
|
|
2369
|
+
codes: ["2986-8"],
|
|
2370
|
+
optimal: [600, 900],
|
|
2371
|
+
standard: [250, 1100]
|
|
2372
|
+
},
|
|
2373
|
+
{
|
|
2374
|
+
elementId: 590,
|
|
2375
|
+
elementName: "TSH",
|
|
2376
|
+
elementGenderType: "Both",
|
|
2377
|
+
cuUnit: "\xB5IU/mL",
|
|
2378
|
+
siUnit: "mIU/L",
|
|
2379
|
+
cuToSiConversionFactor: 1,
|
|
2380
|
+
codes: ["3016-3", "11580-8"],
|
|
2381
|
+
optimal: [1, 2],
|
|
2382
|
+
standard: [0.4, 4.5]
|
|
2383
|
+
}
|
|
2384
|
+
];
|
|
2385
|
+
var labElement = (labId, element) => ({
|
|
2386
|
+
labId,
|
|
2387
|
+
elementId: element.elementId,
|
|
2388
|
+
elementName: element.elementName,
|
|
2389
|
+
elementGenderType: element.elementGenderType,
|
|
2390
|
+
cuUnit: element.cuUnit,
|
|
2391
|
+
siUnit: element.siUnit,
|
|
2392
|
+
cuToSiConversionFactor: element.cuToSiConversionFactor,
|
|
2393
|
+
elementReferences: element.codes.map((code) => ({
|
|
2394
|
+
elementCode: code,
|
|
2395
|
+
elementName: element.elementName
|
|
2396
|
+
}))
|
|
2397
|
+
});
|
|
2398
|
+
|
|
2399
|
+
// src/generated/openapi.ts
|
|
2400
|
+
var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Optimal DX partner API (Mockingbird subset)","description":"Stateful mock of the Optimal DX (ODX) partner API our backend calls: partner labs and their\\nbiomarker elements, practice patients (create, update, delete, partner link, search), lab\\nresults (structured and HL7 v2 ORU imports), the Functional Health Report (JSON or PDF), and\\nwebhook registrations whose signing keys verify the PatientTest webhooks the mock posts.\\nODX publishes no spec; the contract is hand-authored from our consumer's wire shapes. The\\nvendor was retired 2026-07-22 but queue paths still call it while \`geviti-pdf-enabled\` is off.\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from optimal.dx.service.ts / optimal.dx.types.ts, the webhook guard and DTO (odx-signature.guard.ts, odx-webhook-data.dto.ts) and the QA harness (packages/qa odx-client.ts)."}},"servers":[{"url":"https://odxinstanceresource.azure-api.net/geviti"}],"security":[{"apiKey":[]}],"paths":{"/v1/partner/labs":{"get":{"operationId":"ListPartnerLabs","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Labs this partner can import from","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Lab"}}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/v1/elements/{labId}":{"parameters":[{"name":"labId","in":"path","required":true,"schema":{"type":"string","enum":["1","2","3","999"]}}],"get":{"operationId":"ListElements","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The lab's biomarker elements (with the codes HL7 OBX-3 is mapped by)","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/LabElement"}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/v1/practice/{practiceId}/patient":{"parameters":[{"$ref":"#/components/parameters/PracticeId"}],"post":{"operationId":"CreatePatient","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientRequest"}}}},"responses":{"200":{"description":"Created patient","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Patient"}}}},"400":{"$ref":"#/components/responses/ValidationProblem"},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/v1/practice/{practiceId}/patient/{patientId}":{"parameters":[{"$ref":"#/components/parameters/PracticeId"},{"$ref":"#/components/parameters/PatientId"}],"put":{"operationId":"UpdatePatient","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientRequest"}}}},"responses":{"200":{"description":"Updated patient","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Patient"}}}},"400":{"$ref":"#/components/responses/ValidationProblem"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}},"delete":{"operationId":"DeletePatient","description":"Used by the QA harness teardown (via the send-odx-api-request dev tool).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"204":{"description":"Deleted"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/v1/practice/{practiceId}/patient/{patientId}/partner/{localUserId}":{"parameters":[{"$ref":"#/components/parameters/PracticeId"},{"$ref":"#/components/parameters/PatientId"},{"name":"localUserId","in":"path","required":true,"description":"Our user id, stored as the patient's partner (external) id.","schema":{"type":"string","pattern":"^[0-9]{1,9}$"}}],"post":{"operationId":"LinkPartnerUser","description":"Our client posts the literal body \`false\`.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":false,"content":{"application/json":{"schema":{"type":"boolean"}}}},"responses":{"200":{"description":"Linked","content":{"application/json":{"schema":{"type":"boolean"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/v1/practice/{practiceId}/patients":{"parameters":[{"$ref":"#/components/parameters/PracticeId"},{"name":"email","in":"query","schema":{"type":"string","enum":["ada@example.com","nobody@example.com"]}},{"name":"firstName","in":"query","schema":{"type":"string","enum":["Ada","Grace"]}},{"name":"lastName","in":"query","schema":{"type":"string","enum":["Lovelace","Hopper"]}},{"name":"dateOfBirth","in":"query","schema":{"type":"string","enum":["1985-12-10","1906-12-09"]}}],"get":{"operationId":"ListPatients","description":"All patients, or a search when any filter is given (404 when nothing matches).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Matching patients","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Patient"}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/v1/practice/{practiceId}/patient/{patientId}/testresults":{"parameters":[{"$ref":"#/components/parameters/PracticeId"},{"$ref":"#/components/parameters/PatientId"}],"post":{"operationId":"CreateTestResults","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TestResultsRequest"}}}},"responses":{"200":{"description":"The imported patient test","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientTest"}}}},"400":{"$ref":"#/components/responses/ValidationProblem"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/v1/practice/{practiceId}/patient/{patientId}/test":{"parameters":[{"$ref":"#/components/parameters/PracticeId"},{"$ref":"#/components/parameters/PatientId"}],"post":{"operationId":"CreatePatientTest","description":"Import an HL7 v2 ORU^R01 message; OBX-3 codes map to elements by their elementReferences.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Hl7Request"}}}},"responses":{"200":{"description":"The imported patient test","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientTest"}}}},"400":{"$ref":"#/components/responses/ValidationProblem"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/v1/practice/{practiceId}/patient/{patientId}/test/{patientTestId}":{"parameters":[{"$ref":"#/components/parameters/PracticeId"},{"$ref":"#/components/parameters/PatientId"},{"name":"patientTestId","in":"path","required":true,"schema":{"type":"string","description":"Ids are assigned sequentially from 700001 (parity walks reuse them).","enum":["700001","700002","999999"]}}],"put":{"operationId":"UpdatePatientTest","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Hl7Request"}}}},"responses":{"200":{"description":"The re-imported patient test","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientTest"}}}},"400":{"$ref":"#/components/responses/ValidationProblem"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/v1/practice/{practiceId}/patient/{patientId}/tests":{"parameters":[{"$ref":"#/components/parameters/PracticeId"},{"$ref":"#/components/parameters/PatientId"}],"get":{"operationId":"ListPatientTests","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The patient's tests, oldest first","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/PatientTest"}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/v1/reports/FunctionalHealthReport":{"post":{"operationId":"GenerateFunctionalHealthReport","description":"\`outputType: Json\` answers the report as JSON; \`Pdf\` answers application/pdf bytes.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportRequest"}}}},"responses":{"200":{"description":"The report","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Report"}},"application/pdf":{"schema":{"type":"string","format":"binary"}}}},"400":{"$ref":"#/components/responses/ValidationProblem"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/v1/webhooks":{"get":{"operationId":"ListWebhooks","description":"Our webhook guard calls this on every inbound webhook to fetch the signing key.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Registered webhooks, with their signing keys","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Webhook"}}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/v1/webhook":{"post":{"operationId":"RegisterWebhook","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookRequest"}}}},"responses":{"200":{"description":"Registered","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Webhook"}}}},"400":{"$ref":"#/components/responses/ValidationProblem"},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/v1/webhook/{partnerWebhookId}":{"parameters":[{"name":"partnerWebhookId","in":"path","required":true,"schema":{"type":"string","description":"Ids are assigned sequentially from 1.","enum":["1","2","999999"]}}],"put":{"operationId":"UpdateWebhook","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookRequest"}}}},"responses":{"200":{"description":"Updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Webhook"}}}},"400":{"$ref":"#/components/responses/ValidationProblem"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}}},"components":{"securitySchemes":{"apiKey":{"type":"apiKey","in":"header","name":"ApiKey"}},"parameters":{"PracticeId":{"name":"practiceId","in":"path","required":true,"description":"OPTIMAL_PRACTICE_ID. Parity walks use one fixed practice.","schema":{"type":"string","enum":["3f0c0c43-7d2b-4b8e-9a50-9c1f0c6c0001"]}},"PatientId":{"name":"patientId","in":"path","required":true,"schema":{"type":"string","description":"Ids are assigned sequentially from 100001 (parity walks reuse them).","enum":["100001","100002","999999"]}}},"responses":{"Unauthorized":{"description":"Missing or invalid ApiKey (Azure API Management's answer)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"NotFound":{"description":"Unknown patient, test, lab or webhook","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"ValidationProblem":{"description":"ASP.NET validation problem details","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"schemas":{"Error":{"type":"object","description":"\`{Message}\` (ODX), \`{statusCode, message}\` (API Management) or ASP.NET problem details.","properties":{"Message":{"type":"string"},"message":{"type":"string"},"statusCode":{"type":"integer"},"type":{"type":"string"},"title":{"type":"string"},"status":{"type":"integer"},"errors":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}}}}},"Lab":{"type":"object","required":["labId","name"],"properties":{"labId":{"type":"integer"},"name":{"type":"string"},"isCurrentLab":{"type":"boolean"}}},"LabElement":{"type":"object","required":["labId","elementId","elementName","elementReferences"],"properties":{"labId":{"type":"integer"},"elementId":{"type":"integer"},"elementName":{"type":"string"},"elementGenderType":{"type":"string"},"cuUnit":{"type":"string"},"siUnit":{"type":"string"},"cuToSiConversionFactor":{"type":"number"},"elementReferences":{"type":"array","items":{"type":"object","required":["elementCode","elementName"],"properties":{"elementCode":{"type":"string"},"elementName":{"type":"string"}}}}}},"PatientRequest":{"type":"object","required":["firstName","lastName","gender","email"],"properties":{"firstName":{"type":"string","minLength":1,"maxLength":60,"enum":["Ada","Grace","Katherine"]},"lastName":{"type":"string","minLength":1,"maxLength":60,"enum":["Lovelace","Hopper","Johnson"]},"nickname":{"type":["string","null"],"maxLength":60},"dateOfBirth":{"type":["string","null"],"enum":["1985-12-10","1906-12-09",null]},"gender":{"type":"string","enum":["Male","Female"]},"email":{"type":"string","enum":["ada@example.com","grace@example.com"]},"userId":{"type":"string","maxLength":40},"workspaceId":{"type":"integer","minimum":0,"maximum":10}}},"Patient":{"type":"object","required":["patientId","practiceId","firstName","lastName","gender","email","createdDate","lastUpdatedDate"],"properties":{"patientId":{"type":"integer"},"practiceId":{"type":"string"},"createdDate":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"lastUpdatedDate":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"userTitle":{"type":["string","null"]},"userFirstName":{"type":["string","null"]},"userLastName":{"type":["string","null"]},"firstName":{"type":"string"},"lastName":{"type":"string"},"nickname":{"type":["string","null"]},"dateOfBirth":{"type":["string","null"]},"gender":{"type":"string"},"homePhone":{"type":["string","null"]},"workPhone":{"type":["string","null"]},"mobile":{"type":["string","null"]},"email":{"type":"string"},"address":{"type":["string","null"]},"address2":{"type":["string","null"]},"address3":{"type":["string","null"]},"city":{"type":["string","null"]},"province":{"type":["string","null"]},"postalCode":{"type":["string","null"]},"country":{"type":["string","null"]},"userId":{"type":["string","null"]},"workspaceId":{"type":"integer"}}},"TestResultsRequest":{"type":"object","required":["labProfileId","labId","testDate","unitType","results"],"properties":{"labProfileId":{"type":"integer","enum":[1,2]},"labId":{"type":"string","enum":["1","2"]},"testDate":{"type":"string","enum":["2025-01-15T00:00:00.000Z","2025-06-15T00:00:00.000Z"]},"unitType":{"type":"string","enum":["ConventionalUS","SI"]},"userId":{"type":"string","maxLength":40},"menstrualPhase":{"type":"string","enum":["Unknown","Follicular","Ovulation","Luteal","PostMenopausal"]},"isFasting":{"type":"boolean"},"results":{"type":"array","maxItems":5,"items":{"type":"object","required":["elementId"],"properties":{"elementId":{"type":"integer","enum":[494,496,506,537,999]},"value":{"type":"number","minimum":0,"maximum":500},"comparison":{"type":["string","null"],"enum":["<",">","",null]},"observationDateTime":{"type":"string","maxLength":40}}}}}},"Hl7Request":{"type":"object","required":["labProfileId","labId","testDate","unitType","hl7"],"properties":{"labProfileId":{"type":"integer","enum":[1,2]},"labId":{"type":"integer","enum":[1,2,999]},"testDate":{"type":"string","enum":["2025-01-15T00:00:00.000Z","2025-06-15T00:00:00.000Z"]},"unitType":{"type":"string","enum":["ConventionalUS","SI"]},"userId":{"type":"string","maxLength":40},"externalReference":{"type":["string","null"],"maxLength":60},"externalMessageControlId":{"type":["string","null"],"maxLength":60},"externalPatientTestId":{"type":["string","null"],"maxLength":60},"menstrualPhase":{"type":"string","enum":["Unknown","Follicular","Ovulation","Luteal","PostMenopausal"]},"isFasting":{"type":"boolean"},"hl7":{"type":"string","enum":["MSH|^~\\\\&|LAB|AHA|GEVITI|GEVITI|20250115000000||ORU^R01|BL-001|P|2.3\\rPID|1||E2E-1||Test^Patient||19800101|M\\rOBR|1|||^^^Geviti|||20250115\\rOBX|1|NM|1751-7^Albumin||4.2|g/dL|3.5-5.5|N|||F|||20250115\\rOBX|2|NM|2160-0^Creatinine||1.1|mg/dL|0.6-1.3|N|||F|||20250115\\r","MSH|^~\\\\&|LAB|AHA|GEVITI|GEVITI|20250615000000||ORU^R01|IM-001|P|2.3\\rPID|1||E2E-1||Test^Patient||19800101|F\\rOBR|1|||^^^Geviti|||20250615\\rOBX|1|NM|30522-7^hs-CRP||<0.2|mg/L|0-3|N|||F|||20250615\\rOBX|2|NM|ZZZ-1^Unmapped Marker||12|U/L||N|||F|||20250615\\r","not an hl7 message"]}}},"PatientTestElement":{"type":"object","required":["elementId","elementName","unit","comparison"],"properties":{"elementValue":{"type":"number"},"comparison":{"type":"string"},"unit":{"type":"string"},"elementId":{"type":"integer"},"elementName":{"type":"string"},"optimalRangeLow":{"type":"number"},"optimalRangeHigh":{"type":"number"},"standardRangeLow":{"type":"number"},"standardRangeHigh":{"type":"number"}}},"PatientTest":{"type":"object","required":["patientTestId","patientId","labProfileId","testDate","unitType","createdDate","lastUpdatedDate","practiceId","labId","results","menstrualPhase","isFasting"],"properties":{"patientTestId":{"type":"integer"},"patientId":{"type":"integer"},"labProfileId":{"type":"integer"},"testDate":{"type":"string"},"unitType":{"type":"string"},"createdDate":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"lastUpdatedDate":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"userId":{"type":["string","null"]},"practiceId":{"type":"string"},"labId":{"type":"integer"},"externalReference":{"type":["string","null"]},"externalMessageControlId":{"type":["string","null"]},"externalPatientTestId":{"type":["string","null"]},"results":{"type":"array","items":{"$ref":"#/components/schemas/PatientTestElement"}},"importLogs":{"type":["array","null"],"items":{"type":"object","properties":{"observationIdentifier":{"type":["string","null"]},"observationIdentifierText":{"type":["string","null"]},"status":{"type":["string","null"]}}}},"menstrualPhase":{"type":"string"},"isFasting":{"type":"boolean"}}},"ReportRequest":{"type":"object","required":["patientTestId","patientId","outputType"],"properties":{"patientTestId":{"type":"integer","enum":[700001,999999]},"patientId":{"type":"integer","enum":[100001,999999]},"unitType":{"type":"string","enum":["ConventionalUS"]},"practiceId":{"type":"string","enum":["3f0c0c43-7d2b-4b8e-9a50-9c1f0c6c0001"]},"outputType":{"type":"string","enum":["Json","Pdf","Xml"]},"theme":{"type":"string","enum":["Geviti"]},"themeId":{"type":"integer","enum":[21]},"recipientId":{"type":"string","enum":["15","0"]},"cultureCode":{"type":"string","enum":["en-US"]},"reports":{"type":"array","maxItems":3,"items":{"type":"string","enum":["1","2","3"]}},"addMarginForBinding":{"type":"boolean"},"userId":{"type":"string","maxLength":40}}},"Report":{"type":"object","required":["metadata","labs","elements","sections"],"properties":{"metadata":{"type":"object","required":["practiceId","patientId","patientTestId","recipient","reports","unitType"],"properties":{"practiceId":{"type":"string"},"patientId":{"type":"integer"},"patientTestId":{"type":"integer"},"recipient":{"type":"string"},"reports":{"type":"array","items":{"type":"string"}},"unitType":{"type":"string"}}},"labs":{"type":"array","items":{"$ref":"#/components/schemas/Lab"}},"elements":{"type":"array","items":{"$ref":"#/components/schemas/PatientTestElement"}},"sections":{"type":"array","items":{"type":"object","required":["name","reports"],"properties":{"name":{"type":"string"},"reports":{"type":"array","items":{"type":"object","required":["reportId","name","content"],"properties":{"reportId":{"type":"integer"},"name":{"type":"string"},"content":{"type":"object"}}}}}}}}},"WebhookRequest":{"type":"object","required":["entityEvents","webhookUrl"],"properties":{"entityEvents":{"type":"object","required":["PatientTest"],"properties":{"PatientTest":{"type":"array","minItems":1,"items":{"type":"string","enum":["Created","Updated","Deleted"]}}}},"webhookUrl":{"type":"string","enum":["https://backend.example.test/odx/webhook","https://staging.example.test/odx/webhook"]}}},"Webhook":{"type":"object","required":["partnerWebhookId","signingKey","createDate","entityEvents","webhookUrl"],"properties":{"partnerWebhookId":{"type":"integer"},"signingKey":{"type":"string","x-mockingbird-volatile":{"kind":"token"}},"createDate":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"entityEvents":{"type":"object","properties":{"PatientTest":{"type":"array","items":{"type":"string"}}}},"webhookUrl":{"type":"string"}}}}}}`);
|
|
2401
|
+
var operationIds = ["ListPartnerLabs", "ListElements", "CreatePatient", "UpdatePatient", "DeletePatient", "LinkPartnerUser", "ListPatients", "CreateTestResults", "CreatePatientTest", "UpdatePatientTest", "ListPatientTests", "GenerateFunctionalHealthReport", "ListWebhooks", "RegisterWebhook", "UpdateWebhook"];
|
|
2402
|
+
var supportedOperationIds = ["ListPartnerLabs", "ListElements", "CreatePatient", "UpdatePatient", "DeletePatient", "LinkPartnerUser", "ListPatients", "CreateTestResults", "CreatePatientTest", "UpdatePatientTest", "ListPatientTests", "GenerateFunctionalHealthReport", "ListWebhooks", "RegisterWebhook", "UpdateWebhook"];
|
|
2403
|
+
|
|
2404
|
+
// src/results.ts
|
|
2405
|
+
var parseObservations = (hl7) => {
|
|
2406
|
+
const segments = hl7.split(/\r\n|\r|\n/).filter((s) => s.trim() !== "");
|
|
2407
|
+
if (!segments[0]?.startsWith("MSH|")) return void 0;
|
|
2408
|
+
return segments.filter((segment) => segment.startsWith("OBX|")).map((segment) => {
|
|
2409
|
+
const fields = segment.split("|");
|
|
2410
|
+
const [code = "", text2 = ""] = (fields[3] ?? "").split("^");
|
|
2411
|
+
return {
|
|
2412
|
+
code: code.trim(),
|
|
2413
|
+
text: text2.trim(),
|
|
2414
|
+
value: (fields[5] ?? "").trim(),
|
|
2415
|
+
units: (fields[6] ?? "").trim(),
|
|
2416
|
+
range: (fields[7] ?? "").trim()
|
|
2417
|
+
};
|
|
2418
|
+
});
|
|
2419
|
+
};
|
|
2420
|
+
var VALUE = /^(<=|>=|<|>)?\s*(-?\d+(?:\.\d+)?)$/;
|
|
2421
|
+
var matchElement = (code, text2, gender2) => {
|
|
2422
|
+
const byCode = ELEMENTS.filter(
|
|
2423
|
+
(e) => e.codes.some((c) => c.toLowerCase() === code.toLowerCase()) || `EL${e.elementId}` === code.toUpperCase()
|
|
2424
|
+
);
|
|
2425
|
+
const candidates = byCode.length > 0 ? byCode : ELEMENTS.filter((e) => e.elementName.toLowerCase() === text2.toLowerCase());
|
|
2426
|
+
if (candidates.length <= 1) return candidates[0];
|
|
2427
|
+
const sex = gender2.toLowerCase() === "female" ? "Female" : "Male";
|
|
2428
|
+
return candidates.find((e) => e.elementGenderType === sex) ?? candidates[0];
|
|
2429
|
+
};
|
|
2430
|
+
var round = (n) => Math.round(n * 1e3) / 1e3;
|
|
2431
|
+
var resultFor = (element, value, comparison, unitType) => {
|
|
2432
|
+
const si = unitType.toUpperCase() === "SI";
|
|
2433
|
+
const k = si ? element.cuToSiConversionFactor : 1;
|
|
2434
|
+
return {
|
|
2435
|
+
elementValue: value,
|
|
2436
|
+
comparison,
|
|
2437
|
+
unit: si ? element.siUnit : element.cuUnit,
|
|
2438
|
+
elementId: element.elementId,
|
|
2439
|
+
elementName: element.elementName,
|
|
2440
|
+
optimalRangeLow: round(element.optimal[0] * k),
|
|
2441
|
+
optimalRangeHigh: round(element.optimal[1] * k),
|
|
2442
|
+
standardRangeLow: round(element.standard[0] * k),
|
|
2443
|
+
standardRangeHigh: round(element.standard[1] * k)
|
|
2444
|
+
};
|
|
2445
|
+
};
|
|
2446
|
+
var importObservations = (observations, gender2, unitType) => {
|
|
2447
|
+
const results = [];
|
|
2448
|
+
const importLogs = [];
|
|
2449
|
+
for (const obs of observations) {
|
|
2450
|
+
const log = (status) => importLogs.push({
|
|
2451
|
+
observationIdentifier: obs.code || null,
|
|
2452
|
+
observationIdentifierText: obs.text || null,
|
|
2453
|
+
status
|
|
2454
|
+
});
|
|
2455
|
+
const element = matchElement(obs.code, obs.text, gender2);
|
|
2456
|
+
if (!element) {
|
|
2457
|
+
log("NotMapped");
|
|
2458
|
+
continue;
|
|
2459
|
+
}
|
|
2460
|
+
const parsed = VALUE.exec(obs.value);
|
|
2461
|
+
if (!parsed) {
|
|
2462
|
+
log("InvalidValue");
|
|
2463
|
+
continue;
|
|
2464
|
+
}
|
|
2465
|
+
results.push(resultFor(element, Number(parsed[2]), parsed[1] ?? "", unitType));
|
|
2466
|
+
log("Imported");
|
|
2467
|
+
}
|
|
2468
|
+
return { results, importLogs };
|
|
2469
|
+
};
|
|
2470
|
+
var band = (r) => {
|
|
2471
|
+
if (r.elementValue < r.standardRangeLow) return "low";
|
|
2472
|
+
if (r.elementValue > r.standardRangeHigh) return "high";
|
|
2473
|
+
if (r.elementValue < r.optimalRangeLow) return "belowOptimal";
|
|
2474
|
+
if (r.elementValue > r.optimalRangeHigh) return "aboveOptimal";
|
|
2475
|
+
return "optimal";
|
|
2476
|
+
};
|
|
2477
|
+
|
|
2478
|
+
// src/report.ts
|
|
2479
|
+
var RECIPIENTS = {
|
|
2480
|
+
"15": "Patient (Geviti)",
|
|
2481
|
+
"16": "Practitioner (Geviti)",
|
|
2482
|
+
"1": "Patient",
|
|
2483
|
+
"2": "Practitioner"
|
|
2484
|
+
};
|
|
2485
|
+
var describe = (r) => `${r.elementName} ${r.elementValue} ${r.unit} is outside the optimal range ${r.optimalRangeLow}-${r.optimalRangeHigh}`;
|
|
2486
|
+
var jsonReport = (test, request) => {
|
|
2487
|
+
const results = test.results;
|
|
2488
|
+
const outside = results.filter((r) => band(r) !== "optimal");
|
|
2489
|
+
const above = results.filter((r) => ["aboveOptimal", "high"].includes(band(r)));
|
|
2490
|
+
const below = results.filter((r) => ["belowOptimal", "low"].includes(band(r)));
|
|
2491
|
+
const lab = LABS.find((l) => l.labId === test.labId) ?? {
|
|
2492
|
+
labId: test.labId,
|
|
2493
|
+
name: `Lab ${test.labId}`,
|
|
2494
|
+
isCurrentLab: false
|
|
2495
|
+
};
|
|
2496
|
+
const alarm = (r) => band(r) === "low" || band(r) === "high";
|
|
2497
|
+
const rationale = (r) => ({
|
|
2498
|
+
elementId: r.elementId,
|
|
2499
|
+
status: ["aboveOptimal", "high"].includes(band(r)) ? "Above Optimal" : "Below Optimal"
|
|
2500
|
+
});
|
|
2501
|
+
const probability = results.length === 0 ? 0 : Math.round(outside.length / results.length * 100);
|
|
2502
|
+
return {
|
|
2503
|
+
metadata: {
|
|
2504
|
+
practiceId: test.practiceId,
|
|
2505
|
+
patientId: test.patientId,
|
|
2506
|
+
patientTestId: test.patientTestId,
|
|
2507
|
+
recipient: RECIPIENTS[String(request.recipientId ?? "")] ?? "0",
|
|
2508
|
+
reports: Array.isArray(request.reports) ? request.reports.map(String) : [],
|
|
2509
|
+
unitType: typeof request.unitType === "string" ? request.unitType : test.unitType
|
|
2510
|
+
},
|
|
2511
|
+
labs: [lab],
|
|
2512
|
+
elements: results,
|
|
2513
|
+
sections: [
|
|
2514
|
+
{
|
|
2515
|
+
name: "Blood Test Results",
|
|
2516
|
+
reports: [
|
|
2517
|
+
{
|
|
2518
|
+
reportId: 1,
|
|
2519
|
+
name: "Blood Test Results",
|
|
2520
|
+
content: {
|
|
2521
|
+
tests: [{ labId: String(test.labId), testDate: test.testDate }],
|
|
2522
|
+
groups: [
|
|
2523
|
+
{
|
|
2524
|
+
name: "Results",
|
|
2525
|
+
results: results.map((r) => ({
|
|
2526
|
+
elementId: r.elementId,
|
|
2527
|
+
values: [{ comparison: r.comparison, value: r.elementValue, alarm: alarm(r) }]
|
|
2528
|
+
}))
|
|
2529
|
+
}
|
|
2530
|
+
],
|
|
2531
|
+
aboveOptimal: above.map((r) => ({
|
|
2532
|
+
elementId: r.elementId,
|
|
2533
|
+
value: r.elementValue,
|
|
2534
|
+
alarm: alarm(r),
|
|
2535
|
+
description: describe(r)
|
|
2536
|
+
})),
|
|
2537
|
+
belowOptimal: below.map((r) => ({
|
|
2538
|
+
elementId: r.elementId,
|
|
2539
|
+
value: r.elementValue,
|
|
2540
|
+
alarm: alarm(r),
|
|
2541
|
+
description: describe(r)
|
|
2542
|
+
}))
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
]
|
|
2546
|
+
},
|
|
2547
|
+
{
|
|
2548
|
+
name: "Functional Health",
|
|
2549
|
+
reports: [
|
|
2550
|
+
{
|
|
2551
|
+
reportId: 2,
|
|
2552
|
+
name: "Functional Body Systems",
|
|
2553
|
+
content: {
|
|
2554
|
+
conditions: [
|
|
2555
|
+
{
|
|
2556
|
+
conditionId: 1,
|
|
2557
|
+
name: "Overall Functional Health",
|
|
2558
|
+
probabilityOfDysfunction: probability,
|
|
2559
|
+
description: null,
|
|
2560
|
+
rationales: outside.map(rationale),
|
|
2561
|
+
elementIdsConsidered: results.map((r) => r.elementId),
|
|
2562
|
+
elementIdsMissing: []
|
|
2563
|
+
}
|
|
2564
|
+
]
|
|
2565
|
+
}
|
|
2566
|
+
},
|
|
2567
|
+
{
|
|
2568
|
+
reportId: 3,
|
|
2569
|
+
name: "Health Concerns",
|
|
2570
|
+
content: {
|
|
2571
|
+
healthConcerns: outside.length ? [
|
|
2572
|
+
{
|
|
2573
|
+
healthConcernId: 1,
|
|
2574
|
+
name: "Biomarkers outside optimal range",
|
|
2575
|
+
description: `${outside.length} of ${results.length} results are outside their optimal range.`,
|
|
2576
|
+
needOfSupportProbability: probability,
|
|
2577
|
+
rationales: outside.map(rationale)
|
|
2578
|
+
}
|
|
2579
|
+
] : []
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
]
|
|
2583
|
+
}
|
|
2584
|
+
]
|
|
2585
|
+
};
|
|
2586
|
+
};
|
|
2587
|
+
var pdfReport = (test) => {
|
|
2588
|
+
const text2 = `Functional Health Report - patient test ${test.patientTestId} (${test.results.length} results)`.replace(
|
|
2589
|
+
/[()\\]/g,
|
|
2590
|
+
""
|
|
2591
|
+
);
|
|
2592
|
+
const stream = `BT /F1 12 Tf 72 720 Td (${text2}) Tj ET`;
|
|
2593
|
+
const objects = [
|
|
2594
|
+
"<< /Type /Catalog /Pages 2 0 R >>",
|
|
2595
|
+
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
|
2596
|
+
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>",
|
|
2597
|
+
`<< /Length ${stream.length} >>
|
|
2598
|
+
stream
|
|
2599
|
+
${stream}
|
|
2600
|
+
endstream`,
|
|
2601
|
+
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"
|
|
2602
|
+
];
|
|
2603
|
+
let body = "%PDF-1.4\n";
|
|
2604
|
+
const offsets = [];
|
|
2605
|
+
objects.forEach((object, i) => {
|
|
2606
|
+
offsets.push(body.length);
|
|
2607
|
+
body += `${i + 1} 0 obj
|
|
2608
|
+
${object}
|
|
2609
|
+
endobj
|
|
2610
|
+
`;
|
|
2611
|
+
});
|
|
2612
|
+
const xref = body.length;
|
|
2613
|
+
body += `xref
|
|
2614
|
+
0 ${objects.length + 1}
|
|
2615
|
+
0000000000 65535 f
|
|
2616
|
+
`;
|
|
2617
|
+
for (const offset of offsets) body += `${String(offset).padStart(10, "0")} 00000 n
|
|
2618
|
+
`;
|
|
2619
|
+
body += `trailer
|
|
2620
|
+
<< /Size ${objects.length + 1} /Root 1 0 R >>
|
|
2621
|
+
startxref
|
|
2622
|
+
${xref}
|
|
2623
|
+
%%EOF
|
|
2624
|
+
`;
|
|
2625
|
+
return new TextEncoder().encode(body);
|
|
2626
|
+
};
|
|
2627
|
+
|
|
2628
|
+
// src/state.ts
|
|
2629
|
+
var DEFAULT_SETTINGS = { apiKeys: [], presetWebhook: null };
|
|
2630
|
+
var ID_BASES = { patient: 1e5, test: 7e5, webhook: 0, message: 0 };
|
|
2631
|
+
var OdxState = class {
|
|
2632
|
+
constructor(sqlite, namespace, seed) {
|
|
2633
|
+
this.namespace = namespace;
|
|
2634
|
+
this.seed = seed;
|
|
2635
|
+
this.patients = new Collection(sqlite, namespace, "patients");
|
|
2636
|
+
this.tests = new Collection(sqlite, namespace, "tests");
|
|
2637
|
+
this.webhooks = new Collection(sqlite, namespace, "webhooks");
|
|
2638
|
+
this.settings = new Collection(sqlite, namespace, "settings");
|
|
2639
|
+
this.counters = new Collection(sqlite, namespace, "counters");
|
|
2640
|
+
this.ensureSeeded();
|
|
2641
|
+
}
|
|
2642
|
+
namespace;
|
|
2643
|
+
seed;
|
|
2644
|
+
patients;
|
|
2645
|
+
tests;
|
|
2646
|
+
webhooks;
|
|
2647
|
+
settings;
|
|
2648
|
+
counters;
|
|
2649
|
+
/** Numeric ids per kind: patients 100001…, tests 700001…, webhooks 1…. */
|
|
2650
|
+
nextId(kind) {
|
|
2651
|
+
const next = (this.counters.get(kind) ?? 0) + 1;
|
|
2652
|
+
this.counters.insert(kind, next);
|
|
2653
|
+
return ID_BASES[kind] + next;
|
|
2654
|
+
}
|
|
2655
|
+
current() {
|
|
2656
|
+
return this.settings.get("settings") ?? { ...DEFAULT_SETTINGS, ...this.seed.settings };
|
|
2657
|
+
}
|
|
2658
|
+
update(patch) {
|
|
2659
|
+
const next = { ...this.current(), ...patch };
|
|
2660
|
+
this.settings.insert("settings", next);
|
|
2661
|
+
return next;
|
|
2662
|
+
}
|
|
2663
|
+
ensureSeeded() {
|
|
2664
|
+
if (!this.settings.has("settings")) {
|
|
2665
|
+
this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed.settings });
|
|
2666
|
+
}
|
|
2667
|
+
const preset = this.current().presetWebhook;
|
|
2668
|
+
if (preset && this.webhooks.count() === 0) {
|
|
2669
|
+
this.addWebhook(preset.url, ["Created", "Updated", "Deleted"], preset.signingKey);
|
|
2670
|
+
}
|
|
2671
|
+
}
|
|
2672
|
+
addWebhook(url, events, signingKey) {
|
|
2673
|
+
const id = this.nextId("webhook");
|
|
2674
|
+
const webhook = {
|
|
2675
|
+
partnerWebhookId: id,
|
|
2676
|
+
signingKey: signingKey ?? opaqueToken(`odx:signing-key:${this.namespace}:${id}`, 44),
|
|
2677
|
+
createDate: this.seed.timestamp(),
|
|
2678
|
+
entityEvents: { PatientTest: events },
|
|
2679
|
+
webhookUrl: url
|
|
2680
|
+
};
|
|
2681
|
+
this.webhooks.insert(String(id), webhook);
|
|
2682
|
+
return webhook;
|
|
2683
|
+
}
|
|
2684
|
+
patient(practiceId, patientId) {
|
|
2685
|
+
const found = this.patients.get(String(patientId));
|
|
2686
|
+
return found && found.practiceId === practiceId ? found : void 0;
|
|
2687
|
+
}
|
|
2688
|
+
};
|
|
2689
|
+
|
|
2690
|
+
// src/runtime.ts
|
|
2691
|
+
var SIGNATURE_HEADER = "optimaldx-signature";
|
|
2692
|
+
var signOdx = async (signingKey, body) => (await hmac("SHA-256", signingKey, body, "hex")).toUpperCase();
|
|
2693
|
+
var EMITTERS = ["CreatePatientTest", "UpdatePatientTest", "CreateTestResults"];
|
|
2694
|
+
var ODX_PRESETS = {
|
|
2695
|
+
wrong_length_signature: {
|
|
2696
|
+
description: "The webhook for the next test import carries a short signature: our guard's timingSafeEqual throws (a 500, known consumer bug)",
|
|
2697
|
+
rules: EMITTERS.map((operationId) => ({ operationId, effect: "wrong_length_signature" }))
|
|
2698
|
+
},
|
|
2699
|
+
bad_signature: {
|
|
2700
|
+
description: "The webhook for the next test import is signed with the wrong key (same length): our guard rejects it (403)",
|
|
2701
|
+
rules: EMITTERS.map((operationId) => ({ operationId, effect: "bad_signature" }))
|
|
2702
|
+
},
|
|
2703
|
+
empty_success: {
|
|
2704
|
+
description: "Calls answer 200 with an empty body (our client throws 'Empty success response received')",
|
|
2705
|
+
rules: [{ effect: "empty_success" }]
|
|
2706
|
+
},
|
|
2707
|
+
no_content: {
|
|
2708
|
+
description: "Calls answer 204 No Content (our client throws on 204)",
|
|
2709
|
+
rules: [{ effect: "no_content" }]
|
|
2710
|
+
},
|
|
2711
|
+
not_found: {
|
|
2712
|
+
description: "Every call answers 404 {Message}",
|
|
2713
|
+
rules: [{ status: 404, body: { Message: "Not Found" } }]
|
|
2714
|
+
},
|
|
2715
|
+
server_error: {
|
|
2716
|
+
description: "Every call answers 500 {Message: 'An error has occurred.'}",
|
|
2717
|
+
rules: [{ status: 500, body: { Message: "An error has occurred." } }]
|
|
2718
|
+
},
|
|
2719
|
+
slow: {
|
|
2720
|
+
description: "Every call is held back 3 s",
|
|
2721
|
+
rules: [{ latencyMs: 3e3 }]
|
|
2722
|
+
},
|
|
2723
|
+
webhook_duplicate: {
|
|
2724
|
+
description: "The next webhook is delivered twice (ODX's rapid-fire duplicates)",
|
|
2725
|
+
webhook: { mode: "duplicate" }
|
|
2726
|
+
},
|
|
2727
|
+
webhook_reorder: {
|
|
2728
|
+
description: "The next two webhooks arrive swapped",
|
|
2729
|
+
webhook: { mode: "reorder" }
|
|
2730
|
+
},
|
|
2731
|
+
webhook_drop: {
|
|
2732
|
+
description: "The next webhook is never delivered",
|
|
2733
|
+
webhook: { mode: "drop" }
|
|
2734
|
+
}
|
|
2735
|
+
};
|
|
2736
|
+
var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2737
|
+
var adminError3 = (status, message2) => json3(status, { error: { type: "mockingbird_admin", message: message2 } });
|
|
2738
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2739
|
+
var EVENTS = ["Created", "Updated", "Deleted"];
|
|
2740
|
+
var SIGNATURES = ["valid", "short", "bad"];
|
|
2741
|
+
var adminRoutes = (runtime) => ({
|
|
2742
|
+
"GET /patients": ({ namespace }) => json3(200, { patients: runtime.instance(namespace).patients() }),
|
|
2743
|
+
"GET /tests": ({ namespace }) => json3(200, {
|
|
2744
|
+
// Results are the mock's own output; no HL7 (PHI) is ever stored.
|
|
2745
|
+
tests: runtime.instance(namespace).tests()
|
|
2746
|
+
}),
|
|
2747
|
+
"POST /tests/:id/webhook": ({ params, body, namespace }) => {
|
|
2748
|
+
const input = isRecord4(body) ? body : {};
|
|
2749
|
+
const eventType = String(input.eventType ?? "Updated");
|
|
2750
|
+
const signature = String(input.signature ?? "valid");
|
|
2751
|
+
if (!EVENTS.includes(eventType))
|
|
2752
|
+
return adminError3(400, "eventType must be Created, Updated or Deleted");
|
|
2753
|
+
if (!SIGNATURES.includes(signature))
|
|
2754
|
+
return adminError3(400, "signature must be valid, short or bad");
|
|
2755
|
+
const event = runtime.instance(namespace).emit(params.id, eventType, signature);
|
|
2756
|
+
return event ? json3(202, event) : adminError3(404, `no patient test ${params.id}`);
|
|
2757
|
+
},
|
|
2758
|
+
"DELETE /tests/:id": ({ params, namespace }) => {
|
|
2759
|
+
const event = runtime.instance(namespace).emit(params.id, "Deleted");
|
|
2760
|
+
return event ? json3(200, event) : adminError3(404, `no patient test ${params.id}`);
|
|
2761
|
+
},
|
|
2762
|
+
"GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
|
|
2763
|
+
"PUT /settings": ({ body, namespace }) => {
|
|
2764
|
+
if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
|
|
2765
|
+
const patch = {};
|
|
2766
|
+
if (body.apiKeys !== void 0) {
|
|
2767
|
+
if (!Array.isArray(body.apiKeys)) return adminError3(400, "apiKeys: string[]");
|
|
2768
|
+
patch.apiKeys = body.apiKeys.map(String);
|
|
2769
|
+
}
|
|
2770
|
+
return json3(200, runtime.instance(namespace).state.update(patch));
|
|
2771
|
+
}
|
|
2772
|
+
});
|
|
2773
|
+
var createRuntime2 = (options = {}) => {
|
|
2774
|
+
const hub = createWebhookHub({
|
|
2775
|
+
// The message id carries the signature mode a fault preset asked for (`~short`, `~bad`).
|
|
2776
|
+
signer: signers.custom(async ({ messageId, body, secret }) => {
|
|
2777
|
+
if (!secret) return {};
|
|
2778
|
+
const signature = await signOdx(secret, body);
|
|
2779
|
+
if (messageId.endsWith("~short")) return { [SIGNATURE_HEADER]: signature.slice(0, 32) };
|
|
2780
|
+
if (messageId.endsWith("~bad")) {
|
|
2781
|
+
return { [SIGNATURE_HEADER]: await signOdx(`${secret}-wrong`, body) };
|
|
2782
|
+
}
|
|
2783
|
+
return { [SIGNATURE_HEADER]: signature };
|
|
2784
|
+
}),
|
|
2785
|
+
...options.retryDelaysMs ? { retryDelaysMs: options.retryDelaysMs } : {},
|
|
2786
|
+
...options.fetch ? { fetch: options.fetch } : {}
|
|
2787
|
+
});
|
|
2788
|
+
const presetWebhook = options.webhook ? {
|
|
2789
|
+
url: options.webhook.url,
|
|
2790
|
+
signingKey: options.webhook.signingKey ?? `odx_${opaqueToken(String(options.seed ?? 0), 32)}`
|
|
2791
|
+
} : null;
|
|
2792
|
+
let sequence = 0;
|
|
2793
|
+
const runtime = createRuntime({
|
|
2794
|
+
name: ODX_NAMESPACE,
|
|
2795
|
+
document,
|
|
2796
|
+
...options.sqlite ? { sqlite: options.sqlite } : {},
|
|
2797
|
+
...options.clock ? { clock: options.clock } : {},
|
|
2798
|
+
...options.seed !== void 0 ? { seed: options.seed } : {},
|
|
2799
|
+
...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
|
|
2800
|
+
...options.onLog ? { onLog: options.onLog } : {},
|
|
2801
|
+
credential: apiKeyCredential,
|
|
2802
|
+
presets: ODX_PRESETS,
|
|
2803
|
+
webhooks: hub,
|
|
2804
|
+
create: ({ sqlite, namespace, publicNamespace, clock }) => {
|
|
2805
|
+
const api = new OdxAPI({
|
|
2806
|
+
sqlite,
|
|
2807
|
+
namespace,
|
|
2808
|
+
now: clock.now,
|
|
2809
|
+
settings: { ...options.settings, ...presetWebhook ? { presetWebhook } : {} },
|
|
2810
|
+
onWebhook: (event, signature) => {
|
|
2811
|
+
hub.setEndpoints(
|
|
2812
|
+
publicNamespace,
|
|
2813
|
+
api.state.webhooks.list({ order: "oldest" }).map(({ value }) => ({
|
|
2814
|
+
id: `odx_webhook_${value.partnerWebhookId}`,
|
|
2815
|
+
url: value.webhookUrl,
|
|
2816
|
+
secret: value.signingKey,
|
|
2817
|
+
events: value.entityEvents.PatientTest
|
|
2818
|
+
}))
|
|
2819
|
+
);
|
|
2820
|
+
const suffix = signature === "valid" ? "" : `~${signature}`;
|
|
2821
|
+
hub.publish({
|
|
2822
|
+
namespace: publicNamespace,
|
|
2823
|
+
type: event.eventType,
|
|
2824
|
+
body: event,
|
|
2825
|
+
id: `${event.data.patientTestId}:${event.eventType}:${++sequence}${suffix}`
|
|
2826
|
+
});
|
|
2827
|
+
}
|
|
2828
|
+
});
|
|
2829
|
+
return api;
|
|
2830
|
+
},
|
|
2831
|
+
describe: () => ({ webhooks: presetWebhook ? "preset" : "registered" }),
|
|
2832
|
+
admin: adminRoutes
|
|
2833
|
+
});
|
|
2834
|
+
return Object.assign(runtime, { webhooks: hub });
|
|
2835
|
+
};
|
|
2836
|
+
|
|
2837
|
+
// src/index.ts
|
|
2838
|
+
var ODX_NAMESPACE = "odx";
|
|
2839
|
+
var apiKeyCredential = (request) => request.headers.get("apikey") ?? void 0;
|
|
2840
|
+
var MISSING_KEY = "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API.";
|
|
2841
|
+
var INVALID_KEY = "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription.";
|
|
2842
|
+
var message = (status, text2) => jsonRes(status, { Message: text2 });
|
|
2843
|
+
var problem = (errors) => jsonRes(400, {
|
|
2844
|
+
type: "https://tools.ietf.org/html/rfc7231#section-6.5.1",
|
|
2845
|
+
title: "One or more validation errors occurred.",
|
|
2846
|
+
status: 400,
|
|
2847
|
+
errors
|
|
2848
|
+
});
|
|
2849
|
+
var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2850
|
+
var text = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : null;
|
|
2851
|
+
var jsonBody = (context) => context.body.kind === "json" && isRecord5(context.body.value) ? context.body.value : void 0;
|
|
2852
|
+
var dotnetDate = (value) => {
|
|
2853
|
+
const raw = text(value);
|
|
2854
|
+
if (!raw) return null;
|
|
2855
|
+
const match = /^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}:\d{2}))?/.exec(raw);
|
|
2856
|
+
return match ? `${match[1]}T${match[2] ?? "00:00:00"}` : null;
|
|
2857
|
+
};
|
|
2858
|
+
var gender = (value) => {
|
|
2859
|
+
const raw = (text(value) ?? "").toLowerCase();
|
|
2860
|
+
return raw === "male" || raw === "m" ? "Male" : raw === "female" || raw === "f" ? "Female" : "Unknown";
|
|
2861
|
+
};
|
|
2862
|
+
var PHASES = ["Unknown", "Follicular", "Ovulation", "Luteal", "PostMenopausal"];
|
|
2863
|
+
var OdxAPI = class {
|
|
2864
|
+
app;
|
|
2865
|
+
sqlite;
|
|
2866
|
+
state;
|
|
2867
|
+
service;
|
|
2868
|
+
now;
|
|
2869
|
+
onWebhook;
|
|
2870
|
+
constructor(options = {}) {
|
|
2871
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
2872
|
+
const namespace = options.namespace ?? ODX_NAMESPACE;
|
|
2873
|
+
this.now = options.now ?? (() => Date.now());
|
|
2874
|
+
this.onWebhook = options.onWebhook;
|
|
2875
|
+
this.state = new OdxState(sqlite, namespace, {
|
|
2876
|
+
settings: options.settings ?? {},
|
|
2877
|
+
timestamp: () => this.iso()
|
|
2878
|
+
});
|
|
2879
|
+
const handlers = defineOperations({
|
|
2880
|
+
ListPartnerLabs: () => jsonRes(200, LABS),
|
|
2881
|
+
ListElements: (context) => this.listElements(context),
|
|
2882
|
+
CreatePatient: (context) => this.savePatient(context, void 0),
|
|
2883
|
+
UpdatePatient: (context) => this.savePatient(context, context.params.patientId),
|
|
2884
|
+
DeletePatient: (context) => this.deletePatient(context),
|
|
2885
|
+
LinkPartnerUser: (context) => this.linkPartner(context),
|
|
2886
|
+
ListPatients: (context) => this.listPatients(context),
|
|
2887
|
+
CreateTestResults: (context) => this.createTestResults(context),
|
|
2888
|
+
CreatePatientTest: (context) => this.saveHl7Test(context, void 0),
|
|
2889
|
+
UpdatePatientTest: (context) => this.saveHl7Test(context, context.params.patientTestId),
|
|
2890
|
+
ListPatientTests: (context) => this.listTests(context),
|
|
2891
|
+
GenerateFunctionalHealthReport: (context) => this.report(context),
|
|
2892
|
+
ListWebhooks: () => jsonRes(
|
|
2893
|
+
200,
|
|
2894
|
+
this.state.webhooks.list({ order: "oldest" }).map((row) => row.value)
|
|
2895
|
+
),
|
|
2896
|
+
RegisterWebhook: (context) => this.saveWebhook(context, void 0),
|
|
2897
|
+
UpdateWebhook: (context) => this.saveWebhook(context, context.params.partnerWebhookId)
|
|
2898
|
+
});
|
|
2899
|
+
this.service = createService({
|
|
2900
|
+
document,
|
|
2901
|
+
handlers,
|
|
2902
|
+
sqlite,
|
|
2903
|
+
namespace,
|
|
2904
|
+
now: this.now,
|
|
2905
|
+
notFound: () => jsonRes(404, { statusCode: 404, message: "Resource not found" }),
|
|
2906
|
+
onError: (error) => {
|
|
2907
|
+
throw error;
|
|
2908
|
+
},
|
|
2909
|
+
before: (context) => {
|
|
2910
|
+
const key = apiKeyCredential(context.request);
|
|
2911
|
+
if (!key) return jsonRes(401, { statusCode: 401, message: MISSING_KEY });
|
|
2912
|
+
const keys = this.state.current().apiKeys;
|
|
2913
|
+
if (keys.length > 0 && !keys.includes(key)) {
|
|
2914
|
+
return jsonRes(401, { statusCode: 401, message: INVALID_KEY });
|
|
2915
|
+
}
|
|
2916
|
+
const effect = (name) => faultEffect(context.request, name) !== void 0;
|
|
2917
|
+
if (effect("no_content")) return new Response(null, { status: 204 });
|
|
2918
|
+
if (effect("empty_success")) return new Response("", { status: 200 });
|
|
2919
|
+
return void 0;
|
|
2920
|
+
}
|
|
2921
|
+
});
|
|
2922
|
+
this.app = this.service.app;
|
|
2923
|
+
this.sqlite = this.service.sqlite;
|
|
2924
|
+
}
|
|
2925
|
+
fetch(request) {
|
|
2926
|
+
return this.service.fetch(request);
|
|
2927
|
+
}
|
|
2928
|
+
async reset() {
|
|
2929
|
+
await this.service.reset();
|
|
2930
|
+
this.state.ensureSeeded();
|
|
2931
|
+
}
|
|
2932
|
+
iso() {
|
|
2933
|
+
return new Date(this.now()).toISOString();
|
|
2934
|
+
}
|
|
2935
|
+
listElements(context) {
|
|
2936
|
+
const labId = Number(context.params.labId);
|
|
2937
|
+
if (!LABS.some((lab) => lab.labId === labId))
|
|
2938
|
+
return message(404, `Lab ${context.params.labId} not found.`);
|
|
2939
|
+
return jsonRes(
|
|
2940
|
+
200,
|
|
2941
|
+
ELEMENTS.map((element) => labElement(labId, element))
|
|
2942
|
+
);
|
|
2943
|
+
}
|
|
2944
|
+
savePatient(context, patientId) {
|
|
2945
|
+
const practiceId = context.params.practiceId;
|
|
2946
|
+
const existing = patientId === void 0 ? void 0 : this.state.patient(practiceId, patientId);
|
|
2947
|
+
if (patientId !== void 0 && !existing) return message(404, "Patient not found.");
|
|
2948
|
+
const body = jsonBody(context);
|
|
2949
|
+
if (!body) return problem({ "": ["A non-empty request body is required."] });
|
|
2950
|
+
const errors = {};
|
|
2951
|
+
for (const [key, label] of [
|
|
2952
|
+
["firstName", "FirstName"],
|
|
2953
|
+
["lastName", "LastName"],
|
|
2954
|
+
["email", "Email"]
|
|
2955
|
+
]) {
|
|
2956
|
+
if (!text(body[key])?.trim()) errors[label] = [`The ${label} field is required.`];
|
|
2957
|
+
}
|
|
2958
|
+
if (body.dateOfBirth !== void 0 && body.dateOfBirth !== null && !dotnetDate(body.dateOfBirth)) {
|
|
2959
|
+
errors.DateOfBirth = ["The value is not a valid date."];
|
|
2960
|
+
}
|
|
2961
|
+
if (Object.keys(errors).length > 0) return problem(errors);
|
|
2962
|
+
const now = this.iso();
|
|
2963
|
+
const patient = {
|
|
2964
|
+
patientId: existing?.patientId ?? this.state.nextId("patient"),
|
|
2965
|
+
practiceId,
|
|
2966
|
+
createdDate: existing?.createdDate ?? now,
|
|
2967
|
+
lastUpdatedDate: now,
|
|
2968
|
+
userTitle: null,
|
|
2969
|
+
userFirstName: null,
|
|
2970
|
+
userLastName: null,
|
|
2971
|
+
firstName: text(body.firstName),
|
|
2972
|
+
lastName: text(body.lastName),
|
|
2973
|
+
nickname: text(body.nickname),
|
|
2974
|
+
dateOfBirth: dotnetDate(body.dateOfBirth),
|
|
2975
|
+
gender: gender(body.gender),
|
|
2976
|
+
homePhone: null,
|
|
2977
|
+
workPhone: null,
|
|
2978
|
+
mobile: null,
|
|
2979
|
+
email: text(body.email),
|
|
2980
|
+
address: null,
|
|
2981
|
+
address2: null,
|
|
2982
|
+
address3: null,
|
|
2983
|
+
city: null,
|
|
2984
|
+
province: null,
|
|
2985
|
+
postalCode: null,
|
|
2986
|
+
country: null,
|
|
2987
|
+
userId: text(body.userId),
|
|
2988
|
+
workspaceId: typeof body.workspaceId === "number" ? body.workspaceId : 0,
|
|
2989
|
+
partnerUserId: existing?.partnerUserId ?? null
|
|
2990
|
+
};
|
|
2991
|
+
this.state.patients.insert(String(patient.patientId), patient);
|
|
2992
|
+
return annotateResponse(jsonRes(200, publicPatient(patient)), {
|
|
2993
|
+
ids: { patientId: String(patient.patientId) }
|
|
2994
|
+
});
|
|
2995
|
+
}
|
|
2996
|
+
deletePatient(context) {
|
|
2997
|
+
const patient = this.state.patient(
|
|
2998
|
+
context.params.practiceId,
|
|
2999
|
+
context.params.patientId
|
|
3000
|
+
);
|
|
3001
|
+
if (!patient) return message(404, "Patient not found.");
|
|
3002
|
+
this.state.patients.delete(String(patient.patientId));
|
|
3003
|
+
for (const row of this.state.tests.list({ where: (t) => t.patientId === patient.patientId })) {
|
|
3004
|
+
this.state.tests.delete(row.id);
|
|
3005
|
+
}
|
|
3006
|
+
return annotateResponse(new Response(null, { status: 204 }), {
|
|
3007
|
+
ids: { patientId: String(patient.patientId) }
|
|
3008
|
+
});
|
|
3009
|
+
}
|
|
3010
|
+
linkPartner(context) {
|
|
3011
|
+
const patient = this.state.patient(
|
|
3012
|
+
context.params.practiceId,
|
|
3013
|
+
context.params.patientId
|
|
3014
|
+
);
|
|
3015
|
+
if (!patient) return message(404, "Patient not found.");
|
|
3016
|
+
this.state.patients.update(String(patient.patientId), {
|
|
3017
|
+
...patient,
|
|
3018
|
+
partnerUserId: context.params.localUserId,
|
|
3019
|
+
lastUpdatedDate: this.iso()
|
|
3020
|
+
});
|
|
3021
|
+
return annotateResponse(jsonRes(200, true), { ids: { patientId: String(patient.patientId) } });
|
|
3022
|
+
}
|
|
3023
|
+
listPatients(context) {
|
|
3024
|
+
const practiceId = context.params.practiceId;
|
|
3025
|
+
const q = context.url.searchParams;
|
|
3026
|
+
const filters = {
|
|
3027
|
+
email: q.get("email"),
|
|
3028
|
+
firstName: q.get("firstName"),
|
|
3029
|
+
lastName: q.get("lastName"),
|
|
3030
|
+
dateOfBirth: q.get("dateOfBirth")
|
|
3031
|
+
};
|
|
3032
|
+
const searching = Object.values(filters).some((v) => v);
|
|
3033
|
+
const eq = (a, b) => !b || (a ?? "").toLowerCase() === b.toLowerCase();
|
|
3034
|
+
const rows = this.state.patients.list({ where: (p) => p.practiceId === practiceId, order: "oldest" }).map((row) => row.value).filter(
|
|
3035
|
+
(p) => eq(p.email, filters.email) && eq(p.firstName, filters.firstName) && eq(p.lastName, filters.lastName) && (!filters.dateOfBirth || p.dateOfBirth?.slice(0, 10) === dotnetDate(filters.dateOfBirth)?.slice(0, 10))
|
|
3036
|
+
);
|
|
3037
|
+
if (searching && rows.length === 0) return message(404, "No patients found.");
|
|
3038
|
+
return jsonRes(200, rows.map(publicPatient));
|
|
3039
|
+
}
|
|
3040
|
+
listTests(context) {
|
|
3041
|
+
const patient = this.state.patient(
|
|
3042
|
+
context.params.practiceId,
|
|
3043
|
+
context.params.patientId
|
|
3044
|
+
);
|
|
3045
|
+
if (!patient) return message(404, "Patient not found.");
|
|
3046
|
+
return jsonRes(
|
|
3047
|
+
200,
|
|
3048
|
+
this.state.tests.list({ where: (t) => t.patientId === patient.patientId, order: "oldest" }).map((row) => row.value)
|
|
3049
|
+
);
|
|
3050
|
+
}
|
|
3051
|
+
testBase(body, errors) {
|
|
3052
|
+
const labId = Number(body.labId);
|
|
3053
|
+
if (!Number.isInteger(labId) || !LABS.some((lab) => lab.labId === labId)) {
|
|
3054
|
+
errors.LabId = [`Lab ${text(body.labId) ?? ""} is not available to this partner.`];
|
|
3055
|
+
}
|
|
3056
|
+
if (typeof body.labProfileId !== "number")
|
|
3057
|
+
errors.LabProfileId = ["The LabProfileId field is required."];
|
|
3058
|
+
const testDate = dotnetDate(body.testDate);
|
|
3059
|
+
if (!testDate) errors.TestDate = ["The TestDate field is required."];
|
|
3060
|
+
const unitType = text(body.unitType) ?? "";
|
|
3061
|
+
if (!["ConventionalUS", "SI"].includes(unitType))
|
|
3062
|
+
errors.UnitType = ["The UnitType field is invalid."];
|
|
3063
|
+
const phase = text(body.menstrualPhase) ?? "Unknown";
|
|
3064
|
+
if (!PHASES.includes(phase)) errors.MenstrualPhase = ["The MenstrualPhase field is invalid."];
|
|
3065
|
+
return { labId, testDate: testDate ?? "", unitType, phase };
|
|
3066
|
+
}
|
|
3067
|
+
createTestResults(context) {
|
|
3068
|
+
const practiceId = context.params.practiceId;
|
|
3069
|
+
const patient = this.state.patient(practiceId, context.params.patientId);
|
|
3070
|
+
if (!patient) return message(404, "Patient not found.");
|
|
3071
|
+
const body = jsonBody(context);
|
|
3072
|
+
if (!body) return problem({ "": ["A non-empty request body is required."] });
|
|
3073
|
+
const errors = {};
|
|
3074
|
+
const base = this.testBase(body, errors);
|
|
3075
|
+
if (!Array.isArray(body.results)) errors.Results = ["The Results field is required."];
|
|
3076
|
+
if (Object.keys(errors).length > 0) return problem(errors);
|
|
3077
|
+
const results = [];
|
|
3078
|
+
const importLogs = [];
|
|
3079
|
+
for (const raw of body.results) {
|
|
3080
|
+
const item = isRecord5(raw) ? raw : {};
|
|
3081
|
+
const element = ELEMENTS.find((e) => e.elementId === item.elementId);
|
|
3082
|
+
if (!element || typeof item.value !== "number") {
|
|
3083
|
+
importLogs.push({
|
|
3084
|
+
observationIdentifier: text(item.elementId),
|
|
3085
|
+
observationIdentifierText: null,
|
|
3086
|
+
status: element ? "InvalidValue" : "NotMapped"
|
|
3087
|
+
});
|
|
3088
|
+
continue;
|
|
3089
|
+
}
|
|
3090
|
+
results.push(resultFor(element, item.value, text(item.comparison) ?? "", base.unitType));
|
|
3091
|
+
importLogs.push({
|
|
3092
|
+
observationIdentifier: String(element.elementId),
|
|
3093
|
+
observationIdentifierText: element.elementName,
|
|
3094
|
+
status: "Imported"
|
|
3095
|
+
});
|
|
3096
|
+
}
|
|
3097
|
+
const test = this.storeTest(patient, body, base, { results, importLogs }, void 0);
|
|
3098
|
+
return this.testResponse(context, test, "Created");
|
|
3099
|
+
}
|
|
3100
|
+
saveHl7Test(context, patientTestId) {
|
|
3101
|
+
const practiceId = context.params.practiceId;
|
|
3102
|
+
const patient = this.state.patient(practiceId, context.params.patientId);
|
|
3103
|
+
if (!patient) return message(404, "Patient not found.");
|
|
3104
|
+
const existing = patientTestId === void 0 ? void 0 : this.state.tests.get(patientTestId);
|
|
3105
|
+
if (patientTestId !== void 0 && (!existing || existing.patientId !== patient.patientId)) {
|
|
3106
|
+
return message(404, "Patient test not found.");
|
|
3107
|
+
}
|
|
3108
|
+
const body = jsonBody(context);
|
|
3109
|
+
if (!body) return problem({ "": ["A non-empty request body is required."] });
|
|
3110
|
+
const errors = {};
|
|
3111
|
+
const base = this.testBase(body, errors);
|
|
3112
|
+
const observations = parseObservations(text(body.hl7) ?? "");
|
|
3113
|
+
if (!observations) errors.Hl7 = ["The HL7 message could not be parsed (missing MSH segment)."];
|
|
3114
|
+
else if (observations.length === 0) errors.Hl7 = ["The HL7 message contains no OBX segments."];
|
|
3115
|
+
if (Object.keys(errors).length > 0) return problem(errors);
|
|
3116
|
+
const imported = importObservations(observations ?? [], patient.gender, base.unitType);
|
|
3117
|
+
const test = this.storeTest(patient, body, base, imported, existing);
|
|
3118
|
+
return this.testResponse(context, test, existing ? "Updated" : "Created");
|
|
3119
|
+
}
|
|
3120
|
+
storeTest(patient, body, base, imported, existing) {
|
|
3121
|
+
const now = this.iso();
|
|
3122
|
+
const test = {
|
|
3123
|
+
patientTestId: existing?.patientTestId ?? this.state.nextId("test"),
|
|
3124
|
+
patientId: patient.patientId,
|
|
3125
|
+
labProfileId: body.labProfileId,
|
|
3126
|
+
testDate: base.testDate,
|
|
3127
|
+
unitType: base.unitType,
|
|
3128
|
+
createdDate: existing?.createdDate ?? now,
|
|
3129
|
+
lastUpdatedDate: now,
|
|
3130
|
+
userId: text(body.userId),
|
|
3131
|
+
practiceId: patient.practiceId,
|
|
3132
|
+
labId: base.labId,
|
|
3133
|
+
externalReference: text(body.externalReference),
|
|
3134
|
+
externalMessageControlId: text(body.externalMessageControlId),
|
|
3135
|
+
externalPatientTestId: text(body.externalPatientTestId),
|
|
3136
|
+
results: imported.results,
|
|
3137
|
+
importLogs: imported.importLogs,
|
|
3138
|
+
menstrualPhase: base.phase,
|
|
3139
|
+
isFasting: body.isFasting === true
|
|
3140
|
+
};
|
|
3141
|
+
this.state.tests.insert(String(test.patientTestId), test);
|
|
3142
|
+
return test;
|
|
3143
|
+
}
|
|
3144
|
+
testResponse(context, test, eventType) {
|
|
3145
|
+
const signature = faultEffect(context.request, "wrong_length_signature") !== void 0 ? "short" : faultEffect(context.request, "bad_signature") !== void 0 ? "bad" : "valid";
|
|
3146
|
+
this.emit(test.patientTestId, eventType, signature);
|
|
3147
|
+
return annotateResponse(jsonRes(200, test), {
|
|
3148
|
+
ids: { patientId: String(test.patientId), patientTestId: String(test.patientTestId) }
|
|
3149
|
+
});
|
|
3150
|
+
}
|
|
3151
|
+
/** Emit a PatientTest webhook for a stored test (tests, the admin route, `Deleted`). */
|
|
3152
|
+
emit(patientTestId, eventType, signature = "valid") {
|
|
3153
|
+
const test = this.state.tests.get(String(patientTestId));
|
|
3154
|
+
if (!test) return void 0;
|
|
3155
|
+
const event = { entityType: "PatientTest", eventType, data: test };
|
|
3156
|
+
this.onWebhook?.(event, signature);
|
|
3157
|
+
if (eventType === "Deleted") this.state.tests.delete(String(test.patientTestId));
|
|
3158
|
+
return event;
|
|
3159
|
+
}
|
|
3160
|
+
report(context) {
|
|
3161
|
+
const body = jsonBody(context);
|
|
3162
|
+
if (!body) return problem({ "": ["A non-empty request body is required."] });
|
|
3163
|
+
const output = (text(body.outputType) ?? "").toLowerCase();
|
|
3164
|
+
if (output !== "json" && output !== "pdf") {
|
|
3165
|
+
return problem({
|
|
3166
|
+
OutputType: [`The value '${text(body.outputType) ?? ""}' is not valid for OutputType.`]
|
|
3167
|
+
});
|
|
3168
|
+
}
|
|
3169
|
+
const test = this.state.tests.get(String(body.patientTestId));
|
|
3170
|
+
if (!test || body.patientId !== void 0 && test.patientId !== Number(body.patientId)) {
|
|
3171
|
+
return message(404, "Patient test not found.");
|
|
3172
|
+
}
|
|
3173
|
+
const ids = { patientId: String(test.patientId), patientTestId: String(test.patientTestId) };
|
|
3174
|
+
if (output === "pdf") {
|
|
3175
|
+
const pdf = pdfReport(test);
|
|
3176
|
+
return annotateResponse(
|
|
3177
|
+
new Response(pdf, {
|
|
3178
|
+
status: 200,
|
|
3179
|
+
headers: { "content-type": "application/pdf", "content-length": String(pdf.byteLength) }
|
|
3180
|
+
}),
|
|
3181
|
+
{ ids }
|
|
3182
|
+
);
|
|
3183
|
+
}
|
|
3184
|
+
return annotateResponse(jsonRes(200, jsonReport(test, body)), { ids });
|
|
3185
|
+
}
|
|
3186
|
+
saveWebhook(context, id) {
|
|
3187
|
+
const existing = id === void 0 ? void 0 : this.state.webhooks.get(id);
|
|
3188
|
+
if (id !== void 0 && !existing) return message(404, "Webhook not found.");
|
|
3189
|
+
const body = jsonBody(context);
|
|
3190
|
+
const url = text(body?.webhookUrl);
|
|
3191
|
+
const events = isRecord5(body?.entityEvents) ? body.entityEvents.PatientTest : void 0;
|
|
3192
|
+
const errors = {};
|
|
3193
|
+
let valid = false;
|
|
3194
|
+
try {
|
|
3195
|
+
valid = url !== null && ["http:", "https:"].includes(new URL(url).protocol);
|
|
3196
|
+
} catch {
|
|
3197
|
+
valid = false;
|
|
3198
|
+
}
|
|
3199
|
+
if (!valid) errors.WebhookUrl = ["The WebhookUrl field is not a valid URL."];
|
|
3200
|
+
if (!Array.isArray(events) || events.length === 0 || events.some((e) => !["Created", "Updated", "Deleted"].includes(String(e)))) {
|
|
3201
|
+
errors["EntityEvents.PatientTest"] = [
|
|
3202
|
+
"PatientTest events must be Created, Updated or Deleted."
|
|
3203
|
+
];
|
|
3204
|
+
}
|
|
3205
|
+
if (Object.keys(errors).length > 0) return problem(errors);
|
|
3206
|
+
const webhook = existing ? {
|
|
3207
|
+
...existing,
|
|
3208
|
+
webhookUrl: url,
|
|
3209
|
+
entityEvents: { PatientTest: events.map(String) }
|
|
3210
|
+
} : this.state.addWebhook(url, events.map(String));
|
|
3211
|
+
this.state.webhooks.insert(String(webhook.partnerWebhookId), webhook);
|
|
3212
|
+
return annotateResponse(jsonRes(200, webhook), {
|
|
3213
|
+
ids: { partnerWebhookId: String(webhook.partnerWebhookId) }
|
|
3214
|
+
});
|
|
3215
|
+
}
|
|
3216
|
+
patients() {
|
|
3217
|
+
return this.state.patients.list({ order: "oldest" }).map((row) => row.value);
|
|
3218
|
+
}
|
|
3219
|
+
tests() {
|
|
3220
|
+
return this.state.tests.list({ order: "oldest" }).map((row) => row.value);
|
|
3221
|
+
}
|
|
3222
|
+
};
|
|
3223
|
+
var publicPatient = ({ partnerUserId: _partner, ...patient }) => patient;
|
|
3224
|
+
|
|
3225
|
+
export {
|
|
3226
|
+
LABS,
|
|
3227
|
+
ELEMENTS,
|
|
3228
|
+
document,
|
|
3229
|
+
operationIds,
|
|
3230
|
+
supportedOperationIds,
|
|
3231
|
+
parseObservations,
|
|
3232
|
+
matchElement,
|
|
3233
|
+
DEFAULT_SETTINGS,
|
|
3234
|
+
SIGNATURE_HEADER,
|
|
3235
|
+
signOdx,
|
|
3236
|
+
ODX_PRESETS,
|
|
3237
|
+
createRuntime2 as createRuntime,
|
|
3238
|
+
ODX_NAMESPACE,
|
|
3239
|
+
apiKeyCredential,
|
|
3240
|
+
OdxAPI
|
|
3241
|
+
};
|
|
3242
|
+
//# sourceMappingURL=chunk-OYDT3HEE.js.map
|