@crvouga/mockingbird-service-makor-cpg 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 +170 -0
- package/dist/chunk-326MF4C4.js +2896 -0
- package/dist/chunk-326MF4C4.js.map +7 -0
- package/dist/chunk-5QVJOQAT.js +358 -0
- package/dist/chunk-5QVJOQAT.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +1006 -0
- package/dist/index.js +31 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1320 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +88 -0
|
@@ -0,0 +1,2896 @@
|
|
|
1
|
+
// ../core/dist/clock.js
|
|
2
|
+
var createClock = (source = Date.now) => {
|
|
3
|
+
let offsetMs = 0;
|
|
4
|
+
let frozenAt;
|
|
5
|
+
const now = () => frozenAt ?? source() + offsetMs;
|
|
6
|
+
return {
|
|
7
|
+
now,
|
|
8
|
+
set: (epochMs) => {
|
|
9
|
+
if (frozenAt !== void 0)
|
|
10
|
+
frozenAt = epochMs;
|
|
11
|
+
else
|
|
12
|
+
offsetMs = epochMs - source();
|
|
13
|
+
},
|
|
14
|
+
advance: (deltaMs) => {
|
|
15
|
+
if (frozenAt !== void 0)
|
|
16
|
+
frozenAt += deltaMs;
|
|
17
|
+
else
|
|
18
|
+
offsetMs += deltaMs;
|
|
19
|
+
},
|
|
20
|
+
freeze: () => {
|
|
21
|
+
frozenAt = now();
|
|
22
|
+
},
|
|
23
|
+
unfreeze: () => {
|
|
24
|
+
if (frozenAt === void 0)
|
|
25
|
+
return;
|
|
26
|
+
offsetMs = frozenAt - source();
|
|
27
|
+
frozenAt = void 0;
|
|
28
|
+
},
|
|
29
|
+
reset: () => {
|
|
30
|
+
offsetMs = 0;
|
|
31
|
+
frozenAt = void 0;
|
|
32
|
+
},
|
|
33
|
+
state: () => ({ now: now(), frozen: frozenAt !== void 0, offsetMs })
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// ../core/dist/collection.js
|
|
38
|
+
var Collection = class {
|
|
39
|
+
sqlite;
|
|
40
|
+
namespace;
|
|
41
|
+
name;
|
|
42
|
+
constructor(sqlite, namespace, name) {
|
|
43
|
+
this.sqlite = sqlite;
|
|
44
|
+
this.namespace = namespace;
|
|
45
|
+
this.name = name;
|
|
46
|
+
}
|
|
47
|
+
bumpCollectionSeq() {
|
|
48
|
+
const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'").get(this.namespace, this.name);
|
|
49
|
+
const next = (row?.value ?? 0) + 1;
|
|
50
|
+
this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)
|
|
51
|
+
ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, this.name, next);
|
|
52
|
+
return next;
|
|
53
|
+
}
|
|
54
|
+
nextSequence() {
|
|
55
|
+
return this.sqlite.transaction(() => this.bumpCollectionSeq());
|
|
56
|
+
}
|
|
57
|
+
get(id) {
|
|
58
|
+
const row = this.sqlite.prepare("SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
|
|
59
|
+
if (!row)
|
|
60
|
+
return void 0;
|
|
61
|
+
return JSON.parse(row.value).value;
|
|
62
|
+
}
|
|
63
|
+
has(id) {
|
|
64
|
+
const row = this.sqlite.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
|
|
65
|
+
return row !== void 0;
|
|
66
|
+
}
|
|
67
|
+
/** Insert a new record, assigning it the next sequence number. */
|
|
68
|
+
insert(id, value) {
|
|
69
|
+
return this.sqlite.transaction(() => {
|
|
70
|
+
const seq = this.bumpCollectionSeq();
|
|
71
|
+
const stored = { seq, value };
|
|
72
|
+
this.sqlite.prepare(`INSERT INTO mockingbird_records (namespace, collection, id, seq, value)
|
|
73
|
+
VALUES (?, ?, ?, ?, ?)
|
|
74
|
+
ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`).run(this.namespace, this.name, id, seq, JSON.stringify(stored));
|
|
75
|
+
return stored;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/** Replace an existing record's value, keeping its position. */
|
|
79
|
+
update(id, value) {
|
|
80
|
+
return this.sqlite.transaction(() => {
|
|
81
|
+
const row = this.sqlite.prepare("SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.name, id);
|
|
82
|
+
if (!row)
|
|
83
|
+
return void 0;
|
|
84
|
+
const stored = { seq: row.seq, value };
|
|
85
|
+
this.sqlite.prepare("UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?").run(JSON.stringify(stored), this.namespace, this.name, id);
|
|
86
|
+
return stored;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
delete(id) {
|
|
90
|
+
const result = this.sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").run(this.namespace, this.name, id);
|
|
91
|
+
return result.changes > 0;
|
|
92
|
+
}
|
|
93
|
+
/** How many records the collection holds, without reading them. */
|
|
94
|
+
count() {
|
|
95
|
+
const row = this.sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?").get(this.namespace, this.name);
|
|
96
|
+
return Number(row?.n ?? 0);
|
|
97
|
+
}
|
|
98
|
+
list(options = {}) {
|
|
99
|
+
const rows = this.sqlite.prepare("SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?").all(this.namespace, this.name);
|
|
100
|
+
const out = [];
|
|
101
|
+
for (const row of rows) {
|
|
102
|
+
const stored = JSON.parse(row.value);
|
|
103
|
+
if (options.where && !options.where(stored.value, stored.seq))
|
|
104
|
+
continue;
|
|
105
|
+
out.push({ id: row.id, seq: stored.seq, value: stored.value });
|
|
106
|
+
}
|
|
107
|
+
out.sort((a, b) => options.order === "oldest" ? a.seq - b.seq : b.seq - a.seq);
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
// ../core/dist/control.js
|
|
113
|
+
var HEALTH_PATH = "/health";
|
|
114
|
+
var ADMIN_PREFIX = "/__admin";
|
|
115
|
+
var ADMIN_KEY_HEADER = "x-mockingbird-admin-key";
|
|
116
|
+
var NAMESPACE_HEADER = "x-mockingbird-namespace";
|
|
117
|
+
var json = (status, body) => new Response(JSON.stringify(body), {
|
|
118
|
+
status,
|
|
119
|
+
headers: { "content-type": "application/json" }
|
|
120
|
+
});
|
|
121
|
+
var adminError = (status, message) => json(status, { error: { type: "mockingbird_admin", message } });
|
|
122
|
+
var UNITS = {
|
|
123
|
+
ms: 1,
|
|
124
|
+
s: 1e3,
|
|
125
|
+
m: 6e4,
|
|
126
|
+
h: 36e5,
|
|
127
|
+
d: 864e5
|
|
128
|
+
};
|
|
129
|
+
var parseDuration = (value) => {
|
|
130
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
131
|
+
return value;
|
|
132
|
+
if (typeof value !== "string")
|
|
133
|
+
return void 0;
|
|
134
|
+
const match = /^(-?\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(value.trim());
|
|
135
|
+
if (!match)
|
|
136
|
+
return void 0;
|
|
137
|
+
return Number(match[1]) * UNITS[match[2]];
|
|
138
|
+
};
|
|
139
|
+
var parseInstant = (value) => {
|
|
140
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
141
|
+
return value;
|
|
142
|
+
if (typeof value !== "string")
|
|
143
|
+
return void 0;
|
|
144
|
+
const parsed = Date.parse(value);
|
|
145
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
146
|
+
};
|
|
147
|
+
var matchRoute = (pattern, path) => {
|
|
148
|
+
const want = pattern.split("/").filter(Boolean);
|
|
149
|
+
const have = path.split("/").filter(Boolean);
|
|
150
|
+
if (want.length !== have.length)
|
|
151
|
+
return void 0;
|
|
152
|
+
const params = {};
|
|
153
|
+
for (let i = 0; i < want.length; i++) {
|
|
154
|
+
const segment = want[i];
|
|
155
|
+
const actual = have[i];
|
|
156
|
+
if (segment.startsWith(":"))
|
|
157
|
+
params[segment.slice(1)] = decodeURIComponent(actual);
|
|
158
|
+
else if (segment !== actual)
|
|
159
|
+
return void 0;
|
|
160
|
+
}
|
|
161
|
+
return params;
|
|
162
|
+
};
|
|
163
|
+
var readJson = async (request) => {
|
|
164
|
+
const text = await request.text();
|
|
165
|
+
if (text.trim() === "")
|
|
166
|
+
return void 0;
|
|
167
|
+
return JSON.parse(text);
|
|
168
|
+
};
|
|
169
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
170
|
+
var createControlPlane = (context) => {
|
|
171
|
+
const snapshots = /* @__PURE__ */ new Map();
|
|
172
|
+
let snapshotCounter = 0;
|
|
173
|
+
const headerNamespace = (request) => request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace;
|
|
174
|
+
const adminNamespace = (request, url) => url.searchParams.get("namespace") ?? headerNamespace(request);
|
|
175
|
+
const builtin = {
|
|
176
|
+
"GET /": () => json(200, {
|
|
177
|
+
service: context.name,
|
|
178
|
+
routes: [...Object.keys(builtin), ...Object.keys(context.routes)].sort()
|
|
179
|
+
}),
|
|
180
|
+
"POST /reset": async ({ url, namespace }) => {
|
|
181
|
+
const target = url.searchParams.get("all") === "1" ? "*" : namespace;
|
|
182
|
+
await context.reset(target);
|
|
183
|
+
return json(200, { status: "ok", reset: target === "*" ? context.namespaces() : [target] });
|
|
184
|
+
},
|
|
185
|
+
"GET /namespaces": () => json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),
|
|
186
|
+
"GET /clock": () => json(200, context.clock.state()),
|
|
187
|
+
"POST /clock": ({ body }) => {
|
|
188
|
+
if (!isRecord(body))
|
|
189
|
+
return adminError(400, "expected a JSON object");
|
|
190
|
+
if (body.reset === true)
|
|
191
|
+
context.clock.reset();
|
|
192
|
+
if (body.set !== void 0) {
|
|
193
|
+
const instant = parseInstant(body.set);
|
|
194
|
+
if (instant === void 0)
|
|
195
|
+
return adminError(400, "set: expected epoch ms or ISO-8601");
|
|
196
|
+
context.clock.set(instant);
|
|
197
|
+
}
|
|
198
|
+
if (body.advance !== void 0) {
|
|
199
|
+
const delta = parseDuration(body.advance);
|
|
200
|
+
if (delta === void 0)
|
|
201
|
+
return adminError(400, 'advance: expected ms or "15m"-style');
|
|
202
|
+
context.clock.advance(delta);
|
|
203
|
+
}
|
|
204
|
+
if (body.freeze === true)
|
|
205
|
+
context.clock.freeze();
|
|
206
|
+
if (body.freeze === false)
|
|
207
|
+
context.clock.unfreeze();
|
|
208
|
+
return json(200, context.clock.state());
|
|
209
|
+
},
|
|
210
|
+
"GET /faults": () => json(200, { faults: context.faults.list() }),
|
|
211
|
+
"POST /faults": ({ body, namespace }) => {
|
|
212
|
+
if (isRecord(body) && typeof body.preset === "string") {
|
|
213
|
+
if (!context.applyPreset)
|
|
214
|
+
return adminError(400, `${context.name} has no fault presets`);
|
|
215
|
+
const { preset, ...overrides } = body;
|
|
216
|
+
try {
|
|
217
|
+
return json(201, {
|
|
218
|
+
preset,
|
|
219
|
+
rules: context.applyPreset(preset, namespace, overrides)
|
|
220
|
+
});
|
|
221
|
+
} catch (error2) {
|
|
222
|
+
return adminError(404, error2 instanceof Error ? error2.message : String(error2));
|
|
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 (error2) {
|
|
278
|
+
return adminError(409, error2 instanceof Error ? error2.message : String(error2));
|
|
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 (error2) {
|
|
289
|
+
return adminError(409, error2 instanceof Error ? error2.message : String(error2));
|
|
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 (error2) {
|
|
303
|
+
return adminError(409, error2 instanceof Error ? error2.message : String(error2));
|
|
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
|
+
// ../../openapi/core/dist/schema.js
|
|
612
|
+
var resolveSchema = (document2, schema) => {
|
|
613
|
+
let current = schema;
|
|
614
|
+
const seen = /* @__PURE__ */ new Set();
|
|
615
|
+
while (typeof current.$ref === "string") {
|
|
616
|
+
const ref = current.$ref;
|
|
617
|
+
if (seen.has(ref))
|
|
618
|
+
break;
|
|
619
|
+
seen.add(ref);
|
|
620
|
+
const { $ref: _ignored, ...siblings } = current;
|
|
621
|
+
const target = resolveRef(document2, ref);
|
|
622
|
+
current = { ...target, ...siblings };
|
|
623
|
+
}
|
|
624
|
+
if (current.nullable === true) {
|
|
625
|
+
const { nullable: _nullable, ...rest } = current;
|
|
626
|
+
const types = schemaTypes(rest);
|
|
627
|
+
if (types.length > 0 && !types.includes("null"))
|
|
628
|
+
current = { ...rest, type: [...types, "null"] };
|
|
629
|
+
else
|
|
630
|
+
current = rest;
|
|
631
|
+
}
|
|
632
|
+
return current;
|
|
633
|
+
};
|
|
634
|
+
var schemaTypes = (schema) => {
|
|
635
|
+
if (Array.isArray(schema.type))
|
|
636
|
+
return schema.type;
|
|
637
|
+
if (schema.type !== void 0)
|
|
638
|
+
return [schema.type];
|
|
639
|
+
const inferred = [];
|
|
640
|
+
if (schema.properties || schema.required || schema.additionalProperties !== void 0)
|
|
641
|
+
inferred.push("object");
|
|
642
|
+
if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
|
|
643
|
+
inferred.push("array");
|
|
644
|
+
if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
|
|
645
|
+
inferred.push("string");
|
|
646
|
+
if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
|
|
647
|
+
inferred.push("number");
|
|
648
|
+
return inferred;
|
|
649
|
+
};
|
|
650
|
+
var jsonTypeOf = (value) => {
|
|
651
|
+
if (value === null)
|
|
652
|
+
return "null";
|
|
653
|
+
if (Array.isArray(value))
|
|
654
|
+
return "array";
|
|
655
|
+
switch (typeof value) {
|
|
656
|
+
case "string":
|
|
657
|
+
return "string";
|
|
658
|
+
case "boolean":
|
|
659
|
+
return "boolean";
|
|
660
|
+
case "number":
|
|
661
|
+
return Number.isInteger(value) ? "integer" : "number";
|
|
662
|
+
case "object":
|
|
663
|
+
return "object";
|
|
664
|
+
default:
|
|
665
|
+
return "undefined";
|
|
666
|
+
}
|
|
667
|
+
};
|
|
668
|
+
var deepEqual = (a, b) => {
|
|
669
|
+
if (a === b)
|
|
670
|
+
return true;
|
|
671
|
+
if (typeof a !== typeof b || a === null || b === null)
|
|
672
|
+
return false;
|
|
673
|
+
if (Array.isArray(a)) {
|
|
674
|
+
return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
|
|
675
|
+
}
|
|
676
|
+
if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
|
|
677
|
+
const ka = Object.keys(a);
|
|
678
|
+
const kb = Object.keys(b);
|
|
679
|
+
return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
|
|
680
|
+
}
|
|
681
|
+
return false;
|
|
682
|
+
};
|
|
683
|
+
var FORMAT_PATTERNS = {
|
|
684
|
+
uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
|
|
685
|
+
date: /^\d{4}-\d{2}-\d{2}$/,
|
|
686
|
+
"date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
|
|
687
|
+
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
|
|
688
|
+
uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
|
|
689
|
+
ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
|
|
690
|
+
};
|
|
691
|
+
var graphemeLength = (value) => [...value].length;
|
|
692
|
+
var validateValue = (document2, schema, value, path = []) => {
|
|
693
|
+
const errors = [];
|
|
694
|
+
const s = resolveSchema(document2, schema);
|
|
695
|
+
const fail = (message) => errors.push({ path, message });
|
|
696
|
+
const actual = jsonTypeOf(value);
|
|
697
|
+
if (actual === "undefined") {
|
|
698
|
+
fail("value is undefined");
|
|
699
|
+
return errors;
|
|
700
|
+
}
|
|
701
|
+
const types = schemaTypes(s);
|
|
702
|
+
if (types.length > 0) {
|
|
703
|
+
const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
|
|
704
|
+
if (!ok) {
|
|
705
|
+
fail(`expected type ${types.join("|")}, got ${actual}`);
|
|
706
|
+
return errors;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
|
|
710
|
+
fail("value not in enum");
|
|
711
|
+
}
|
|
712
|
+
if (s.const !== void 0 && !deepEqual(s.const, value))
|
|
713
|
+
fail("value does not equal const");
|
|
714
|
+
if (typeof value === "string") {
|
|
715
|
+
const length = graphemeLength(value);
|
|
716
|
+
if (s.minLength !== void 0 && length < s.minLength)
|
|
717
|
+
fail(`length ${length} < minLength ${s.minLength}`);
|
|
718
|
+
if (s.maxLength !== void 0 && length > s.maxLength)
|
|
719
|
+
fail(`length ${length} > maxLength ${s.maxLength}`);
|
|
720
|
+
if (s.pattern !== void 0) {
|
|
721
|
+
try {
|
|
722
|
+
if (!new RegExp(s.pattern, "u").test(value))
|
|
723
|
+
fail(`does not match pattern ${s.pattern}`);
|
|
724
|
+
} catch {
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
if (s.format !== void 0) {
|
|
728
|
+
const pattern = FORMAT_PATTERNS[s.format];
|
|
729
|
+
if (pattern && !pattern.test(value))
|
|
730
|
+
fail(`does not match format ${s.format}`);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
if (typeof value === "number") {
|
|
734
|
+
if (s.minimum !== void 0 && value < s.minimum)
|
|
735
|
+
fail(`${value} < minimum ${s.minimum}`);
|
|
736
|
+
if (s.maximum !== void 0 && value > s.maximum)
|
|
737
|
+
fail(`${value} > maximum ${s.maximum}`);
|
|
738
|
+
if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
|
|
739
|
+
fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
|
|
740
|
+
if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
|
|
741
|
+
fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
|
|
742
|
+
if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
|
|
743
|
+
fail(`${value} is not a multiple of ${s.multipleOf}`);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
if (Array.isArray(value)) {
|
|
747
|
+
if (s.minItems !== void 0 && value.length < s.minItems)
|
|
748
|
+
fail(`${value.length} items < minItems ${s.minItems}`);
|
|
749
|
+
if (s.maxItems !== void 0 && value.length > s.maxItems)
|
|
750
|
+
fail(`${value.length} items > maxItems ${s.maxItems}`);
|
|
751
|
+
if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
|
|
752
|
+
fail("items are not unique");
|
|
753
|
+
value.forEach((item, i) => {
|
|
754
|
+
const itemSchema = s.prefixItems?.[i] ?? s.items;
|
|
755
|
+
if (itemSchema)
|
|
756
|
+
errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
if (actual === "object") {
|
|
760
|
+
const record = value;
|
|
761
|
+
const keys = Object.keys(record);
|
|
762
|
+
for (const name of s.required ?? [])
|
|
763
|
+
if (!(name in record))
|
|
764
|
+
fail(`missing required property ${name}`);
|
|
765
|
+
if (s.minProperties !== void 0 && keys.length < s.minProperties)
|
|
766
|
+
fail(`${keys.length} properties < minProperties ${s.minProperties}`);
|
|
767
|
+
if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
|
|
768
|
+
fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
|
|
769
|
+
for (const key of keys) {
|
|
770
|
+
const property = s.properties?.[key];
|
|
771
|
+
if (property) {
|
|
772
|
+
errors.push(...validateValue(document2, property, record[key], [...path, key]));
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
if (s.additionalProperties === false)
|
|
776
|
+
fail(`unexpected property ${key}`);
|
|
777
|
+
else if (typeof s.additionalProperties === "object") {
|
|
778
|
+
errors.push(...validateValue(document2, s.additionalProperties, record[key], [...path, key]));
|
|
779
|
+
}
|
|
780
|
+
if (s.propertyNames) {
|
|
781
|
+
const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
|
|
782
|
+
if (nameErrors.length > 0)
|
|
783
|
+
fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
if (s.allOf)
|
|
788
|
+
for (const branch of s.allOf)
|
|
789
|
+
errors.push(...validateValue(document2, branch, value, path));
|
|
790
|
+
if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
|
|
791
|
+
fail("matches no anyOf branch");
|
|
792
|
+
if (s.oneOf) {
|
|
793
|
+
const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
|
|
794
|
+
if (matches2 !== 1)
|
|
795
|
+
fail(`matches ${matches2} oneOf branches, expected exactly 1`);
|
|
796
|
+
}
|
|
797
|
+
if (s.not && validateValue(document2, s.not, value).length === 0)
|
|
798
|
+
fail("matches forbidden `not` schema");
|
|
799
|
+
return errors;
|
|
800
|
+
};
|
|
801
|
+
|
|
802
|
+
// ../../http/codec/dist/form.js
|
|
803
|
+
var parsePath = (rawKey) => {
|
|
804
|
+
const open = rawKey.indexOf("[");
|
|
805
|
+
if (open === -1)
|
|
806
|
+
return [rawKey];
|
|
807
|
+
const path = [rawKey.slice(0, open)];
|
|
808
|
+
const rest = rawKey.slice(open);
|
|
809
|
+
const pattern = /\[([^\]]*)\]/g;
|
|
810
|
+
let match = pattern.exec(rest);
|
|
811
|
+
let consumed = 0;
|
|
812
|
+
while (match !== null) {
|
|
813
|
+
if (match.index !== consumed)
|
|
814
|
+
return [rawKey];
|
|
815
|
+
path.push(match[1] ?? "");
|
|
816
|
+
consumed = match.index + match[0].length;
|
|
817
|
+
match = pattern.exec(rest);
|
|
818
|
+
}
|
|
819
|
+
if (consumed !== rest.length)
|
|
820
|
+
return [rawKey];
|
|
821
|
+
return path;
|
|
822
|
+
};
|
|
823
|
+
var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
|
|
824
|
+
var put = (target, key, value) => {
|
|
825
|
+
if (key === "__proto__") {
|
|
826
|
+
Object.defineProperty(target, key, {
|
|
827
|
+
value,
|
|
828
|
+
enumerable: true,
|
|
829
|
+
writable: true,
|
|
830
|
+
configurable: true
|
|
831
|
+
});
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
;
|
|
835
|
+
target[key] = value;
|
|
836
|
+
};
|
|
837
|
+
var assign = (target, path, value) => {
|
|
838
|
+
let cursor = target;
|
|
839
|
+
for (let i = 0; i < path.length; i++) {
|
|
840
|
+
const segment = path[i];
|
|
841
|
+
const last = i === path.length - 1;
|
|
842
|
+
if (Array.isArray(cursor)) {
|
|
843
|
+
const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
|
|
844
|
+
if (index === void 0)
|
|
845
|
+
return;
|
|
846
|
+
if (last) {
|
|
847
|
+
put(cursor, index, value);
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
|
|
851
|
+
if (next === void 0 || typeof next === "string") {
|
|
852
|
+
const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
|
|
853
|
+
put(cursor, index, created);
|
|
854
|
+
cursor = created;
|
|
855
|
+
} else {
|
|
856
|
+
cursor = next;
|
|
857
|
+
}
|
|
858
|
+
continue;
|
|
859
|
+
}
|
|
860
|
+
if (typeof cursor === "string")
|
|
861
|
+
return;
|
|
862
|
+
if (last) {
|
|
863
|
+
put(cursor, segment, value);
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
const nextSegment = path[i + 1];
|
|
867
|
+
const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
|
|
868
|
+
if (existing === void 0 || typeof existing === "string") {
|
|
869
|
+
const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
|
|
870
|
+
put(cursor, segment, created);
|
|
871
|
+
cursor = created;
|
|
872
|
+
} else {
|
|
873
|
+
cursor = existing;
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
};
|
|
877
|
+
var decodeFormPairs = (pairs) => {
|
|
878
|
+
const out = {};
|
|
879
|
+
for (const [rawKey, value] of pairs)
|
|
880
|
+
assign(out, parsePath(rawKey), value);
|
|
881
|
+
return densify(out);
|
|
882
|
+
};
|
|
883
|
+
var densify = (value) => {
|
|
884
|
+
if (typeof value === "string")
|
|
885
|
+
return value;
|
|
886
|
+
if (Array.isArray(value))
|
|
887
|
+
return value.filter((item) => item !== void 0).map(densify);
|
|
888
|
+
const out = {};
|
|
889
|
+
for (const [key, item] of Object.entries(value))
|
|
890
|
+
put(out, key, densify(item));
|
|
891
|
+
return out;
|
|
892
|
+
};
|
|
893
|
+
var decodeForm = (text) => {
|
|
894
|
+
const source = text.startsWith("?") ? text.slice(1) : text;
|
|
895
|
+
return decodeFormPairs(new URLSearchParams(source).entries());
|
|
896
|
+
};
|
|
897
|
+
|
|
898
|
+
// ../../http/codec/dist/content.js
|
|
899
|
+
var JSON_MEDIA_TYPE = "application/json";
|
|
900
|
+
var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
|
|
901
|
+
var mediaTypeOf = (contentType) => {
|
|
902
|
+
if (!contentType)
|
|
903
|
+
return void 0;
|
|
904
|
+
const essence = contentType.split(";")[0]?.trim().toLowerCase();
|
|
905
|
+
return essence ? essence : void 0;
|
|
906
|
+
};
|
|
907
|
+
var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
|
|
908
|
+
var utf8 = new TextDecoder("utf-8", { fatal: false });
|
|
909
|
+
var decodeBody = (contentType, bytes) => {
|
|
910
|
+
if (bytes.byteLength === 0)
|
|
911
|
+
return { kind: "empty" };
|
|
912
|
+
const mediaType = mediaTypeOf(contentType);
|
|
913
|
+
if (mediaType === void 0)
|
|
914
|
+
return { kind: "bytes", value: bytes };
|
|
915
|
+
if (isJsonMediaType(mediaType)) {
|
|
916
|
+
const text = utf8.decode(bytes);
|
|
917
|
+
try {
|
|
918
|
+
return { kind: "json", value: JSON.parse(text) };
|
|
919
|
+
} catch (error2) {
|
|
920
|
+
return {
|
|
921
|
+
kind: "invalid",
|
|
922
|
+
mediaType,
|
|
923
|
+
text,
|
|
924
|
+
error: error2 instanceof Error ? error2.message : String(error2)
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
if (mediaType === FORM_MEDIA_TYPE) {
|
|
929
|
+
return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
|
|
930
|
+
}
|
|
931
|
+
if (mediaType.startsWith("text/"))
|
|
932
|
+
return { kind: "text", value: utf8.decode(bytes) };
|
|
933
|
+
return { kind: "bytes", value: bytes };
|
|
934
|
+
};
|
|
935
|
+
var readBody = async (message) => {
|
|
936
|
+
const bytes = new Uint8Array(await message.arrayBuffer());
|
|
937
|
+
return decodeBody(message.headers.get("content-type"), bytes);
|
|
938
|
+
};
|
|
939
|
+
|
|
940
|
+
// ../core/dist/http.js
|
|
941
|
+
var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
|
|
942
|
+
status,
|
|
943
|
+
headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
|
|
944
|
+
});
|
|
945
|
+
var HttpError = class extends Error {
|
|
946
|
+
status;
|
|
947
|
+
body;
|
|
948
|
+
headers;
|
|
949
|
+
constructor(status, body, headers = {}) {
|
|
950
|
+
super(`HTTP ${status}`);
|
|
951
|
+
this.status = status;
|
|
952
|
+
this.body = body;
|
|
953
|
+
this.headers = headers;
|
|
954
|
+
this.name = "HttpError";
|
|
955
|
+
}
|
|
956
|
+
toResponse() {
|
|
957
|
+
const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
|
|
958
|
+
if (contentType === "text/plain") {
|
|
959
|
+
return new Response(String(this.body), {
|
|
960
|
+
status: this.status,
|
|
961
|
+
headers: this.headers
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
return jsonRes(this.status, this.body, this.headers);
|
|
965
|
+
}
|
|
966
|
+
};
|
|
967
|
+
|
|
968
|
+
// ../core/dist/journal.js
|
|
969
|
+
var DEFAULT_JOURNAL_SIZE = 1e3;
|
|
970
|
+
var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
|
|
971
|
+
const capacity = Math.max(0, Math.floor(size));
|
|
972
|
+
const rings = /* @__PURE__ */ new Map();
|
|
973
|
+
let sequence = 0;
|
|
974
|
+
const order = /* @__PURE__ */ new WeakMap();
|
|
975
|
+
const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
|
|
976
|
+
return {
|
|
977
|
+
size: capacity,
|
|
978
|
+
record(entry) {
|
|
979
|
+
if (capacity === 0)
|
|
980
|
+
return;
|
|
981
|
+
order.set(entry, sequence++);
|
|
982
|
+
let ring = rings.get(entry.namespace);
|
|
983
|
+
if (!ring) {
|
|
984
|
+
ring = { entries: [], next: 0 };
|
|
985
|
+
rings.set(entry.namespace, ring);
|
|
986
|
+
}
|
|
987
|
+
if (ring.entries.length < capacity)
|
|
988
|
+
ring.entries.push(entry);
|
|
989
|
+
else {
|
|
990
|
+
ring.entries[ring.next] = entry;
|
|
991
|
+
ring.next = (ring.next + 1) % capacity;
|
|
992
|
+
}
|
|
993
|
+
},
|
|
994
|
+
list(query = {}) {
|
|
995
|
+
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));
|
|
996
|
+
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));
|
|
997
|
+
return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
|
|
998
|
+
},
|
|
999
|
+
clear(namespace) {
|
|
1000
|
+
if (namespace === void 0)
|
|
1001
|
+
rings.clear();
|
|
1002
|
+
else
|
|
1003
|
+
rings.delete(namespace);
|
|
1004
|
+
}
|
|
1005
|
+
};
|
|
1006
|
+
};
|
|
1007
|
+
var notes = /* @__PURE__ */ new WeakMap();
|
|
1008
|
+
var annotateResponse = (response, extra) => {
|
|
1009
|
+
const existing = notes.get(response);
|
|
1010
|
+
notes.set(response, {
|
|
1011
|
+
...existing,
|
|
1012
|
+
...extra,
|
|
1013
|
+
...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
|
|
1014
|
+
});
|
|
1015
|
+
return response;
|
|
1016
|
+
};
|
|
1017
|
+
var responseNotes = (response) => notes.get(response);
|
|
1018
|
+
|
|
1019
|
+
// ../core/dist/metrics.js
|
|
1020
|
+
var createMetrics = () => {
|
|
1021
|
+
let requests = 0;
|
|
1022
|
+
let faults = 0;
|
|
1023
|
+
let totalDurationMs = 0;
|
|
1024
|
+
const byOperation = /* @__PURE__ */ new Map();
|
|
1025
|
+
const unmatched = /* @__PURE__ */ new Map();
|
|
1026
|
+
return {
|
|
1027
|
+
record(entry) {
|
|
1028
|
+
requests++;
|
|
1029
|
+
totalDurationMs += entry.durationMs;
|
|
1030
|
+
if (entry.faultId !== void 0)
|
|
1031
|
+
faults++;
|
|
1032
|
+
const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
|
|
1033
|
+
byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
|
|
1034
|
+
if (entry.unmatched) {
|
|
1035
|
+
const route = `${entry.method} ${entry.path}`;
|
|
1036
|
+
unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
|
|
1037
|
+
}
|
|
1038
|
+
},
|
|
1039
|
+
report: () => ({
|
|
1040
|
+
requests,
|
|
1041
|
+
byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
|
|
1042
|
+
unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
|
|
1043
|
+
const space = route.indexOf(" ");
|
|
1044
|
+
return { method: route.slice(0, space), path: route.slice(space + 1), count };
|
|
1045
|
+
}),
|
|
1046
|
+
faults,
|
|
1047
|
+
totalDurationMs
|
|
1048
|
+
}),
|
|
1049
|
+
reset() {
|
|
1050
|
+
requests = 0;
|
|
1051
|
+
faults = 0;
|
|
1052
|
+
totalDurationMs = 0;
|
|
1053
|
+
byOperation.clear();
|
|
1054
|
+
unmatched.clear();
|
|
1055
|
+
}
|
|
1056
|
+
};
|
|
1057
|
+
};
|
|
1058
|
+
|
|
1059
|
+
// ../../core/dist/timeline.js
|
|
1060
|
+
var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1061
|
+
var Timeline = class {
|
|
1062
|
+
maxCheckpoints;
|
|
1063
|
+
now;
|
|
1064
|
+
makeId;
|
|
1065
|
+
nodes = /* @__PURE__ */ new Map();
|
|
1066
|
+
heads = /* @__PURE__ */ new Map();
|
|
1067
|
+
/** Unreferenced nodes in the exact order they became collectible. */
|
|
1068
|
+
evictable = /* @__PURE__ */ new Set();
|
|
1069
|
+
/** Branch heads plus explicit retainers. Absent means zero. */
|
|
1070
|
+
references = /* @__PURE__ */ new Map();
|
|
1071
|
+
explicitPins = /* @__PURE__ */ new Map();
|
|
1072
|
+
sequence = 0;
|
|
1073
|
+
constructor(options = {}) {
|
|
1074
|
+
const max = options.maxCheckpoints ?? 1e3;
|
|
1075
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1076
|
+
throw new RangeError("maxCheckpoints must be a positive integer");
|
|
1077
|
+
this.maxCheckpoints = max;
|
|
1078
|
+
this.now = options.now ?? (() => this.sequence);
|
|
1079
|
+
this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
|
|
1080
|
+
}
|
|
1081
|
+
/** Capture a new immutable value and move `branch` to it. */
|
|
1082
|
+
commit(value, options = {}) {
|
|
1083
|
+
const branch = options.branch ?? "main";
|
|
1084
|
+
this.assertBranch(branch);
|
|
1085
|
+
const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
|
|
1086
|
+
if (parent !== null && !this.nodes.has(parent))
|
|
1087
|
+
throw new RangeError(`no checkpoint ${parent}`);
|
|
1088
|
+
const id = this.makeId(++this.sequence);
|
|
1089
|
+
if (this.nodes.has(id))
|
|
1090
|
+
throw new RangeError(`duplicate checkpoint id ${id}`);
|
|
1091
|
+
const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
|
|
1092
|
+
this.nodes.set(id, checkpoint);
|
|
1093
|
+
this.moveHead(branch, id);
|
|
1094
|
+
this.collect(this.maxCheckpoints);
|
|
1095
|
+
return checkpoint;
|
|
1096
|
+
}
|
|
1097
|
+
/** Create a branch pointer without copying its checkpoint value. */
|
|
1098
|
+
fork(branch, options = {}) {
|
|
1099
|
+
this.assertBranch(branch);
|
|
1100
|
+
if (this.heads.has(branch))
|
|
1101
|
+
throw new RangeError(`branch already exists: ${branch}`);
|
|
1102
|
+
const from = options.from ?? this.heads.get("main");
|
|
1103
|
+
if (from === void 0)
|
|
1104
|
+
return void 0;
|
|
1105
|
+
const checkpoint = this.get(from);
|
|
1106
|
+
this.moveHead(branch, checkpoint.id);
|
|
1107
|
+
return checkpoint;
|
|
1108
|
+
}
|
|
1109
|
+
/** Move a branch pointer to an existing checkpoint. */
|
|
1110
|
+
checkout(branch, id) {
|
|
1111
|
+
this.assertBranch(branch);
|
|
1112
|
+
const checkpoint = this.get(id);
|
|
1113
|
+
this.moveHead(branch, checkpoint.id);
|
|
1114
|
+
return checkpoint;
|
|
1115
|
+
}
|
|
1116
|
+
get(id) {
|
|
1117
|
+
const checkpoint = this.nodes.get(id);
|
|
1118
|
+
if (!checkpoint)
|
|
1119
|
+
throw new RangeError(`no checkpoint ${id}`);
|
|
1120
|
+
return checkpoint;
|
|
1121
|
+
}
|
|
1122
|
+
head(branch = "main") {
|
|
1123
|
+
const id = this.heads.get(branch);
|
|
1124
|
+
return id === void 0 ? void 0 : this.get(id);
|
|
1125
|
+
}
|
|
1126
|
+
hasBranch(branch) {
|
|
1127
|
+
return this.heads.has(branch);
|
|
1128
|
+
}
|
|
1129
|
+
branches() {
|
|
1130
|
+
return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
|
|
1131
|
+
}
|
|
1132
|
+
checkpoints() {
|
|
1133
|
+
return [...this.nodes.values()];
|
|
1134
|
+
}
|
|
1135
|
+
/** Number of retained checkpoints without allocating an array. */
|
|
1136
|
+
get size() {
|
|
1137
|
+
return this.nodes.size;
|
|
1138
|
+
}
|
|
1139
|
+
/** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
|
|
1140
|
+
retain(id) {
|
|
1141
|
+
const checkpoint = this.get(id);
|
|
1142
|
+
this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
|
|
1143
|
+
this.addReference(id);
|
|
1144
|
+
return checkpoint;
|
|
1145
|
+
}
|
|
1146
|
+
/** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
|
|
1147
|
+
release(id) {
|
|
1148
|
+
if (!this.nodes.has(id))
|
|
1149
|
+
return false;
|
|
1150
|
+
const pins = this.explicitPins.get(id) ?? 0;
|
|
1151
|
+
if (pins === 0)
|
|
1152
|
+
return false;
|
|
1153
|
+
if (pins === 1)
|
|
1154
|
+
this.explicitPins.delete(id);
|
|
1155
|
+
else
|
|
1156
|
+
this.explicitPins.set(id, pins - 1);
|
|
1157
|
+
this.removeReference(id);
|
|
1158
|
+
this.collect(this.maxCheckpoints);
|
|
1159
|
+
return true;
|
|
1160
|
+
}
|
|
1161
|
+
deleteBranch(branch) {
|
|
1162
|
+
if (branch === "main")
|
|
1163
|
+
throw new RangeError("cannot delete main branch");
|
|
1164
|
+
const previous = this.heads.get(branch);
|
|
1165
|
+
const deleted = this.heads.delete(branch);
|
|
1166
|
+
if (previous !== void 0)
|
|
1167
|
+
this.removeReference(previous);
|
|
1168
|
+
this.collect(this.maxCheckpoints);
|
|
1169
|
+
return deleted;
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
|
|
1173
|
+
* commits never scan pinned nodes or the retained history. Parents are metadata rather than a
|
|
1174
|
+
* storage dependency, so a retained node remains usable after pruning.
|
|
1175
|
+
*/
|
|
1176
|
+
gc(max = this.maxCheckpoints) {
|
|
1177
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1178
|
+
throw new RangeError("max must be a positive integer");
|
|
1179
|
+
const removed = [];
|
|
1180
|
+
this.collect(max, removed);
|
|
1181
|
+
return removed;
|
|
1182
|
+
}
|
|
1183
|
+
collect(max, removed) {
|
|
1184
|
+
while (this.nodes.size > max && this.evictable.size > 0) {
|
|
1185
|
+
const id = this.evictable.values().next().value;
|
|
1186
|
+
this.evictable.delete(id);
|
|
1187
|
+
this.nodes.delete(id);
|
|
1188
|
+
removed?.push(id);
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
moveHead(branch, id) {
|
|
1192
|
+
const previous = this.heads.get(branch);
|
|
1193
|
+
if (previous === id)
|
|
1194
|
+
return;
|
|
1195
|
+
if (previous !== void 0)
|
|
1196
|
+
this.removeReference(previous);
|
|
1197
|
+
this.heads.set(branch, id);
|
|
1198
|
+
this.addReference(id);
|
|
1199
|
+
}
|
|
1200
|
+
addReference(id) {
|
|
1201
|
+
this.references.set(id, (this.references.get(id) ?? 0) + 1);
|
|
1202
|
+
this.evictable.delete(id);
|
|
1203
|
+
}
|
|
1204
|
+
removeReference(id) {
|
|
1205
|
+
const next = (this.references.get(id) ?? 0) - 1;
|
|
1206
|
+
if (next > 0)
|
|
1207
|
+
this.references.set(id, next);
|
|
1208
|
+
else {
|
|
1209
|
+
this.references.delete(id);
|
|
1210
|
+
if (this.nodes.has(id))
|
|
1211
|
+
this.evictable.add(id);
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
assertBranch(branch) {
|
|
1215
|
+
if (!BRANCH_PATTERN.test(branch))
|
|
1216
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
|
|
1217
|
+
}
|
|
1218
|
+
};
|
|
1219
|
+
|
|
1220
|
+
// ../../sqlite/dist/default.js
|
|
1221
|
+
import { Database } from "@crvouga/mockingbird-service-sqlite";
|
|
1222
|
+
var createDefaultSqlite = () => new Database();
|
|
1223
|
+
var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
|
|
1224
|
+
|
|
1225
|
+
// ../../sqlite/dist/migrate.js
|
|
1226
|
+
var ensureMigrationsTable = (sqlite) => {
|
|
1227
|
+
sqlite.exec(`
|
|
1228
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
1229
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
1230
|
+
applied_at INTEGER NOT NULL
|
|
1231
|
+
)
|
|
1232
|
+
`);
|
|
1233
|
+
};
|
|
1234
|
+
var migrate = (sqlite, migrations) => {
|
|
1235
|
+
ensureMigrationsTable(sqlite);
|
|
1236
|
+
const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
|
|
1237
|
+
const pending = migrations.filter((migration) => !applied.has(migration.id));
|
|
1238
|
+
if (pending.length === 0)
|
|
1239
|
+
return;
|
|
1240
|
+
const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
|
|
1241
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1242
|
+
sqlite.transaction(() => {
|
|
1243
|
+
for (const migration of pending) {
|
|
1244
|
+
sqlite.exec(migration.sql);
|
|
1245
|
+
insert.run(migration.id, now);
|
|
1246
|
+
}
|
|
1247
|
+
});
|
|
1248
|
+
};
|
|
1249
|
+
|
|
1250
|
+
// ../../sqlite/dist/schema.js
|
|
1251
|
+
var CORE_MIGRATIONS = [
|
|
1252
|
+
{
|
|
1253
|
+
id: "20260322_core_records_sequences",
|
|
1254
|
+
sql: `
|
|
1255
|
+
CREATE TABLE IF NOT EXISTS mockingbird_records (
|
|
1256
|
+
namespace TEXT NOT NULL,
|
|
1257
|
+
collection TEXT NOT NULL,
|
|
1258
|
+
id TEXT NOT NULL,
|
|
1259
|
+
seq INTEGER NOT NULL,
|
|
1260
|
+
value TEXT NOT NULL,
|
|
1261
|
+
PRIMARY KEY (namespace, collection, id)
|
|
1262
|
+
);
|
|
1263
|
+
CREATE INDEX IF NOT EXISTS mockingbird_records_seq
|
|
1264
|
+
ON mockingbird_records (namespace, collection, seq);
|
|
1265
|
+
CREATE TABLE IF NOT EXISTS mockingbird_sequences (
|
|
1266
|
+
namespace TEXT NOT NULL,
|
|
1267
|
+
name TEXT NOT NULL,
|
|
1268
|
+
kind TEXT NOT NULL,
|
|
1269
|
+
value INTEGER NOT NULL,
|
|
1270
|
+
PRIMARY KEY (namespace, name, kind)
|
|
1271
|
+
);
|
|
1272
|
+
`
|
|
1273
|
+
}
|
|
1274
|
+
];
|
|
1275
|
+
var migrateCore = (sqlite) => {
|
|
1276
|
+
migrate(sqlite, CORE_MIGRATIONS);
|
|
1277
|
+
};
|
|
1278
|
+
var clearNamespace = (sqlite, namespace) => {
|
|
1279
|
+
sqlite.transaction(() => {
|
|
1280
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1281
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1282
|
+
});
|
|
1283
|
+
};
|
|
1284
|
+
|
|
1285
|
+
// ../../openapi/metadata/dist/types.js
|
|
1286
|
+
var EXTENSION_KEYS = {
|
|
1287
|
+
operation: "x-mockingbird",
|
|
1288
|
+
resource: "x-mockingbird-resource",
|
|
1289
|
+
resourceRef: "x-mockingbird-resource-ref",
|
|
1290
|
+
volatile: "x-mockingbird-volatile",
|
|
1291
|
+
scope: "x-mockingbird-scope",
|
|
1292
|
+
unsupported: "x-mockingbird-unsupported",
|
|
1293
|
+
parityHeader: "x-mockingbird-parity-header"
|
|
1294
|
+
};
|
|
1295
|
+
|
|
1296
|
+
// ../../openapi/metadata/dist/read.js
|
|
1297
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1298
|
+
var extensionOf = (holder, key) => holder[key];
|
|
1299
|
+
var operationMetadata = (operation) => {
|
|
1300
|
+
const raw = extensionOf(operation, EXTENSION_KEYS.operation);
|
|
1301
|
+
const ext = isRecord2(raw) ? raw : {};
|
|
1302
|
+
const supported = ext.supported ?? true;
|
|
1303
|
+
const parity = ext.parity ?? {};
|
|
1304
|
+
return {
|
|
1305
|
+
supported,
|
|
1306
|
+
reason: typeof ext.reason === "string" ? ext.reason : void 0,
|
|
1307
|
+
parity: {
|
|
1308
|
+
enabled: supported && (parity.enabled ?? true),
|
|
1309
|
+
safe: parity.safe ?? true,
|
|
1310
|
+
reason: typeof parity.reason === "string" ? parity.reason : void 0
|
|
1311
|
+
}
|
|
1312
|
+
};
|
|
1313
|
+
};
|
|
1314
|
+
|
|
1315
|
+
// ../core/dist/service.js
|
|
1316
|
+
import { Hono } from "hono";
|
|
1317
|
+
var defineOperations = (handlers) => handlers;
|
|
1318
|
+
var OperationRegistryError = class extends Error {
|
|
1319
|
+
problems;
|
|
1320
|
+
constructor(problems) {
|
|
1321
|
+
super(`operation registry is inconsistent:
|
|
1322
|
+
${problems.map((p) => ` - ${p}`).join("\n")}`);
|
|
1323
|
+
this.problems = problems;
|
|
1324
|
+
this.name = "OperationRegistryError";
|
|
1325
|
+
}
|
|
1326
|
+
};
|
|
1327
|
+
var verifyOperations = (document2, handlers) => {
|
|
1328
|
+
const problems = [];
|
|
1329
|
+
const operations = listOperations(document2);
|
|
1330
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1331
|
+
for (const operation of operations) {
|
|
1332
|
+
if (seen.has(operation.operationId))
|
|
1333
|
+
problems.push(`duplicate operationId ${operation.operationId}`);
|
|
1334
|
+
seen.add(operation.operationId);
|
|
1335
|
+
const supported = operationMetadata(operation.operation).supported;
|
|
1336
|
+
const handler = handlers[operation.operationId];
|
|
1337
|
+
if (supported && !handler)
|
|
1338
|
+
problems.push(`supported operation ${operation.operationId} has no handler`);
|
|
1339
|
+
if (!supported && handler)
|
|
1340
|
+
problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
|
|
1341
|
+
}
|
|
1342
|
+
for (const id of Object.keys(handlers)) {
|
|
1343
|
+
if (!seen.has(id))
|
|
1344
|
+
problems.push(`handler ${id} has no OpenAPI operation`);
|
|
1345
|
+
}
|
|
1346
|
+
return problems;
|
|
1347
|
+
};
|
|
1348
|
+
var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
|
|
1349
|
+
var routeOrder = (a, b) => {
|
|
1350
|
+
const sa = a.path.split("/");
|
|
1351
|
+
const sb = b.path.split("/");
|
|
1352
|
+
for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
|
|
1353
|
+
const x = sa[i] ?? "";
|
|
1354
|
+
const y = sb[i] ?? "";
|
|
1355
|
+
const px = x.startsWith("{");
|
|
1356
|
+
const py = y.startsWith("{");
|
|
1357
|
+
if (px !== py)
|
|
1358
|
+
return px ? 1 : -1;
|
|
1359
|
+
if (x !== y)
|
|
1360
|
+
return x < y ? -1 : 1;
|
|
1361
|
+
}
|
|
1362
|
+
return 0;
|
|
1363
|
+
};
|
|
1364
|
+
var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
|
|
1365
|
+
var bootSqlite = (sqlite) => {
|
|
1366
|
+
const client = resolveSqlite(sqlite);
|
|
1367
|
+
migrateCore(client);
|
|
1368
|
+
return client;
|
|
1369
|
+
};
|
|
1370
|
+
var createService = (options) => {
|
|
1371
|
+
const problems = verifyOperations(options.document, options.handlers);
|
|
1372
|
+
if (problems.length > 0)
|
|
1373
|
+
throw new OperationRegistryError(problems);
|
|
1374
|
+
migrateCore(options.sqlite);
|
|
1375
|
+
const now = options.now ?? (() => Date.now());
|
|
1376
|
+
const app = new Hono();
|
|
1377
|
+
app.notFound((c) => options.notFound(c.req.raw));
|
|
1378
|
+
app.onError((error2, c) => options.onError(error2, c.req.raw));
|
|
1379
|
+
const operations = [...listOperations(options.document)].sort(routeOrder);
|
|
1380
|
+
for (const operation of operations) {
|
|
1381
|
+
const metadata = operationMetadata(operation.operation);
|
|
1382
|
+
const handler = options.handlers[operation.operationId];
|
|
1383
|
+
const route = async (c) => {
|
|
1384
|
+
const request = c.req.raw;
|
|
1385
|
+
if (!metadata.supported || !handler) {
|
|
1386
|
+
return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
|
|
1387
|
+
}
|
|
1388
|
+
const url = new URL(request.url);
|
|
1389
|
+
const context = {
|
|
1390
|
+
request,
|
|
1391
|
+
url,
|
|
1392
|
+
params: c.req.param(),
|
|
1393
|
+
query: queryOf(url),
|
|
1394
|
+
body: await readBody(request),
|
|
1395
|
+
sqlite: options.sqlite,
|
|
1396
|
+
namespace: options.namespace,
|
|
1397
|
+
operation,
|
|
1398
|
+
document: options.document,
|
|
1399
|
+
now
|
|
1400
|
+
};
|
|
1401
|
+
const short = await options.before?.(context);
|
|
1402
|
+
if (short)
|
|
1403
|
+
return short;
|
|
1404
|
+
return handler(context);
|
|
1405
|
+
};
|
|
1406
|
+
app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
|
|
1407
|
+
}
|
|
1408
|
+
return {
|
|
1409
|
+
app,
|
|
1410
|
+
sqlite: options.sqlite,
|
|
1411
|
+
namespace: options.namespace,
|
|
1412
|
+
fetch: async (request) => app.fetch(request),
|
|
1413
|
+
reset: async () => {
|
|
1414
|
+
clearNamespace(options.sqlite, options.namespace);
|
|
1415
|
+
}
|
|
1416
|
+
};
|
|
1417
|
+
};
|
|
1418
|
+
|
|
1419
|
+
// ../core/dist/snapshot.js
|
|
1420
|
+
var snapshotNamespace = (sqlite, namespace) => ({
|
|
1421
|
+
namespace,
|
|
1422
|
+
records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
|
|
1423
|
+
sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
|
|
1424
|
+
});
|
|
1425
|
+
var restoreNamespace = (sqlite, namespace, snapshot) => {
|
|
1426
|
+
sqlite.transaction(() => {
|
|
1427
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1428
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1429
|
+
const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
|
|
1430
|
+
for (const row of snapshot.records) {
|
|
1431
|
+
record.run(namespace, row.collection, row.id, row.seq, row.value);
|
|
1432
|
+
}
|
|
1433
|
+
const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
|
|
1434
|
+
for (const row of snapshot.sequences) {
|
|
1435
|
+
sequence.run(namespace, row.name, row.kind, row.value);
|
|
1436
|
+
}
|
|
1437
|
+
});
|
|
1438
|
+
};
|
|
1439
|
+
|
|
1440
|
+
// ../core/dist/version.js
|
|
1441
|
+
var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
|
|
1442
|
+
|
|
1443
|
+
// ../core/dist/webhooks.js
|
|
1444
|
+
var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1445
|
+
var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
|
|
1446
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1447
|
+
var parseEndpoint = (value) => {
|
|
1448
|
+
if (!isRecord3(value) || typeof value.url !== "string")
|
|
1449
|
+
return "each endpoint needs a url";
|
|
1450
|
+
try {
|
|
1451
|
+
new URL(value.url);
|
|
1452
|
+
} catch {
|
|
1453
|
+
return `not a URL: ${value.url}`;
|
|
1454
|
+
}
|
|
1455
|
+
const endpoint = { url: value.url };
|
|
1456
|
+
if (typeof value.id === "string")
|
|
1457
|
+
endpoint.id = value.id;
|
|
1458
|
+
if (typeof value.secret === "string")
|
|
1459
|
+
endpoint.secret = value.secret;
|
|
1460
|
+
if (typeof value.signUrl === "string")
|
|
1461
|
+
endpoint.signUrl = value.signUrl;
|
|
1462
|
+
const events = value.events ?? value.enabledEvents;
|
|
1463
|
+
if (Array.isArray(events))
|
|
1464
|
+
endpoint.events = events.map(String);
|
|
1465
|
+
if (isRecord3(value.tags)) {
|
|
1466
|
+
endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
|
|
1467
|
+
}
|
|
1468
|
+
if (typeof value.account === "string")
|
|
1469
|
+
endpoint.tags = { ...endpoint.tags, account: value.account };
|
|
1470
|
+
if (isRecord3(value.headers)) {
|
|
1471
|
+
endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
|
|
1472
|
+
}
|
|
1473
|
+
return endpoint;
|
|
1474
|
+
};
|
|
1475
|
+
var webhookAdminRoutes = (hub) => ({
|
|
1476
|
+
"GET /webhooks": ({ url, namespace }) => json2(200, {
|
|
1477
|
+
deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
|
|
1478
|
+
const type = url.searchParams.get("type");
|
|
1479
|
+
return type === null || d.type === type;
|
|
1480
|
+
})
|
|
1481
|
+
}),
|
|
1482
|
+
"GET /webhooks/events": ({ url, namespace }) => {
|
|
1483
|
+
const type = url.searchParams.get("type");
|
|
1484
|
+
return json2(200, {
|
|
1485
|
+
events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
|
|
1486
|
+
});
|
|
1487
|
+
},
|
|
1488
|
+
"POST /webhooks/:id/replay": async ({ params }) => {
|
|
1489
|
+
const replayed = await hub.replay(params.id);
|
|
1490
|
+
return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
|
|
1491
|
+
},
|
|
1492
|
+
"POST /webhooks/flush": async () => {
|
|
1493
|
+
await hub.flush();
|
|
1494
|
+
return json2(200, { status: "ok" });
|
|
1495
|
+
},
|
|
1496
|
+
"POST /webhooks/faults": ({ body, namespace }) => {
|
|
1497
|
+
if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
|
|
1498
|
+
return adminError2(400, "mode must be duplicate, reorder or drop");
|
|
1499
|
+
}
|
|
1500
|
+
const fault = { mode: body.mode };
|
|
1501
|
+
if (typeof body.count === "number")
|
|
1502
|
+
fault.count = body.count;
|
|
1503
|
+
hub.fault(namespace, fault);
|
|
1504
|
+
return json2(201, { namespace, ...fault });
|
|
1505
|
+
},
|
|
1506
|
+
"GET /webhook-endpoints": ({ namespace }) => json2(200, {
|
|
1507
|
+
endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
|
|
1508
|
+
...rest,
|
|
1509
|
+
secret: secret ? "(set)" : null
|
|
1510
|
+
}))
|
|
1511
|
+
}),
|
|
1512
|
+
"PUT /webhook-endpoints": ({ body, namespace }) => {
|
|
1513
|
+
const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
|
|
1514
|
+
if (!Array.isArray(list))
|
|
1515
|
+
return adminError2(400, "expected [{url, secret?, events?}]");
|
|
1516
|
+
const parsed = [];
|
|
1517
|
+
for (const each of list) {
|
|
1518
|
+
const endpoint = parseEndpoint(each);
|
|
1519
|
+
if (typeof endpoint === "string")
|
|
1520
|
+
return adminError2(400, endpoint);
|
|
1521
|
+
parsed.push(endpoint);
|
|
1522
|
+
}
|
|
1523
|
+
const set = hub.setEndpoints(namespace, parsed);
|
|
1524
|
+
return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
|
|
1525
|
+
},
|
|
1526
|
+
"DELETE /webhook-endpoints": ({ namespace }) => {
|
|
1527
|
+
hub.setEndpoints(namespace, []);
|
|
1528
|
+
return json2(200, { status: "ok" });
|
|
1529
|
+
}
|
|
1530
|
+
});
|
|
1531
|
+
var parsePayload = (message) => {
|
|
1532
|
+
if (message.contentType.startsWith("application/json")) {
|
|
1533
|
+
try {
|
|
1534
|
+
return JSON.parse(message.body);
|
|
1535
|
+
} catch {
|
|
1536
|
+
return message.body;
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
|
|
1540
|
+
return Object.fromEntries(new URLSearchParams(message.body));
|
|
1541
|
+
}
|
|
1542
|
+
return message.body;
|
|
1543
|
+
};
|
|
1544
|
+
|
|
1545
|
+
// ../core/dist/runtime.js
|
|
1546
|
+
var MOCKINGBIRD_HEADER = "x-mockingbird";
|
|
1547
|
+
var BRANCH_HEADER = "x-mockingbird-branch";
|
|
1548
|
+
var AT_HEADER = "x-mockingbird-at";
|
|
1549
|
+
var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
|
|
1550
|
+
var DEFAULT_NAMESPACE = "default";
|
|
1551
|
+
var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1552
|
+
var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
|
|
1553
|
+
var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1554
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
1555
|
+
var effects = /* @__PURE__ */ new WeakMap();
|
|
1556
|
+
var reuseSorted = (fresh, previous, compare, equal) => {
|
|
1557
|
+
if (!previous || previous.length === 0)
|
|
1558
|
+
return fresh.map((row) => Object.freeze(row));
|
|
1559
|
+
const result = new Array(fresh.length);
|
|
1560
|
+
let unchanged = fresh.length === previous.length;
|
|
1561
|
+
let oldIndex = 0;
|
|
1562
|
+
for (let index = 0; index < fresh.length; index++) {
|
|
1563
|
+
const row = fresh[index];
|
|
1564
|
+
while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
|
|
1565
|
+
oldIndex++;
|
|
1566
|
+
}
|
|
1567
|
+
const old = previous[oldIndex];
|
|
1568
|
+
result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
|
|
1569
|
+
if (result[index] !== previous[index])
|
|
1570
|
+
unchanged = false;
|
|
1571
|
+
}
|
|
1572
|
+
return unchanged ? previous : result;
|
|
1573
|
+
};
|
|
1574
|
+
var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
|
|
1575
|
+
var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
|
|
1576
|
+
var DroppedConnectionError = class extends TypeError {
|
|
1577
|
+
code = "MOCKINGBIRD_DROP";
|
|
1578
|
+
constructor() {
|
|
1579
|
+
super("fetch failed: connection dropped by Mockingbird fault");
|
|
1580
|
+
this.name = "TypeError";
|
|
1581
|
+
}
|
|
1582
|
+
};
|
|
1583
|
+
var operationMatcher = (document2) => {
|
|
1584
|
+
const matchers = listOperations(document2).map((operation) => ({
|
|
1585
|
+
operationId: operation.operationId,
|
|
1586
|
+
method: operation.method.toUpperCase(),
|
|
1587
|
+
pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
|
|
1588
|
+
params: (operation.path.match(/\{/g) ?? []).length
|
|
1589
|
+
})).sort((a, b) => a.params - b.params);
|
|
1590
|
+
return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
|
|
1591
|
+
};
|
|
1592
|
+
var createRuntime = (options) => {
|
|
1593
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
1594
|
+
const clock = options.clock ?? createClock();
|
|
1595
|
+
const rng = createRng(options.seed ?? 0);
|
|
1596
|
+
const wallNow = options.io?.wallNow ?? Date.now;
|
|
1597
|
+
const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
|
|
1598
|
+
const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1599
|
+
const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
|
|
1600
|
+
const metrics = createMetrics();
|
|
1601
|
+
const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
|
|
1602
|
+
const version = options.version ?? PACKAGE_VERSION;
|
|
1603
|
+
const instances = /* @__PURE__ */ new Map();
|
|
1604
|
+
const publicNamespaces = /* @__PURE__ */ new Set();
|
|
1605
|
+
const branchRngs = /* @__PURE__ */ new Map();
|
|
1606
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
1607
|
+
const branchStorage = /* @__PURE__ */ new Map();
|
|
1608
|
+
const captured = /* @__PURE__ */ new Map();
|
|
1609
|
+
const credentials = createCredentialRegistry();
|
|
1610
|
+
const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
|
|
1611
|
+
const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
|
|
1612
|
+
const instanceFor = (key, publicNamespace = key, isolatedRng) => {
|
|
1613
|
+
const existing = instances.get(key);
|
|
1614
|
+
if (existing)
|
|
1615
|
+
return existing;
|
|
1616
|
+
if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
|
|
1617
|
+
throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
|
|
1618
|
+
}
|
|
1619
|
+
const created = options.create({
|
|
1620
|
+
namespace: storageNamespace(key),
|
|
1621
|
+
publicNamespace,
|
|
1622
|
+
sqlite,
|
|
1623
|
+
clock,
|
|
1624
|
+
rng: isolatedRng ?? rng
|
|
1625
|
+
});
|
|
1626
|
+
instances.set(key, created);
|
|
1627
|
+
publicNamespaces.add(publicNamespace);
|
|
1628
|
+
if (isolatedRng)
|
|
1629
|
+
branchRngs.set(key, isolatedRng);
|
|
1630
|
+
return created;
|
|
1631
|
+
};
|
|
1632
|
+
const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
|
|
1633
|
+
const capture = (storage) => {
|
|
1634
|
+
const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
|
|
1635
|
+
const previous = captured.get(storage);
|
|
1636
|
+
const snapshot2 = {
|
|
1637
|
+
namespace: fresh.namespace,
|
|
1638
|
+
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),
|
|
1639
|
+
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)
|
|
1640
|
+
};
|
|
1641
|
+
Object.freeze(snapshot2.records);
|
|
1642
|
+
Object.freeze(snapshot2.sequences);
|
|
1643
|
+
Object.freeze(snapshot2);
|
|
1644
|
+
captured.set(storage, snapshot2);
|
|
1645
|
+
return Object.freeze({
|
|
1646
|
+
snapshot: snapshot2,
|
|
1647
|
+
clock: Object.freeze(clock.state()),
|
|
1648
|
+
rngState: (branchRngs.get(storage) ?? rng).state()
|
|
1649
|
+
});
|
|
1650
|
+
};
|
|
1651
|
+
const timeline = (name = DEFAULT_NAMESPACE) => {
|
|
1652
|
+
let found = timelines.get(name);
|
|
1653
|
+
if (found)
|
|
1654
|
+
return found;
|
|
1655
|
+
instance(name);
|
|
1656
|
+
found = new Timeline({
|
|
1657
|
+
now: clock.now,
|
|
1658
|
+
...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
|
|
1659
|
+
});
|
|
1660
|
+
found.commit(capture(name));
|
|
1661
|
+
timelines.set(name, found);
|
|
1662
|
+
return found;
|
|
1663
|
+
};
|
|
1664
|
+
const physicalBranch = (namespace, branch2) => {
|
|
1665
|
+
if (branch2 === "main")
|
|
1666
|
+
return namespace;
|
|
1667
|
+
const mapKey = `${namespace}\0${branch2}`;
|
|
1668
|
+
const existing = branchStorage.get(mapKey);
|
|
1669
|
+
if (existing)
|
|
1670
|
+
return existing;
|
|
1671
|
+
const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
|
|
1672
|
+
branchStorage.set(mapKey, key);
|
|
1673
|
+
return key;
|
|
1674
|
+
};
|
|
1675
|
+
const ensureBranch = (namespace, branch2, at) => {
|
|
1676
|
+
if (!BRANCH_PATTERN2.test(branch2))
|
|
1677
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
|
|
1678
|
+
const history = timeline(namespace);
|
|
1679
|
+
if (branch2 === "main") {
|
|
1680
|
+
if (at !== void 0) {
|
|
1681
|
+
const point = history.checkout("main", at);
|
|
1682
|
+
restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
|
|
1683
|
+
captured.set(namespace, point.value.snapshot);
|
|
1684
|
+
rng.setState(point.value.rngState);
|
|
1685
|
+
clock.set(point.value.clock.now);
|
|
1686
|
+
if (point.value.clock.frozen)
|
|
1687
|
+
clock.freeze();
|
|
1688
|
+
else
|
|
1689
|
+
clock.unfreeze();
|
|
1690
|
+
}
|
|
1691
|
+
return namespace;
|
|
1692
|
+
}
|
|
1693
|
+
const storage = physicalBranch(namespace, branch2);
|
|
1694
|
+
if (!history.hasBranch(branch2)) {
|
|
1695
|
+
if (at === void 0)
|
|
1696
|
+
history.commit(capture(namespace));
|
|
1697
|
+
const point = history.fork(branch2, at === void 0 ? {} : { from: at });
|
|
1698
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1699
|
+
if (point)
|
|
1700
|
+
branchRng.setState(point.value.rngState);
|
|
1701
|
+
instanceFor(storage, namespace, branchRng);
|
|
1702
|
+
if (point)
|
|
1703
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1704
|
+
if (point)
|
|
1705
|
+
captured.set(storage, point.value.snapshot);
|
|
1706
|
+
} else if (at !== void 0 && history.head(branch2)?.id !== at) {
|
|
1707
|
+
const point = history.checkout(branch2, at);
|
|
1708
|
+
if (!instances.has(storage)) {
|
|
1709
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1710
|
+
branchRng.setState(point.value.rngState);
|
|
1711
|
+
instanceFor(storage, namespace, branchRng);
|
|
1712
|
+
}
|
|
1713
|
+
branchRngs.get(storage)?.setState(point.value.rngState);
|
|
1714
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1715
|
+
captured.set(storage, point.value.snapshot);
|
|
1716
|
+
} else {
|
|
1717
|
+
if (!instances.has(storage)) {
|
|
1718
|
+
const point = history.head(branch2);
|
|
1719
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1720
|
+
if (point)
|
|
1721
|
+
branchRng.setState(point.value.rngState);
|
|
1722
|
+
instanceFor(storage, namespace, branchRng);
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
return storage;
|
|
1726
|
+
};
|
|
1727
|
+
const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
|
|
1728
|
+
const storage = ensureBranch(namespace, branch2);
|
|
1729
|
+
return timeline(namespace).commit(capture(storage), { branch: branch2 });
|
|
1730
|
+
};
|
|
1731
|
+
const branch = (name, branchOptions = {}) => {
|
|
1732
|
+
const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1733
|
+
ensureBranch(namespace, name, branchOptions.at);
|
|
1734
|
+
const head = timeline(namespace).head(name);
|
|
1735
|
+
if (!head)
|
|
1736
|
+
throw new RangeError(`branch ${name} has no checkpoint`);
|
|
1737
|
+
return head;
|
|
1738
|
+
};
|
|
1739
|
+
const checkout = (checkpointId, checkoutOptions = {}) => {
|
|
1740
|
+
const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1741
|
+
const branchName = checkoutOptions.branch ?? "main";
|
|
1742
|
+
const history = timeline(namespace);
|
|
1743
|
+
const point = history.checkout(branchName, checkpointId);
|
|
1744
|
+
const storage = ensureBranch(namespace, branchName);
|
|
1745
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1746
|
+
captured.set(storage, point.value.snapshot);
|
|
1747
|
+
clock.set(point.value.clock.now);
|
|
1748
|
+
if (point.value.clock.frozen)
|
|
1749
|
+
clock.freeze();
|
|
1750
|
+
else
|
|
1751
|
+
clock.unfreeze();
|
|
1752
|
+
(branchRngs.get(storage) ?? rng).setState(point.value.rngState);
|
|
1753
|
+
};
|
|
1754
|
+
const reset = async (name = DEFAULT_NAMESPACE) => {
|
|
1755
|
+
if (name === "*") {
|
|
1756
|
+
options.webhooks?.clear();
|
|
1757
|
+
for (const each of instances.values())
|
|
1758
|
+
await each.reset();
|
|
1759
|
+
timelines.clear();
|
|
1760
|
+
branchStorage.clear();
|
|
1761
|
+
branchRngs.clear();
|
|
1762
|
+
captured.clear();
|
|
1763
|
+
return;
|
|
1764
|
+
}
|
|
1765
|
+
options.webhooks?.clear(name);
|
|
1766
|
+
const target = instances.get(name);
|
|
1767
|
+
if (target)
|
|
1768
|
+
await target.reset();
|
|
1769
|
+
else
|
|
1770
|
+
clearNamespace(sqlite, storageNamespace(name));
|
|
1771
|
+
for (const [mapping, storage] of branchStorage) {
|
|
1772
|
+
if (!mapping.startsWith(`${name}\0`))
|
|
1773
|
+
continue;
|
|
1774
|
+
const branchInstance = instances.get(storage);
|
|
1775
|
+
if (branchInstance)
|
|
1776
|
+
await branchInstance.reset();
|
|
1777
|
+
else
|
|
1778
|
+
clearNamespace(sqlite, storageNamespace(storage));
|
|
1779
|
+
branchStorage.delete(mapping);
|
|
1780
|
+
branchRngs.delete(storage);
|
|
1781
|
+
captured.delete(storage);
|
|
1782
|
+
}
|
|
1783
|
+
timelines.delete(name);
|
|
1784
|
+
captured.delete(name);
|
|
1785
|
+
};
|
|
1786
|
+
const snapshot = (name = DEFAULT_NAMESPACE) => {
|
|
1787
|
+
return checkpoint(name, "main").value.snapshot;
|
|
1788
|
+
};
|
|
1789
|
+
const restore = (from, name = DEFAULT_NAMESPACE) => {
|
|
1790
|
+
instance(name);
|
|
1791
|
+
restoreNamespace(sqlite, storageNamespace(name), from);
|
|
1792
|
+
captured.set(name, from);
|
|
1793
|
+
const history = timelines.get(name);
|
|
1794
|
+
if (history)
|
|
1795
|
+
history.commit(capture(name), { branch: "main" });
|
|
1796
|
+
else
|
|
1797
|
+
timeline(name);
|
|
1798
|
+
};
|
|
1799
|
+
const runtime = {
|
|
1800
|
+
name: options.name,
|
|
1801
|
+
sqlite,
|
|
1802
|
+
clock,
|
|
1803
|
+
faults,
|
|
1804
|
+
metrics,
|
|
1805
|
+
journal,
|
|
1806
|
+
rng,
|
|
1807
|
+
credentials,
|
|
1808
|
+
webhooks: options.webhooks,
|
|
1809
|
+
applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
|
|
1810
|
+
const preset = options.presets?.[name];
|
|
1811
|
+
if (!preset)
|
|
1812
|
+
throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
|
|
1813
|
+
const added = (preset.rules ?? []).map((rule, index) => faults.add({
|
|
1814
|
+
namespace,
|
|
1815
|
+
...rule,
|
|
1816
|
+
...overrides,
|
|
1817
|
+
preset: name,
|
|
1818
|
+
id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
|
|
1819
|
+
}));
|
|
1820
|
+
if (preset.webhook && options.webhooks) {
|
|
1821
|
+
options.webhooks.fault(namespace, {
|
|
1822
|
+
...preset.webhook,
|
|
1823
|
+
...overrides.count !== void 0 ? { count: overrides.count } : {}
|
|
1824
|
+
});
|
|
1825
|
+
}
|
|
1826
|
+
return added;
|
|
1827
|
+
},
|
|
1828
|
+
instance,
|
|
1829
|
+
namespaces: () => [...publicNamespaces].sort(),
|
|
1830
|
+
reset,
|
|
1831
|
+
snapshot,
|
|
1832
|
+
restore,
|
|
1833
|
+
checkpoint,
|
|
1834
|
+
branch,
|
|
1835
|
+
checkout,
|
|
1836
|
+
timeline,
|
|
1837
|
+
fetch: async (incoming) => {
|
|
1838
|
+
let request = incoming;
|
|
1839
|
+
const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
|
|
1840
|
+
if (prefixed) {
|
|
1841
|
+
const url2 = new URL(request.url);
|
|
1842
|
+
url2.pathname = prefixed[2] ?? "/";
|
|
1843
|
+
const headers = new Headers(request.headers);
|
|
1844
|
+
if (!headers.has(NAMESPACE_HEADER)) {
|
|
1845
|
+
headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
|
|
1846
|
+
}
|
|
1847
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
|
1848
|
+
request = new Request(url2, {
|
|
1849
|
+
method: request.method,
|
|
1850
|
+
headers,
|
|
1851
|
+
...hasBody ? { body: await request.arrayBuffer() } : {},
|
|
1852
|
+
signal: request.signal
|
|
1853
|
+
});
|
|
1854
|
+
}
|
|
1855
|
+
let namespace = control.namespaceOf(request);
|
|
1856
|
+
if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
|
|
1857
|
+
const credential = options.credential(request);
|
|
1858
|
+
const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
|
|
1859
|
+
if (mapped !== void 0)
|
|
1860
|
+
namespace = mapped;
|
|
1861
|
+
}
|
|
1862
|
+
const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
|
|
1863
|
+
const at = request.headers.get(AT_HEADER) ?? void 0;
|
|
1864
|
+
const stamp = (response2) => {
|
|
1865
|
+
const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
|
|
1866
|
+
try {
|
|
1867
|
+
response2.headers.set(MOCKINGBIRD_HEADER, value);
|
|
1868
|
+
return response2;
|
|
1869
|
+
} catch {
|
|
1870
|
+
const copy = new Response(response2.body, response2);
|
|
1871
|
+
copy.headers.set(MOCKINGBIRD_HEADER, value);
|
|
1872
|
+
return copy;
|
|
1873
|
+
}
|
|
1874
|
+
};
|
|
1875
|
+
const handled = await control.handle(request);
|
|
1876
|
+
if (handled)
|
|
1877
|
+
return stamp(handled);
|
|
1878
|
+
const started = monotonicNow();
|
|
1879
|
+
const url = new URL(request.url);
|
|
1880
|
+
const operationId = operationIdFor(request, url.pathname);
|
|
1881
|
+
const log = (status, faultId, response2) => {
|
|
1882
|
+
const noted = response2 ? responseNotes(response2) : void 0;
|
|
1883
|
+
const entry = {
|
|
1884
|
+
service: options.name,
|
|
1885
|
+
namespace,
|
|
1886
|
+
operationId,
|
|
1887
|
+
method: request.method,
|
|
1888
|
+
path: url.pathname,
|
|
1889
|
+
status,
|
|
1890
|
+
durationMs: Math.round((monotonicNow() - started) * 100) / 100,
|
|
1891
|
+
unmatched: options.document !== void 0 && operationId === void 0,
|
|
1892
|
+
...faultId !== void 0 ? { faultId } : {},
|
|
1893
|
+
...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
|
|
1894
|
+
...noted?.adopted ? { adopted: true } : {}
|
|
1895
|
+
};
|
|
1896
|
+
metrics.record(entry);
|
|
1897
|
+
journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
|
|
1898
|
+
options.onLog?.(entry);
|
|
1899
|
+
};
|
|
1900
|
+
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
1901
|
+
log(400);
|
|
1902
|
+
return stamp(new Response(JSON.stringify({
|
|
1903
|
+
error: {
|
|
1904
|
+
type: "mockingbird_admin",
|
|
1905
|
+
message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
|
|
1906
|
+
}
|
|
1907
|
+
}), { status: 400, headers: { "content-type": "application/json" } }));
|
|
1908
|
+
}
|
|
1909
|
+
if (!BRANCH_PATTERN2.test(selectedBranch)) {
|
|
1910
|
+
log(400);
|
|
1911
|
+
return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
|
|
1912
|
+
}
|
|
1913
|
+
let storage;
|
|
1914
|
+
try {
|
|
1915
|
+
if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
|
|
1916
|
+
const point = timeline(namespace).get(at);
|
|
1917
|
+
storage = physicalBranch(namespace, `at_${at}`);
|
|
1918
|
+
let viewRng = branchRngs.get(storage);
|
|
1919
|
+
if (!viewRng) {
|
|
1920
|
+
viewRng = createRng(options.seed ?? 0);
|
|
1921
|
+
instanceFor(storage, namespace, viewRng);
|
|
1922
|
+
}
|
|
1923
|
+
viewRng.setState(point.value.rngState);
|
|
1924
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1925
|
+
captured.set(storage, point.value.snapshot);
|
|
1926
|
+
} else {
|
|
1927
|
+
storage = ensureBranch(namespace, selectedBranch, at);
|
|
1928
|
+
}
|
|
1929
|
+
} catch (error2) {
|
|
1930
|
+
log(409);
|
|
1931
|
+
return stamp(adminFail(409, error2 instanceof Error ? error2.message : String(error2)));
|
|
1932
|
+
}
|
|
1933
|
+
const hits = await faults.take({
|
|
1934
|
+
operationId,
|
|
1935
|
+
method: request.method,
|
|
1936
|
+
path: url.pathname,
|
|
1937
|
+
namespace
|
|
1938
|
+
});
|
|
1939
|
+
const final = hits.find((hit) => hit.drop || hit.response);
|
|
1940
|
+
if (final?.drop) {
|
|
1941
|
+
log(0, final.id);
|
|
1942
|
+
throw new DroppedConnectionError();
|
|
1943
|
+
}
|
|
1944
|
+
if (final?.response) {
|
|
1945
|
+
log(final.response.status, final.id);
|
|
1946
|
+
return stamp(final.response);
|
|
1947
|
+
}
|
|
1948
|
+
const fired = hits.filter((hit) => hit.effect !== void 0);
|
|
1949
|
+
if (fired.length > 0)
|
|
1950
|
+
effects.set(request, fired.map((hit) => hit.effect));
|
|
1951
|
+
let response = await instanceFor(storage, namespace).fetch(request);
|
|
1952
|
+
if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
|
|
1953
|
+
const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
|
|
1954
|
+
response = mutableResponse(response);
|
|
1955
|
+
response.headers.set(CHECKPOINT_HEADER, point.id);
|
|
1956
|
+
}
|
|
1957
|
+
if (selectedBranch !== "main") {
|
|
1958
|
+
response = mutableResponse(response);
|
|
1959
|
+
response.headers.set(BRANCH_HEADER, selectedBranch);
|
|
1960
|
+
}
|
|
1961
|
+
if (at !== void 0) {
|
|
1962
|
+
response = mutableResponse(response);
|
|
1963
|
+
response.headers.set(AT_HEADER, at);
|
|
1964
|
+
}
|
|
1965
|
+
log(response.status, fired[0]?.id, response);
|
|
1966
|
+
return stamp(response);
|
|
1967
|
+
}
|
|
1968
|
+
};
|
|
1969
|
+
const control = createControlPlane({
|
|
1970
|
+
name: options.name,
|
|
1971
|
+
startedAt: wallNow(),
|
|
1972
|
+
wallNow,
|
|
1973
|
+
clock,
|
|
1974
|
+
faults,
|
|
1975
|
+
metrics,
|
|
1976
|
+
journal,
|
|
1977
|
+
defaultNamespace: DEFAULT_NAMESPACE,
|
|
1978
|
+
namespaces: runtime.namespaces,
|
|
1979
|
+
reset,
|
|
1980
|
+
timeTravel: {
|
|
1981
|
+
checkpoint: (name, branchName) => {
|
|
1982
|
+
const point = checkpoint(name, branchName);
|
|
1983
|
+
return {
|
|
1984
|
+
id: point.id,
|
|
1985
|
+
branch: point.branch,
|
|
1986
|
+
parent: point.parent,
|
|
1987
|
+
at: point.at,
|
|
1988
|
+
records: point.value.snapshot.records.length
|
|
1989
|
+
};
|
|
1990
|
+
},
|
|
1991
|
+
branch: (branchName, branchOptions) => {
|
|
1992
|
+
const point = branch(branchName, branchOptions);
|
|
1993
|
+
return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
|
|
1994
|
+
},
|
|
1995
|
+
checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
|
|
1996
|
+
retain: (name, checkpointId) => {
|
|
1997
|
+
timeline(name).retain(checkpointId);
|
|
1998
|
+
},
|
|
1999
|
+
release: (name, checkpointId) => timeline(name).release(checkpointId),
|
|
2000
|
+
inspect: (name) => {
|
|
2001
|
+
const history = timeline(name);
|
|
2002
|
+
return {
|
|
2003
|
+
branches: history.branches(),
|
|
2004
|
+
checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
|
|
2005
|
+
id,
|
|
2006
|
+
branch: branchName,
|
|
2007
|
+
parent,
|
|
2008
|
+
at
|
|
2009
|
+
}))
|
|
2010
|
+
};
|
|
2011
|
+
}
|
|
2012
|
+
},
|
|
2013
|
+
describe: options.describe ?? (() => ({})),
|
|
2014
|
+
...options.presets ? {
|
|
2015
|
+
applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
|
|
2016
|
+
} : {},
|
|
2017
|
+
routes: {
|
|
2018
|
+
...credentialRoutes(credentials),
|
|
2019
|
+
...options.presets ? presetRoutes(options.presets, runtime) : {},
|
|
2020
|
+
...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
|
|
2021
|
+
...options.admin?.(runtime) ?? {}
|
|
2022
|
+
},
|
|
2023
|
+
adminKey: options.adminKey
|
|
2024
|
+
});
|
|
2025
|
+
return runtime;
|
|
2026
|
+
};
|
|
2027
|
+
var mutableResponse = (response) => {
|
|
2028
|
+
try {
|
|
2029
|
+
response.headers.set("x-mockingbird-mutable-probe", "1");
|
|
2030
|
+
response.headers.delete("x-mockingbird-mutable-probe");
|
|
2031
|
+
return response;
|
|
2032
|
+
} catch {
|
|
2033
|
+
return new Response(response.body, response);
|
|
2034
|
+
}
|
|
2035
|
+
};
|
|
2036
|
+
var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2037
|
+
var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
|
|
2038
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2039
|
+
var credentialRoutes = (registry) => ({
|
|
2040
|
+
"GET /credentials": () => adminJson(200, {
|
|
2041
|
+
credentials: registry.entries().map(({ credential, namespace }) => ({
|
|
2042
|
+
credential: maskCredential(credential),
|
|
2043
|
+
namespace
|
|
2044
|
+
}))
|
|
2045
|
+
}),
|
|
2046
|
+
"PUT /credentials": ({ body, namespace }) => {
|
|
2047
|
+
const pairs = [];
|
|
2048
|
+
const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
|
|
2049
|
+
if (Array.isArray(list)) {
|
|
2050
|
+
for (const each of list) {
|
|
2051
|
+
if (typeof each === "string")
|
|
2052
|
+
pairs.push([each, namespace]);
|
|
2053
|
+
else if (isObject(each) && typeof each.credential === "string") {
|
|
2054
|
+
pairs.push([
|
|
2055
|
+
each.credential,
|
|
2056
|
+
typeof each.namespace === "string" ? each.namespace : namespace
|
|
2057
|
+
]);
|
|
2058
|
+
} else
|
|
2059
|
+
return adminFail(400, "each entry is a credential string or {credential, namespace}");
|
|
2060
|
+
}
|
|
2061
|
+
} else if (isObject(list)) {
|
|
2062
|
+
for (const [credential, target] of Object.entries(list)) {
|
|
2063
|
+
if (typeof target !== "string")
|
|
2064
|
+
return adminFail(400, `namespace for ${credential} must be a string`);
|
|
2065
|
+
pairs.push([credential, target]);
|
|
2066
|
+
}
|
|
2067
|
+
} else if (isObject(body) && typeof body.credential === "string") {
|
|
2068
|
+
pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
|
|
2069
|
+
} else {
|
|
2070
|
+
return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
|
|
2071
|
+
}
|
|
2072
|
+
for (const [credential, target] of pairs) {
|
|
2073
|
+
if (!NAMESPACE_PATTERN.test(target))
|
|
2074
|
+
return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
|
|
2075
|
+
registry.set(credential, target);
|
|
2076
|
+
}
|
|
2077
|
+
return adminJson(200, { mapped: pairs.length });
|
|
2078
|
+
},
|
|
2079
|
+
"DELETE /credentials": ({ url }) => {
|
|
2080
|
+
const credential = url.searchParams.get("credential");
|
|
2081
|
+
if (credential === null)
|
|
2082
|
+
registry.clear();
|
|
2083
|
+
else
|
|
2084
|
+
registry.remove(credential);
|
|
2085
|
+
return adminJson(200, { status: "ok" });
|
|
2086
|
+
}
|
|
2087
|
+
});
|
|
2088
|
+
var presetRoutes = (presets, runtime) => ({
|
|
2089
|
+
"GET /faults/presets": () => adminJson(200, {
|
|
2090
|
+
presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
|
|
2091
|
+
}),
|
|
2092
|
+
"POST /faults/presets/:name": ({ params, body, namespace }) => {
|
|
2093
|
+
const name = params.name;
|
|
2094
|
+
if (!presets[name])
|
|
2095
|
+
return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
|
|
2096
|
+
const overrides = isObject(body) ? body : {};
|
|
2097
|
+
return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
|
|
2098
|
+
}
|
|
2099
|
+
});
|
|
2100
|
+
|
|
2101
|
+
// ../core/dist/validation.js
|
|
2102
|
+
var bodyIssues = (context, contentType = "application/json") => {
|
|
2103
|
+
const requestBody = context.operation.operation.requestBody;
|
|
2104
|
+
if (!requestBody)
|
|
2105
|
+
return [];
|
|
2106
|
+
const resolved = deref(context.document, requestBody);
|
|
2107
|
+
const schema = resolved.content?.[contentType]?.schema;
|
|
2108
|
+
if (!schema)
|
|
2109
|
+
return [];
|
|
2110
|
+
const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
|
|
2111
|
+
if (context.body.kind === "invalid") {
|
|
2112
|
+
return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
|
|
2113
|
+
}
|
|
2114
|
+
if (value === void 0) {
|
|
2115
|
+
return resolved.required ? [{ path: "", message: "request body is required" }] : [];
|
|
2116
|
+
}
|
|
2117
|
+
return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
|
|
2118
|
+
};
|
|
2119
|
+
|
|
2120
|
+
// src/generated/openapi.ts
|
|
2121
|
+
var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Legacy Makor AI API \\"CPG\\" (Mockingbird subset)","description":"Stateful mock subset of the legacy Makor AI (\\"CPG\\") API: care-plan details and the plus-user\\ntoggle (Intercom sync, user-actions queue), the bloodwork-results webhook (ODX), subscription\\nand Wholescripts order reads, AI patient summaries and async-review scripts (called\\nbrowser-direct from the EMR frontend). Not the in-repo makor-ecosystem gateway.\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from the consumer's wire shapes: backend makor-ai.types.ts and makor-ai-client.service.ts; EMR frontend cpg-api.ts, user-summary.service.ts, async-review-script.service.ts and types/async-review-script.types.ts. The vendor publishes no spec."}},"servers":[{"url":"https://makor-ai-api.up.railway.app"}],"security":[{"apiKey":[]}],"paths":{"/api/care-plans/current-care-plan-details/{userId}":{"parameters":[{"$ref":"#/components/parameters/UserId"}],"get":{"operationId":"GetCurrentCarePlan","description":"A 404 naming the user means \\"no active or approved care plan\\" (the normal case).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The current care plan","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CarePlanStatus"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/api/care-plans/plus-user/{userId}":{"parameters":[{"$ref":"#/components/parameters/UserId"}],"patch":{"operationId":"UpdatePlusUser","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["plusUser"],"properties":{"plusUser":{"type":"boolean"}}}}}},"responses":{"200":{"description":"Updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessMessage"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/api/bloodwork/webhook":{"post":{"operationId":"BloodworkResultsReceived","description":"ODX tells Makor new lab results exist; accepted asynchronously (202).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["userId","labResultsId"],"properties":{"userId":{"type":"string","minLength":1,"maxLength":40},"labResultsId":{"type":"string","minLength":1,"maxLength":80}}}}}},"responses":{"202":{"description":"Accepted","content":{"application/json":{"schema":{"type":"object","required":["message"],"properties":{"message":{"type":"string"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/api/subscription/cancel/{userId}":{"parameters":[{"$ref":"#/components/parameters/UserId"}],"post":{"operationId":"CancelSubscription","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Cancelled, already cancelled, or nothing to cancel","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CancelSubscriptionResponse"}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/api/subscription/status/{userId}":{"parameters":[{"$ref":"#/components/parameters/UserId"}],"get":{"operationId":"GetSubscriptionStatus","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The subscription, or hasActiveSubscription false","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubscriptionStatus"}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/api/wholescripts-orders/user/{userId}":{"parameters":[{"$ref":"#/components/parameters/UserId"}],"get":{"operationId":"GetWholescriptsOrders","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"page","in":"query","schema":{"type":"integer","minimum":1,"maximum":50}},{"name":"count","in":"query","schema":{"type":"integer","minimum":1,"maximum":100}}],"responses":{"200":{"description":"A page of orders","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OrderHistoryResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/api/v2/generate-user-summary":{"post":{"operationId":"GenerateUserSummary","description":"Synchronous: answers the finished summary and stores it as the user's most recent. The real server takes 30-50 s; the mock answers at once (preset slow_generation adds it back).","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GenerateUserSummaryRequest"}}}},"responses":{"200":{"description":"The generated summary","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FullUserSummary"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"500":{"$ref":"#/components/responses/ServerError"}}}},"/api/v2/user-summary/{cpgUserId}":{"parameters":[{"name":"cpgUserId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"user","missing":"999999999"}}}],"get":{"operationId":"GetUserSummary","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The most recent summary","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserSummaryResponse"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/api/async-review-script/{userId}/{labTestId}":{"parameters":[{"$ref":"#/components/parameters/UserId"},{"$ref":"#/components/parameters/LabTestId"}],"get":{"operationId":"GetReviewScript","description":"The most recent review for the lab test; \`processing\` until N ms have passed on the mock clock.","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The review","content":{"application/json":{"schema":{"type":"object","required":["review"],"properties":{"review":{"$ref":"#/components/schemas/AsyncReviewScript"}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/api/async-review-script/generate":{"post":{"operationId":"GenerateReviewScript","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"allOf":[{"type":"object","required":["userId","labTestId"],"properties":{"userId":{"type":"string","minLength":1,"maxLength":40,"x-mockingbird-resource-ref":{"type":"user","missing":"999999999"}},"labTestId":{"$ref":"#/components/schemas/LabTestIdValue"}}},{"$ref":"#/components/schemas/ReviewScriptOptions"}]}}}},"responses":{"200":{"description":"Generated (complete) or accepted (processing)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/GenerateReviewResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"500":{"description":"Generation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/GenerateReviewResponse"}}}}}}},"/api/async-review-script/regenerate/{userId}/{labTestId}":{"parameters":[{"$ref":"#/components/parameters/UserId"},{"$ref":"#/components/parameters/LabTestId"}],"post":{"operationId":"RegenerateReviewScript","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewScriptOptions"}}}},"responses":{"200":{"description":"Regenerated (complete) or accepted (processing)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/GenerateReviewResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"description":"Generation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/GenerateReviewResponse"}}}}}}}},"components":{"securitySchemes":{"apiKey":{"type":"apiKey","in":"header","name":"x-api-key"}},"parameters":{"UserId":{"name":"userId","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"user","missing":"999999999"}}},"LabTestId":{"name":"labTestId","in":"path","required":true,"schema":{"$ref":"#/components/schemas/LabTestIdValue"}}},"responses":{"BadRequest":{"description":"Invalid request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"Unauthorized":{"description":"Missing or unknown x-api-key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"NotFound":{"description":"No such record for this user (a normal outcome)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"ServerError":{"description":"Generation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}},"schemas":{"LabTestIdValue":{"description":"Any non-empty id. The first branch only steers the walk generator toward a small alphabet, so random walks revisit the lab tests they generated scripts for.","anyOf":[{"type":"string","pattern":"^lab_[0-3]$"},{"type":"string","minLength":1,"maxLength":80}]},"ErrorResponse":{"type":"object","required":["error"],"properties":{"error":{"type":"string"},"message":{"type":"string"},"statusCode":{"type":"integer"}}},"SuccessMessage":{"type":"object","required":["success"],"properties":{"success":{"type":"boolean"},"message":{"type":"string"}}},"Pricing":{"type":"object","required":["subtotal_cents","shipping_cents","tax_cents","total_cost_cents_before_discount","total_cost_cents","discount_percent","discount_type"],"properties":{"subtotal_cents":{"type":"number"},"shipping_cents":{"type":"number"},"tax_cents":{"type":"number"},"total_cost_cents_before_discount":{"type":"number"},"total_cost_cents":{"type":"number"},"discount_percent":{"type":["number","null"]},"discount_type":{"type":["string","null"]}}},"CarePlanStatus":{"type":"object","required":["carePlanId","status","pricing","state"],"properties":{"carePlanId":{"type":"string"},"status":{"type":"string"},"pricing":{"$ref":"#/components/schemas/Pricing"},"state":{"type":"string"}}},"SubscriptionStatusData":{"type":"object","required":["id","user_id","status"],"properties":{"id":{"type":"string"},"user_id":{"type":"string"},"stripe_customer_id":{"type":["string","null"]},"stripe_subscription_id":{"type":["string","null"]},"stripe_checkout_session_id":{"type":["string","null"]},"checkout_url":{"type":["string","null"]},"cp_id":{"type":["string","null"]},"price_cents":{"type":["number","null"]},"subtotal_price":{},"tax_cents":{"type":["number","null"]},"shipping_cents":{"type":["number","null"]},"discount_percent":{"type":["number","null"]},"coupon_id":{"type":["string","null"]},"interval_days":{"type":["number","null"]},"idempotency_key":{"type":["string","null"]},"subscription_intent_id":{"type":["string","null"]},"stripe_latest_invoice_id":{"type":["string","null"]},"status_reason":{"type":["string","null"]},"status":{"type":"string"},"last_fulfilled_invoice_id":{"type":["string","null"]},"next_renewal_date":{"type":["string","null"]},"last_invoice_paid_at":{"type":["string","null"]},"created_at":{"type":["string","null"]},"updated_at":{"type":["string","null"]}}},"SubscriptionStatus":{"type":"object","required":["success","data"],"properties":{"success":{"type":"boolean"},"data":{"oneOf":[{"$ref":"#/components/schemas/SubscriptionStatusData"},{"type":"object","required":["hasActiveSubscription"],"properties":{"hasActiveSubscription":{"type":"boolean"},"message":{"type":"string"}}}]}}},"CancelSubscriptionResponse":{"type":"object","required":["success","data"],"properties":{"success":{"type":"boolean"},"data":{"oneOf":[{"type":"object","required":["subscription_id","status"],"properties":{"subscription_id":{"type":"string"},"status":{"type":"string"},"message":{"type":"string"}}},{"type":"object","required":["success"],"properties":{"success":{"type":"boolean"},"message":{"type":"string"},"alreadyCancelled":{"type":"boolean"}}}]}}},"OrderItem":{"type":"object","required":["id","carePlanId","invoiceId","wholeScriptsOrderId","status","tracking","supplements"],"properties":{"id":{"type":"number"},"carePlanId":{"type":"string"},"invoiceId":{"type":"string"},"wholeScriptsOrderId":{"type":"string"},"submitSuccess":{"type":"boolean"},"orderDate":{"type":"string"},"status":{"type":"string"},"tracking":{"type":"array","items":{"type":"object"}},"shipMethod":{"type":"string"},"supplements":{"type":"array","items":{"type":"object"}},"billingCycle":{"type":"number"},"needsPolling":{"type":"boolean"},"lastPolled":{"type":"string"},"pricingSnapshot":{"type":"object"},"createdAt":{"type":"string"},"updatedAt":{"type":"string"},"activeCarePlan":{"type":"boolean"}}},"OrderHistoryResponse":{"type":"object","required":["data","page","count","total","totalPages"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/OrderItem"}},"page":{"type":"number"},"count":{"type":"number"},"total":{"type":"number"},"totalPages":{"type":"number"}}},"GenerateUserSummaryRequest":{"type":"object","required":["user_id"],"properties":{"user_id":{"type":"string","minLength":1,"maxLength":40,"pattern":"\\\\S"},"intake_forms":{"type":"array","maxItems":4,"items":{"type":"object","required":["title","content"],"properties":{"title":{"type":"string","maxLength":80},"content":{"type":"string","maxLength":400}}}},"free_text_entries":{"type":"array","maxItems":4,"items":{"type":"object","required":["entry_id","text"],"properties":{"entry_id":{"type":"string","maxLength":40},"timestamp":{"type":"string","maxLength":40},"text":{"type":"string","maxLength":400}}}},"llm_model":{"type":"string","maxLength":60}}},"Biomarker":{"type":"object","required":["biomarker_name","value","optimal_range","standard_range","severity_category"],"properties":{"biomarker_name":{"type":"string"},"value":{"type":"number"},"optimal_range":{"type":"array","items":{"type":"number"}},"standard_range":{"type":"array","items":{"type":"number"}},"severity_category":{"type":"string"}}},"BiomarkerAnalysis":{"description":"A single test's analysis, or the with-trends shape (both are passed through).","type":"object","additionalProperties":true},"FullUserSummary":{"type":"object","required":["user_id","summary","biomarker_analysis"],"properties":{"user_id":{"type":"string","x-mockingbird-resource":{"type":"user","identity":true}},"summary":{"type":"object","required":["general_summary","past_visits"],"properties":{"general_summary":{"type":"array","items":{"type":"string"}},"past_visits":{"type":"array","items":{"type":"string"}},"intake_summary":{"type":"array","items":{"type":"string"}}}},"biomarker_analysis":{"$ref":"#/components/schemas/BiomarkerAnalysis"}}},"UserSummaryResponse":{"type":"object","required":["cpgUserId","summary","isMostRecent","createdAt"],"properties":{"cpgUserId":{"type":"string"},"summary":{"$ref":"#/components/schemas/FullUserSummary"},"isMostRecent":{"type":"boolean"},"createdAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"ReviewScriptOptions":{"type":"object","properties":{"intakeForm":{"type":"string","maxLength":400},"chartingNotes":{"type":"array","maxItems":3,"items":{"type":"object","required":["content"],"properties":{"title":{"type":"string","maxLength":80},"content":{"type":"string","maxLength":400},"created_at":{"type":"string","maxLength":40},"provider_name":{"type":"string","maxLength":80}}}},"demographics":{"type":"object","properties":{"first_name":{"type":"string","maxLength":40},"last_name":{"type":"string","maxLength":40},"age":{"type":"integer","minimum":0,"maximum":120},"state":{"type":"string","maxLength":2}}}}},"LabFinding":{"type":"object","required":["marker","value","status","interpretation"],"properties":{"marker":{"type":"string"},"value":{"type":"string"},"previousValue":{"type":"string"},"status":{"type":"string","enum":["optimal","low","high","trending_low","trending_high"]},"interpretation":{"type":"string"}}},"ScriptContent":{"type":"object","required":["overview","labFindings","symptomsVsLabChanges","nutritionRecommendations","fiberGuidance","supplementRecommendations","lifestyleRecommendations","reflectionQuestions"],"properties":{"overview":{"type":"object","required":["summary","patterns"],"properties":{"summary":{"type":"string"},"patterns":{"type":"array","items":{"type":"string"}}}},"labFindings":{"type":"object","required":["thyroid","stressAdrenal","metabolicBloodSugar","inflammationImmune","nutrientStatus"],"properties":{"thyroid":{"type":"array","items":{"$ref":"#/components/schemas/LabFinding"}},"stressAdrenal":{"type":"array","items":{"$ref":"#/components/schemas/LabFinding"}},"metabolicBloodSugar":{"type":"array","items":{"$ref":"#/components/schemas/LabFinding"}},"inflammationImmune":{"type":"array","items":{"$ref":"#/components/schemas/LabFinding"}},"nutrientStatus":{"type":"array","items":{"$ref":"#/components/schemas/LabFinding"}}}},"symptomsVsLabChanges":{"type":"array","items":{"type":"object","required":["observation","labEvidence"],"properties":{"observation":{"type":"string"},"labEvidence":{"type":"string"}}}},"nutritionRecommendations":{"type":"array","items":{"type":"object","required":["recommendation","rationale","priority"],"properties":{"recommendation":{"type":"string"},"rationale":{"type":"string"},"priority":{"type":"string","enum":["high","medium","low"]}}}},"fiberGuidance":{"type":"object","required":["included","categories"],"properties":{"included":{"type":"boolean"},"categories":{"type":"array","items":{"type":"object","required":["category","options","howToAdd"],"properties":{"category":{"type":"string"},"options":{"type":"string"},"howToAdd":{"type":"string"}}}}}},"supplementRecommendations":{"type":"array","items":{"type":"object","required":["supplement","purpose","relevance","timing"],"properties":{"supplement":{"type":"string"},"purpose":{"type":"string"},"relevance":{"type":"string"},"timing":{"type":["string","null"]}}}},"lifestyleRecommendations":{"type":"array","items":{"type":"object","required":["area","recommendation"],"properties":{"area":{"type":"string"},"recommendation":{"type":"string"}}}},"reflectionQuestions":{"type":"array","items":{"type":"string"}}}},"AsyncReviewScript":{"type":"object","required":["id","labTestId","reviewType","status","scriptContent","createdAt","updatedAt"],"properties":{"id":{"type":"integer"},"labTestId":{"type":"string"},"reviewType":{"type":"string","enum":["initial","comparative"]},"status":{"type":"string","enum":["processing","complete","failed"]},"scriptContent":{"oneOf":[{"$ref":"#/components/schemas/ScriptContent"},{"type":"null"}]},"errorMessage":{"type":["string","null"]},"metadata":{"type":"object","required":["inputTokens","outputTokens","model","partialParse","generatedAt"],"properties":{"inputTokens":{"type":"integer"},"outputTokens":{"type":"integer"},"model":{"type":"string"},"partialParse":{"type":"boolean"},"generatedAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"isMostRecent":{"type":"boolean"},"createdAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"updatedAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"GenerateReviewResponse":{"type":"object","required":["message","reviewId","status","reviewType","scriptContent"],"properties":{"message":{"type":"string"},"reviewId":{"type":"integer"},"status":{"type":"string","enum":["processing","complete","failed"]},"reviewType":{"type":"string","enum":["initial","comparative"]},"scriptContent":{"oneOf":[{"$ref":"#/components/schemas/ScriptContent"},{"type":"null"}]},"errorMessage":{"type":"string"}}}}}}`);
|
|
2122
|
+
var operationIds = ["GetCurrentCarePlan", "UpdatePlusUser", "BloodworkResultsReceived", "CancelSubscription", "GetSubscriptionStatus", "GetWholescriptsOrders", "GenerateUserSummary", "GetUserSummary", "GetReviewScript", "GenerateReviewScript", "RegenerateReviewScript"];
|
|
2123
|
+
var supportedOperationIds = ["GetCurrentCarePlan", "UpdatePlusUser", "BloodworkResultsReceived", "CancelSubscription", "GetSubscriptionStatus", "GetWholescriptsOrders", "GenerateUserSummary", "GetUserSummary", "GetReviewScript", "GenerateReviewScript", "RegenerateReviewScript"];
|
|
2124
|
+
|
|
2125
|
+
// src/state.ts
|
|
2126
|
+
var DEFAULT_SETTINGS = { apiKeys: [], processingMs: 0 };
|
|
2127
|
+
var summaryKey = (userId) => `summary:${userId}`;
|
|
2128
|
+
var reviewKey = (userId, labTestId) => `review:${userId}:${labTestId}`;
|
|
2129
|
+
var MakorCpgState = class {
|
|
2130
|
+
constructor(sqlite, namespace, seed) {
|
|
2131
|
+
this.seed = seed;
|
|
2132
|
+
this.carePlans = new Collection(sqlite, namespace, "care_plans");
|
|
2133
|
+
this.subscriptions = new Collection(sqlite, namespace, "subscriptions");
|
|
2134
|
+
this.orders = new Collection(sqlite, namespace, "wholescripts_orders");
|
|
2135
|
+
this.summaries = new Collection(sqlite, namespace, "summaries");
|
|
2136
|
+
this.reviews = new Collection(sqlite, namespace, "reviews");
|
|
2137
|
+
this.bloodwork = new Collection(sqlite, namespace, "bloodwork_webhooks");
|
|
2138
|
+
this.summaryFixtures = new Collection(sqlite, namespace, "summary_fixtures");
|
|
2139
|
+
this.reviewFixtures = new Collection(sqlite, namespace, "review_fixtures");
|
|
2140
|
+
this.settings = new Collection(sqlite, namespace, "settings");
|
|
2141
|
+
this.ensureSeeded();
|
|
2142
|
+
}
|
|
2143
|
+
seed;
|
|
2144
|
+
carePlans;
|
|
2145
|
+
subscriptions;
|
|
2146
|
+
orders;
|
|
2147
|
+
summaries;
|
|
2148
|
+
reviews;
|
|
2149
|
+
bloodwork;
|
|
2150
|
+
summaryFixtures;
|
|
2151
|
+
reviewFixtures;
|
|
2152
|
+
settings;
|
|
2153
|
+
ensureSeeded() {
|
|
2154
|
+
if (!this.settings.has("settings")) {
|
|
2155
|
+
this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed.settings });
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
current() {
|
|
2159
|
+
return this.settings.get("settings") ?? DEFAULT_SETTINGS;
|
|
2160
|
+
}
|
|
2161
|
+
update(patch) {
|
|
2162
|
+
const next = { ...this.current(), ...patch };
|
|
2163
|
+
this.settings.insert("settings", next);
|
|
2164
|
+
return next;
|
|
2165
|
+
}
|
|
2166
|
+
setSummaryFixture(userId, fixture) {
|
|
2167
|
+
this.summaryFixtures.insert(summaryKey(userId), fixture);
|
|
2168
|
+
}
|
|
2169
|
+
/** The user's own fixture, else the `*` fixture. */
|
|
2170
|
+
summaryFixture(userId) {
|
|
2171
|
+
return this.summaryFixtures.get(summaryKey(userId)) ?? this.summaryFixtures.get(summaryKey("*"));
|
|
2172
|
+
}
|
|
2173
|
+
setReviewFixture(userId, labTestId, content) {
|
|
2174
|
+
this.reviewFixtures.insert(reviewKey(userId, labTestId), content);
|
|
2175
|
+
}
|
|
2176
|
+
/** Most specific first: user + lab test, user, lab test, then `*`. */
|
|
2177
|
+
reviewFixture(userId, labTestId) {
|
|
2178
|
+
for (const key of [
|
|
2179
|
+
reviewKey(userId, labTestId),
|
|
2180
|
+
reviewKey(userId, "*"),
|
|
2181
|
+
reviewKey("*", labTestId),
|
|
2182
|
+
reviewKey("*", "*")
|
|
2183
|
+
]) {
|
|
2184
|
+
const found = this.reviewFixtures.get(key);
|
|
2185
|
+
if (found) return found;
|
|
2186
|
+
}
|
|
2187
|
+
return void 0;
|
|
2188
|
+
}
|
|
2189
|
+
/** The user's summaries, newest first. */
|
|
2190
|
+
summariesOf(userId) {
|
|
2191
|
+
return this.summaries.list({ where: (s) => s.cpgUserId === userId }).map((row) => row.value);
|
|
2192
|
+
}
|
|
2193
|
+
addSummary(record) {
|
|
2194
|
+
this.summaries.insert(`${record.cpgUserId}/${this.summaries.nextSequence()}`, record);
|
|
2195
|
+
}
|
|
2196
|
+
/** Reviews for one user (optionally one lab test), newest first. */
|
|
2197
|
+
reviewsOf(userId, labTestId) {
|
|
2198
|
+
return this.reviews.list({
|
|
2199
|
+
where: (r) => r.userId === userId && (labTestId === void 0 || r.labTestId === labTestId)
|
|
2200
|
+
}).map((row) => row.value);
|
|
2201
|
+
}
|
|
2202
|
+
nextReviewId() {
|
|
2203
|
+
return this.reviews.count() + 1;
|
|
2204
|
+
}
|
|
2205
|
+
};
|
|
2206
|
+
|
|
2207
|
+
// src/runtime.ts
|
|
2208
|
+
var GENERATION_OPS = ["GenerateUserSummary", "GenerateReviewScript", "RegenerateReviewScript"];
|
|
2209
|
+
var MAKOR_CPG_PRESETS = {
|
|
2210
|
+
slow_generation: {
|
|
2211
|
+
description: "Summary and review-script generation take 40 s, the real server's 30-50 s (override with latencyMs); the EMR's 50 s summary timeout is the edge",
|
|
2212
|
+
rules: GENERATION_OPS.map((operationId) => ({ operationId, latencyMs: 4e4 }))
|
|
2213
|
+
},
|
|
2214
|
+
generation_failed: {
|
|
2215
|
+
description: "Generation fails: summaries answer 500; review scripts answer 500 {status: 'failed', errorMessage} and store a failed review",
|
|
2216
|
+
rules: GENERATION_OPS.map((operationId) => ({ operationId, effect: "generation_failed" }))
|
|
2217
|
+
},
|
|
2218
|
+
care_plan_invalid_shape: {
|
|
2219
|
+
description: "Care-plan details answer 200 without pricing (the backend's schema check fails: 'Invalid response format', null)",
|
|
2220
|
+
rules: [{ operationId: "GetCurrentCarePlan", effect: "care_plan_invalid_shape" }]
|
|
2221
|
+
},
|
|
2222
|
+
bloodwork_not_accepted: {
|
|
2223
|
+
description: "The bloodwork webhook answers 200 instead of 202 (the backend warns and returns null)",
|
|
2224
|
+
rules: [{ operationId: "BloodworkResultsReceived", effect: "bloodwork_not_accepted" }]
|
|
2225
|
+
},
|
|
2226
|
+
route_missing: {
|
|
2227
|
+
description: "Every call answers 404 'Cannot GET \u2026': a wrong route, which the backend logs at error level (unlike the no-plan 404)",
|
|
2228
|
+
rules: [{ pathPrefix: "/api/", effect: "route_missing" }]
|
|
2229
|
+
},
|
|
2230
|
+
unauthorized: {
|
|
2231
|
+
description: "Every call answers 401 Invalid API key",
|
|
2232
|
+
rules: [
|
|
2233
|
+
{
|
|
2234
|
+
pathPrefix: "/api/",
|
|
2235
|
+
status: 401,
|
|
2236
|
+
body: { error: "Unauthorized", message: "Invalid API key", statusCode: 401 }
|
|
2237
|
+
}
|
|
2238
|
+
]
|
|
2239
|
+
},
|
|
2240
|
+
server_error: {
|
|
2241
|
+
description: "Every call answers 500",
|
|
2242
|
+
rules: [
|
|
2243
|
+
{
|
|
2244
|
+
pathPrefix: "/api/",
|
|
2245
|
+
status: 500,
|
|
2246
|
+
body: { error: "Internal Server Error", message: "Something went wrong", statusCode: 500 }
|
|
2247
|
+
}
|
|
2248
|
+
]
|
|
2249
|
+
}
|
|
2250
|
+
};
|
|
2251
|
+
var CORS_HEADERS = {
|
|
2252
|
+
"access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
|
|
2253
|
+
"access-control-allow-headers": "content-type, x-api-key, x-mockingbird-namespace, authorization",
|
|
2254
|
+
"access-control-expose-headers": "x-mockingbird",
|
|
2255
|
+
"access-control-max-age": "600"
|
|
2256
|
+
};
|
|
2257
|
+
var corsHeaders = (request) => ({
|
|
2258
|
+
...CORS_HEADERS,
|
|
2259
|
+
"access-control-allow-origin": request.headers.get("origin") ?? "*",
|
|
2260
|
+
...request.headers.get("access-control-request-headers") ? {
|
|
2261
|
+
"access-control-allow-headers": request.headers.get(
|
|
2262
|
+
"access-control-request-headers"
|
|
2263
|
+
)
|
|
2264
|
+
} : {},
|
|
2265
|
+
vary: "Origin"
|
|
2266
|
+
});
|
|
2267
|
+
var withCors = (request, response) => {
|
|
2268
|
+
const headers = corsHeaders(request);
|
|
2269
|
+
try {
|
|
2270
|
+
for (const [name, value] of Object.entries(headers)) response.headers.set(name, value);
|
|
2271
|
+
return response;
|
|
2272
|
+
} catch {
|
|
2273
|
+
const copy = new Response(response.body, response);
|
|
2274
|
+
for (const [name, value] of Object.entries(headers)) copy.headers.set(name, value);
|
|
2275
|
+
return copy;
|
|
2276
|
+
}
|
|
2277
|
+
};
|
|
2278
|
+
var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2279
|
+
var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
|
|
2280
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2281
|
+
var DEFAULT_PRICING = {
|
|
2282
|
+
subtotal_cents: 18900,
|
|
2283
|
+
shipping_cents: 0,
|
|
2284
|
+
tax_cents: 1512,
|
|
2285
|
+
total_cost_cents_before_discount: 20412,
|
|
2286
|
+
total_cost_cents: 20412,
|
|
2287
|
+
discount_percent: null,
|
|
2288
|
+
discount_type: null
|
|
2289
|
+
};
|
|
2290
|
+
var subscriptionRow = (userId, patch, at) => ({
|
|
2291
|
+
id: `sub_row_${userId}`,
|
|
2292
|
+
user_id: userId,
|
|
2293
|
+
stripe_customer_id: `cus_mock_${userId}`,
|
|
2294
|
+
stripe_subscription_id: `sub_mock_${userId}`,
|
|
2295
|
+
stripe_checkout_session_id: null,
|
|
2296
|
+
checkout_url: null,
|
|
2297
|
+
cp_id: null,
|
|
2298
|
+
price_cents: 18900,
|
|
2299
|
+
subtotal_price: null,
|
|
2300
|
+
tax_cents: 1512,
|
|
2301
|
+
shipping_cents: 0,
|
|
2302
|
+
discount_percent: null,
|
|
2303
|
+
coupon_id: null,
|
|
2304
|
+
interval_days: 30,
|
|
2305
|
+
idempotency_key: null,
|
|
2306
|
+
subscription_intent_id: null,
|
|
2307
|
+
stripe_latest_invoice_id: null,
|
|
2308
|
+
status_reason: null,
|
|
2309
|
+
status: "active",
|
|
2310
|
+
last_fulfilled_invoice_id: null,
|
|
2311
|
+
next_renewal_date: null,
|
|
2312
|
+
last_invoice_paid_at: null,
|
|
2313
|
+
created_at: at,
|
|
2314
|
+
updated_at: at,
|
|
2315
|
+
...patch
|
|
2316
|
+
});
|
|
2317
|
+
var isScript = (value) => isRecord4(value) && isRecord4(value.overview) && isRecord4(value.labFindings);
|
|
2318
|
+
var adminRoutes = (runtime) => {
|
|
2319
|
+
const state = (namespace) => runtime.instance(namespace).state;
|
|
2320
|
+
const iso = () => new Date(runtime.clock.now()).toISOString();
|
|
2321
|
+
return {
|
|
2322
|
+
"GET /care-plans/:userId": ({ params, namespace }) => {
|
|
2323
|
+
const plan = state(namespace).carePlans.get(params.userId);
|
|
2324
|
+
return plan ? json3(200, plan) : adminError3(404, `no care plan for ${params.userId}`);
|
|
2325
|
+
},
|
|
2326
|
+
"PUT /care-plans/:userId": ({ params, body, namespace }) => {
|
|
2327
|
+
if (!isRecord4(body))
|
|
2328
|
+
return adminError3(400, "expected {carePlanId?, status?, pricing?, state?}");
|
|
2329
|
+
const userId = params.userId;
|
|
2330
|
+
const plan = {
|
|
2331
|
+
carePlanId: typeof body.carePlanId === "string" ? body.carePlanId : `cp_${userId}`,
|
|
2332
|
+
status: typeof body.status === "string" ? body.status : "Active",
|
|
2333
|
+
pricing: {
|
|
2334
|
+
...DEFAULT_PRICING,
|
|
2335
|
+
...isRecord4(body.pricing) ? body.pricing : {}
|
|
2336
|
+
},
|
|
2337
|
+
state: typeof body.state === "string" ? body.state : "TX",
|
|
2338
|
+
plusUser: body.plusUser === true
|
|
2339
|
+
};
|
|
2340
|
+
state(namespace).carePlans.insert(userId, plan);
|
|
2341
|
+
return json3(200, plan);
|
|
2342
|
+
},
|
|
2343
|
+
"DELETE /care-plans/:userId": ({ params, namespace }) => json3(200, { deleted: state(namespace).carePlans.delete(params.userId) }),
|
|
2344
|
+
"PUT /subscriptions/:userId": ({ params, body, namespace }) => {
|
|
2345
|
+
if (!isRecord4(body)) return adminError3(400, "expected subscription fields (status, \u2026)");
|
|
2346
|
+
const row = subscriptionRow(params.userId, body, iso());
|
|
2347
|
+
state(namespace).subscriptions.insert(params.userId, row);
|
|
2348
|
+
return json3(200, row);
|
|
2349
|
+
},
|
|
2350
|
+
"PUT /wholescripts-orders/:userId": ({ params, body, namespace }) => {
|
|
2351
|
+
const list = Array.isArray(body) ? body : isRecord4(body) ? body.orders : void 0;
|
|
2352
|
+
if (!Array.isArray(list) || !list.every(isRecord4)) {
|
|
2353
|
+
return adminError3(400, "expected [order, \u2026] or {orders: [order, \u2026]}");
|
|
2354
|
+
}
|
|
2355
|
+
const orders = list.map((order, index) => ({ id: index + 1, ...order }));
|
|
2356
|
+
state(namespace).orders.insert(params.userId, orders);
|
|
2357
|
+
return json3(200, { orders });
|
|
2358
|
+
},
|
|
2359
|
+
"GET /bloodwork": ({ namespace }) => json3(200, {
|
|
2360
|
+
webhooks: state(namespace).bloodwork.list({ order: "oldest" }).map((row) => row.value)
|
|
2361
|
+
}),
|
|
2362
|
+
"PUT /fixtures/summary": ({ body, namespace }) => {
|
|
2363
|
+
if (!isRecord4(body) || !isRecord4(body.summary)) {
|
|
2364
|
+
return adminError3(
|
|
2365
|
+
400,
|
|
2366
|
+
"expected {userId?, summary: {general_summary, past_visits}, biomarker_analysis?}"
|
|
2367
|
+
);
|
|
2368
|
+
}
|
|
2369
|
+
const userId = typeof body.userId === "string" ? body.userId : "*";
|
|
2370
|
+
const fixture = {
|
|
2371
|
+
summary: body.summary,
|
|
2372
|
+
biomarker_analysis: isRecord4(body.biomarker_analysis) ? body.biomarker_analysis : {}
|
|
2373
|
+
};
|
|
2374
|
+
state(namespace).setSummaryFixture(userId, fixture);
|
|
2375
|
+
return json3(200, { userId, ...fixture });
|
|
2376
|
+
},
|
|
2377
|
+
"PUT /fixtures/review-script": ({ body, namespace }) => {
|
|
2378
|
+
if (!isRecord4(body) || !isScript(body.scriptContent)) {
|
|
2379
|
+
return adminError3(400, "expected {userId?, labTestId?, scriptContent: ScriptContent}");
|
|
2380
|
+
}
|
|
2381
|
+
const userId = typeof body.userId === "string" ? body.userId : "*";
|
|
2382
|
+
const labTestId = typeof body.labTestId === "string" ? body.labTestId : "*";
|
|
2383
|
+
state(namespace).setReviewFixture(userId, labTestId, body.scriptContent);
|
|
2384
|
+
return json3(200, { userId, labTestId });
|
|
2385
|
+
},
|
|
2386
|
+
"POST /summaries": ({ body, namespace }) => {
|
|
2387
|
+
if (!isRecord4(body) || typeof body.cpgUserId !== "string") {
|
|
2388
|
+
return adminError3(
|
|
2389
|
+
400,
|
|
2390
|
+
"expected {cpgUserId, summary?: {summary, biomarker_analysis}, createdAt?}"
|
|
2391
|
+
);
|
|
2392
|
+
}
|
|
2393
|
+
const given = isRecord4(body.summary) ? body.summary : {};
|
|
2394
|
+
const summary = {
|
|
2395
|
+
user_id: body.cpgUserId,
|
|
2396
|
+
summary: isRecord4(given.summary) ? given.summary : {
|
|
2397
|
+
general_summary: ["Seeded summary (mock)."],
|
|
2398
|
+
past_visits: []
|
|
2399
|
+
},
|
|
2400
|
+
biomarker_analysis: isRecord4(given.biomarker_analysis) ? given.biomarker_analysis : {}
|
|
2401
|
+
};
|
|
2402
|
+
const record = {
|
|
2403
|
+
cpgUserId: body.cpgUserId,
|
|
2404
|
+
summary,
|
|
2405
|
+
createdAt: typeof body.createdAt === "string" ? body.createdAt : iso()
|
|
2406
|
+
};
|
|
2407
|
+
state(namespace).addSummary(record);
|
|
2408
|
+
return json3(201, record);
|
|
2409
|
+
},
|
|
2410
|
+
"GET /reviews": ({ url, namespace }) => {
|
|
2411
|
+
const userId = url.searchParams.get("userId");
|
|
2412
|
+
const rows = state(namespace).reviews.list({ order: "oldest" }).map((row) => row.value).filter((review) => userId === null || review.userId === userId);
|
|
2413
|
+
return json3(200, { reviews: rows });
|
|
2414
|
+
},
|
|
2415
|
+
"POST /reviews": ({ body, namespace }) => {
|
|
2416
|
+
if (!isRecord4(body) || typeof body.userId !== "string" || typeof body.labTestId !== "string") {
|
|
2417
|
+
return adminError3(400, "expected {userId, labTestId, status?, scriptContent?, reviewType?}");
|
|
2418
|
+
}
|
|
2419
|
+
const s = state(namespace);
|
|
2420
|
+
const status = body.status === "processing" || body.status === "failed" ? body.status : "complete";
|
|
2421
|
+
const content = isScript(body.scriptContent) ? body.scriptContent : defaultScriptContent(body.labTestId);
|
|
2422
|
+
const at = runtime.clock.now();
|
|
2423
|
+
const review = {
|
|
2424
|
+
id: s.nextReviewId(),
|
|
2425
|
+
userId: body.userId,
|
|
2426
|
+
labTestId: body.labTestId,
|
|
2427
|
+
reviewType: body.reviewType === "comparative" ? "comparative" : "initial",
|
|
2428
|
+
status,
|
|
2429
|
+
pending: content,
|
|
2430
|
+
scriptContent: status === "complete" ? content : null,
|
|
2431
|
+
errorMessage: status === "failed" ? typeof body.errorMessage === "string" ? body.errorMessage : "Review generation failed (seeded)" : null,
|
|
2432
|
+
createdAt: new Date(at).toISOString(),
|
|
2433
|
+
updatedAt: new Date(at).toISOString(),
|
|
2434
|
+
readyAtMs: status === "processing" ? at + (typeof body.readyInMs === "number" ? body.readyInMs : s.current().processingMs) : at
|
|
2435
|
+
};
|
|
2436
|
+
s.reviews.insert(String(review.id), review);
|
|
2437
|
+
return json3(201, review);
|
|
2438
|
+
},
|
|
2439
|
+
"GET /settings": ({ namespace }) => json3(200, state(namespace).current()),
|
|
2440
|
+
"PUT /settings": ({ body, namespace }) => {
|
|
2441
|
+
if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
|
|
2442
|
+
const patch = {};
|
|
2443
|
+
if (body.apiKeys !== void 0) {
|
|
2444
|
+
if (!Array.isArray(body.apiKeys)) return adminError3(400, "apiKeys: string[]");
|
|
2445
|
+
patch.apiKeys = body.apiKeys.map(String);
|
|
2446
|
+
}
|
|
2447
|
+
if (body.processingMs !== void 0) {
|
|
2448
|
+
if (typeof body.processingMs !== "number" || body.processingMs < 0)
|
|
2449
|
+
return adminError3(400, "processingMs: ms >= 0");
|
|
2450
|
+
patch.processingMs = body.processingMs;
|
|
2451
|
+
}
|
|
2452
|
+
return json3(200, state(namespace).update(patch));
|
|
2453
|
+
},
|
|
2454
|
+
"POST /tick": ({ namespace }) => json3(200, { settled: runtime.instance(namespace).tick() })
|
|
2455
|
+
};
|
|
2456
|
+
};
|
|
2457
|
+
var createRuntime2 = (options = {}) => {
|
|
2458
|
+
const runtime = createRuntime({
|
|
2459
|
+
name: MAKOR_CPG_NAMESPACE,
|
|
2460
|
+
document,
|
|
2461
|
+
...options.sqlite ? { sqlite: options.sqlite } : {},
|
|
2462
|
+
...options.clock ? { clock: options.clock } : {},
|
|
2463
|
+
...options.seed !== void 0 ? { seed: options.seed } : {},
|
|
2464
|
+
...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
|
|
2465
|
+
...options.onLog ? { onLog: options.onLog } : {},
|
|
2466
|
+
credential: apiKeyCredential,
|
|
2467
|
+
presets: MAKOR_CPG_PRESETS,
|
|
2468
|
+
create: ({ sqlite, namespace, clock }) => new MakorCpgAPI({
|
|
2469
|
+
sqlite,
|
|
2470
|
+
namespace,
|
|
2471
|
+
now: clock.now,
|
|
2472
|
+
...options.settings ? { settings: options.settings } : {}
|
|
2473
|
+
}),
|
|
2474
|
+
admin: adminRoutes
|
|
2475
|
+
});
|
|
2476
|
+
const inner = runtime.fetch;
|
|
2477
|
+
return Object.assign(runtime, {
|
|
2478
|
+
fetch: async (request) => {
|
|
2479
|
+
if (request.method === "OPTIONS") {
|
|
2480
|
+
return withCors(request, new Response(null, { status: 204 }));
|
|
2481
|
+
}
|
|
2482
|
+
return withCors(request, await inner(request));
|
|
2483
|
+
}
|
|
2484
|
+
});
|
|
2485
|
+
};
|
|
2486
|
+
|
|
2487
|
+
// src/index.ts
|
|
2488
|
+
var MAKOR_CPG_NAMESPACE = "makor-cpg";
|
|
2489
|
+
var NO_CARE_PLAN_MESSAGE = "No active or approved care plan found for this user";
|
|
2490
|
+
var apiKeyCredential = (request) => request.headers.get("x-api-key")?.trim() || void 0;
|
|
2491
|
+
var error = (status, name, message) => jsonRes(status, { error: name, message, statusCode: status });
|
|
2492
|
+
var notFound = (message) => error(404, "Not Found", message);
|
|
2493
|
+
var badRequest = (message) => error(400, "Bad Request", message);
|
|
2494
|
+
var describeIssues = (issues) => issues.map((issue) => `${issue.path || "body"}: ${issue.message}`).join("; ");
|
|
2495
|
+
var emptyAnalysis = (testDate) => ({
|
|
2496
|
+
test_date: testDate,
|
|
2497
|
+
total_out_of_range: 0,
|
|
2498
|
+
total_optimal: 0,
|
|
2499
|
+
by_severity: {
|
|
2500
|
+
alarm_high: [],
|
|
2501
|
+
alarm_low: [],
|
|
2502
|
+
out_of_standard_high: [],
|
|
2503
|
+
out_of_standard_low: [],
|
|
2504
|
+
out_of_optimal_high: [],
|
|
2505
|
+
out_of_optimal_low: []
|
|
2506
|
+
}
|
|
2507
|
+
});
|
|
2508
|
+
var defaultScriptContent = (labTestId) => ({
|
|
2509
|
+
overview: {
|
|
2510
|
+
summary: `Mock async review script for lab test ${labTestId}.`,
|
|
2511
|
+
patterns: ["No clinically significant patterns (mock)."]
|
|
2512
|
+
},
|
|
2513
|
+
labFindings: {
|
|
2514
|
+
thyroid: [
|
|
2515
|
+
{
|
|
2516
|
+
marker: "TSH",
|
|
2517
|
+
value: "1.8 mIU/L",
|
|
2518
|
+
status: "optimal",
|
|
2519
|
+
interpretation: "Within the optimal range (mock)."
|
|
2520
|
+
}
|
|
2521
|
+
],
|
|
2522
|
+
stressAdrenal: [],
|
|
2523
|
+
metabolicBloodSugar: [
|
|
2524
|
+
{
|
|
2525
|
+
marker: "HbA1c",
|
|
2526
|
+
value: "5.2 %",
|
|
2527
|
+
status: "optimal",
|
|
2528
|
+
interpretation: "Within the optimal range (mock)."
|
|
2529
|
+
}
|
|
2530
|
+
],
|
|
2531
|
+
inflammationImmune: [],
|
|
2532
|
+
nutrientStatus: [
|
|
2533
|
+
{
|
|
2534
|
+
marker: "Vitamin D",
|
|
2535
|
+
value: "28 ng/mL",
|
|
2536
|
+
status: "low",
|
|
2537
|
+
interpretation: "Below the optimal range (mock)."
|
|
2538
|
+
}
|
|
2539
|
+
]
|
|
2540
|
+
},
|
|
2541
|
+
symptomsVsLabChanges: [],
|
|
2542
|
+
nutritionRecommendations: [
|
|
2543
|
+
{
|
|
2544
|
+
recommendation: "Add a daily serving of fatty fish.",
|
|
2545
|
+
rationale: "Supports vitamin D status (mock).",
|
|
2546
|
+
priority: "medium"
|
|
2547
|
+
}
|
|
2548
|
+
],
|
|
2549
|
+
fiberGuidance: {
|
|
2550
|
+
included: true,
|
|
2551
|
+
categories: [
|
|
2552
|
+
{
|
|
2553
|
+
category: "Legumes",
|
|
2554
|
+
options: "Lentils, chickpeas, black beans",
|
|
2555
|
+
howToAdd: "Half a cup with lunch."
|
|
2556
|
+
}
|
|
2557
|
+
]
|
|
2558
|
+
},
|
|
2559
|
+
supplementRecommendations: [
|
|
2560
|
+
{
|
|
2561
|
+
supplement: "Vitamin D3",
|
|
2562
|
+
purpose: "Raise vitamin D toward optimal",
|
|
2563
|
+
relevance: "Vitamin D below optimal (mock).",
|
|
2564
|
+
timing: "Morning, with food"
|
|
2565
|
+
}
|
|
2566
|
+
],
|
|
2567
|
+
lifestyleRecommendations: [{ area: "Sleep", recommendation: "Keep a consistent schedule." }],
|
|
2568
|
+
reflectionQuestions: ["How has your energy been over the last month?"]
|
|
2569
|
+
});
|
|
2570
|
+
var MakorCpgAPI = class {
|
|
2571
|
+
app;
|
|
2572
|
+
sqlite;
|
|
2573
|
+
state;
|
|
2574
|
+
service;
|
|
2575
|
+
now;
|
|
2576
|
+
constructor(options = {}) {
|
|
2577
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
2578
|
+
const namespace = options.namespace ?? MAKOR_CPG_NAMESPACE;
|
|
2579
|
+
this.now = options.now ?? (() => Date.now());
|
|
2580
|
+
this.state = new MakorCpgState(sqlite, namespace, { settings: options.settings ?? {} });
|
|
2581
|
+
const handlers = defineOperations({
|
|
2582
|
+
GetCurrentCarePlan: (context) => this.getCarePlan(context),
|
|
2583
|
+
UpdatePlusUser: (context) => this.updatePlusUser(context),
|
|
2584
|
+
BloodworkResultsReceived: (context) => this.bloodworkReceived(context),
|
|
2585
|
+
CancelSubscription: (context) => this.cancelSubscription(context),
|
|
2586
|
+
GetSubscriptionStatus: (context) => this.subscriptionStatus(context),
|
|
2587
|
+
GetWholescriptsOrders: (context) => this.wholescriptsOrders(context),
|
|
2588
|
+
GenerateUserSummary: (context) => this.generateSummary(context),
|
|
2589
|
+
GetUserSummary: (context) => this.getSummary(context),
|
|
2590
|
+
GetReviewScript: (context) => this.getReview(context),
|
|
2591
|
+
GenerateReviewScript: (context) => this.generateReview(context, "generate"),
|
|
2592
|
+
RegenerateReviewScript: (context) => this.generateReview(context, "regenerate")
|
|
2593
|
+
});
|
|
2594
|
+
this.service = createService({
|
|
2595
|
+
document,
|
|
2596
|
+
handlers,
|
|
2597
|
+
sqlite,
|
|
2598
|
+
namespace,
|
|
2599
|
+
now: this.now,
|
|
2600
|
+
notFound: (request) => notFound(`Cannot ${request.method} ${new URL(request.url).pathname}`),
|
|
2601
|
+
onError: (thrown) => {
|
|
2602
|
+
if (thrown instanceof HttpError) return thrown.toResponse();
|
|
2603
|
+
throw thrown;
|
|
2604
|
+
},
|
|
2605
|
+
before: (context) => {
|
|
2606
|
+
const key = apiKeyCredential(context.request);
|
|
2607
|
+
if (!key) return error(401, "Unauthorized", "Missing API key");
|
|
2608
|
+
const keys = this.state.current().apiKeys;
|
|
2609
|
+
if (keys.length > 0 && !keys.includes(key)) {
|
|
2610
|
+
return error(401, "Unauthorized", "Invalid API key");
|
|
2611
|
+
}
|
|
2612
|
+
if (faultEffect(context.request, "route_missing") !== void 0) {
|
|
2613
|
+
return notFound(`Cannot ${context.request.method} ${context.url.pathname}`);
|
|
2614
|
+
}
|
|
2615
|
+
return void 0;
|
|
2616
|
+
}
|
|
2617
|
+
});
|
|
2618
|
+
this.app = this.service.app;
|
|
2619
|
+
this.sqlite = this.service.sqlite;
|
|
2620
|
+
}
|
|
2621
|
+
fetch(request) {
|
|
2622
|
+
return this.service.fetch(request);
|
|
2623
|
+
}
|
|
2624
|
+
async reset() {
|
|
2625
|
+
await this.service.reset();
|
|
2626
|
+
this.state.ensureSeeded();
|
|
2627
|
+
}
|
|
2628
|
+
iso(ms = this.now()) {
|
|
2629
|
+
return new Date(ms).toISOString();
|
|
2630
|
+
}
|
|
2631
|
+
body(context) {
|
|
2632
|
+
return context.body.kind === "json" && typeof context.body.value === "object" && context.body.value !== null && !Array.isArray(context.body.value) ? context.body.value : {};
|
|
2633
|
+
}
|
|
2634
|
+
getCarePlan(context) {
|
|
2635
|
+
const userId = context.params.userId ?? "";
|
|
2636
|
+
const plan = this.state.carePlans.get(userId);
|
|
2637
|
+
if (!plan) return annotateResponse(notFound(NO_CARE_PLAN_MESSAGE), { ids: { userId } });
|
|
2638
|
+
const { plusUser: _plusUser, ...body } = plan;
|
|
2639
|
+
if (faultEffect(context.request, "care_plan_invalid_shape") !== void 0) {
|
|
2640
|
+
const { pricing: _pricing, ...partial } = body;
|
|
2641
|
+
return jsonRes(200, partial);
|
|
2642
|
+
}
|
|
2643
|
+
return annotateResponse(jsonRes(200, body), { ids: { userId, carePlanId: plan.carePlanId } });
|
|
2644
|
+
}
|
|
2645
|
+
updatePlusUser(context) {
|
|
2646
|
+
const issues = bodyIssues(context);
|
|
2647
|
+
if (issues.length > 0) return badRequest(describeIssues(issues));
|
|
2648
|
+
const userId = context.params.userId ?? "";
|
|
2649
|
+
const plan = this.state.carePlans.get(userId);
|
|
2650
|
+
if (!plan) return notFound(NO_CARE_PLAN_MESSAGE);
|
|
2651
|
+
const plusUser = this.body(context).plusUser === true;
|
|
2652
|
+
this.state.carePlans.update(userId, { ...plan, plusUser });
|
|
2653
|
+
return annotateResponse(
|
|
2654
|
+
jsonRes(200, {
|
|
2655
|
+
success: true,
|
|
2656
|
+
message: `Plus user ${plusUser ? "enabled" : "disabled"} for care plan ${plan.carePlanId}`
|
|
2657
|
+
}),
|
|
2658
|
+
{ ids: { userId, carePlanId: plan.carePlanId } }
|
|
2659
|
+
);
|
|
2660
|
+
}
|
|
2661
|
+
bloodworkReceived(context) {
|
|
2662
|
+
const issues = bodyIssues(context);
|
|
2663
|
+
if (issues.length > 0) return badRequest(describeIssues(issues));
|
|
2664
|
+
const body = this.body(context);
|
|
2665
|
+
const record = {
|
|
2666
|
+
userId: String(body.userId),
|
|
2667
|
+
labResultsId: String(body.labResultsId),
|
|
2668
|
+
receivedAt: this.iso()
|
|
2669
|
+
};
|
|
2670
|
+
this.state.bloodwork.insert(`bw_${this.state.bloodwork.nextSequence()}`, record);
|
|
2671
|
+
const ids = { userId: record.userId, labResultsId: record.labResultsId };
|
|
2672
|
+
if (faultEffect(context.request, "bloodwork_not_accepted") !== void 0) {
|
|
2673
|
+
return annotateResponse(jsonRes(200, { message: "Webhook processed" }), { ids });
|
|
2674
|
+
}
|
|
2675
|
+
return annotateResponse(jsonRes(202, { message: "Webhook received" }), { ids });
|
|
2676
|
+
}
|
|
2677
|
+
subscriptionStatus(context) {
|
|
2678
|
+
const userId = context.params.userId ?? "";
|
|
2679
|
+
const subscription = this.state.subscriptions.get(userId);
|
|
2680
|
+
const active = subscription && !/cancel/i.test(subscription.status);
|
|
2681
|
+
return jsonRes(200, {
|
|
2682
|
+
success: true,
|
|
2683
|
+
data: active ? subscription : { hasActiveSubscription: false, message: "No active subscription found for this user" }
|
|
2684
|
+
});
|
|
2685
|
+
}
|
|
2686
|
+
cancelSubscription(context) {
|
|
2687
|
+
const userId = context.params.userId ?? "";
|
|
2688
|
+
const subscription = this.state.subscriptions.get(userId);
|
|
2689
|
+
if (!subscription) {
|
|
2690
|
+
return jsonRes(200, {
|
|
2691
|
+
success: true,
|
|
2692
|
+
data: { success: false, message: "No subscription found for this user" }
|
|
2693
|
+
});
|
|
2694
|
+
}
|
|
2695
|
+
if (/cancel/i.test(subscription.status)) {
|
|
2696
|
+
return jsonRes(200, {
|
|
2697
|
+
success: true,
|
|
2698
|
+
data: { success: true, message: "Subscription already cancelled", alreadyCancelled: true }
|
|
2699
|
+
});
|
|
2700
|
+
}
|
|
2701
|
+
this.state.subscriptions.update(userId, {
|
|
2702
|
+
...subscription,
|
|
2703
|
+
status: "canceled",
|
|
2704
|
+
status_reason: "cancelled_via_api",
|
|
2705
|
+
updated_at: this.iso()
|
|
2706
|
+
});
|
|
2707
|
+
return annotateResponse(
|
|
2708
|
+
jsonRes(200, {
|
|
2709
|
+
success: true,
|
|
2710
|
+
data: {
|
|
2711
|
+
subscription_id: String(subscription.stripe_subscription_id ?? subscription.id),
|
|
2712
|
+
status: "canceled",
|
|
2713
|
+
message: "Subscription cancelled"
|
|
2714
|
+
}
|
|
2715
|
+
}),
|
|
2716
|
+
{ ids: { userId, subscriptionId: subscription.id } }
|
|
2717
|
+
);
|
|
2718
|
+
}
|
|
2719
|
+
wholescriptsOrders(context) {
|
|
2720
|
+
const page = context.query.page === void 0 ? 1 : Number(context.query.page);
|
|
2721
|
+
const count = context.query.count === void 0 ? 10 : Number(context.query.count);
|
|
2722
|
+
if (!Number.isInteger(page) || page < 1 || !Number.isInteger(count) || count < 1) {
|
|
2723
|
+
return badRequest("page and count must be positive integers");
|
|
2724
|
+
}
|
|
2725
|
+
const orders = this.state.orders.get(context.params.userId ?? "") ?? [];
|
|
2726
|
+
return jsonRes(200, {
|
|
2727
|
+
data: orders.slice((page - 1) * count, page * count),
|
|
2728
|
+
page,
|
|
2729
|
+
count,
|
|
2730
|
+
total: orders.length,
|
|
2731
|
+
totalPages: Math.ceil(orders.length / count)
|
|
2732
|
+
});
|
|
2733
|
+
}
|
|
2734
|
+
generateSummary(context) {
|
|
2735
|
+
const issues = bodyIssues(context);
|
|
2736
|
+
if (issues.length > 0) return badRequest(describeIssues(issues));
|
|
2737
|
+
const body = this.body(context);
|
|
2738
|
+
const userId = String(body.user_id).trim();
|
|
2739
|
+
if (faultEffect(context.request, "generation_failed") !== void 0) {
|
|
2740
|
+
return error(500, "Internal Server Error", "Failed to generate user summary");
|
|
2741
|
+
}
|
|
2742
|
+
const forms = Array.isArray(body.intake_forms) ? body.intake_forms.length : 0;
|
|
2743
|
+
const notes2 = Array.isArray(body.free_text_entries) ? body.free_text_entries.length : 0;
|
|
2744
|
+
const fixture = this.state.summaryFixture(userId);
|
|
2745
|
+
const summary = {
|
|
2746
|
+
user_id: userId,
|
|
2747
|
+
summary: fixture?.summary ?? {
|
|
2748
|
+
general_summary: [
|
|
2749
|
+
`Mock summary for user ${userId}: ${forms} intake form(s) and ${notes2} visit note(s) reviewed.`
|
|
2750
|
+
],
|
|
2751
|
+
past_visits: notes2 > 0 ? [`${notes2} visit note(s) on file.`] : [],
|
|
2752
|
+
intake_summary: forms > 0 ? [`${forms} intake form(s) on file.`] : []
|
|
2753
|
+
},
|
|
2754
|
+
biomarker_analysis: fixture?.biomarker_analysis ?? emptyAnalysis(this.iso().slice(0, 10))
|
|
2755
|
+
};
|
|
2756
|
+
this.state.addSummary({ cpgUserId: userId, summary, createdAt: this.iso() });
|
|
2757
|
+
return annotateResponse(jsonRes(200, summary), { ids: { userId } });
|
|
2758
|
+
}
|
|
2759
|
+
getSummary(context) {
|
|
2760
|
+
const userId = context.params.cpgUserId ?? "";
|
|
2761
|
+
const latest = this.state.summariesOf(userId)[0];
|
|
2762
|
+
if (!latest) return notFound("No summary found for this user");
|
|
2763
|
+
return annotateResponse(
|
|
2764
|
+
jsonRes(200, {
|
|
2765
|
+
cpgUserId: latest.cpgUserId,
|
|
2766
|
+
summary: latest.summary,
|
|
2767
|
+
isMostRecent: true,
|
|
2768
|
+
createdAt: latest.createdAt
|
|
2769
|
+
}),
|
|
2770
|
+
{ ids: { userId } }
|
|
2771
|
+
);
|
|
2772
|
+
}
|
|
2773
|
+
/** Complete a processing review once its time has come on the mock clock. */
|
|
2774
|
+
settle(review) {
|
|
2775
|
+
if (review.status !== "processing" || this.now() < review.readyAtMs) return review;
|
|
2776
|
+
const done = {
|
|
2777
|
+
...review,
|
|
2778
|
+
status: "complete",
|
|
2779
|
+
scriptContent: review.pending,
|
|
2780
|
+
updatedAt: this.iso(review.readyAtMs)
|
|
2781
|
+
};
|
|
2782
|
+
this.state.reviews.update(String(review.id), done);
|
|
2783
|
+
return done;
|
|
2784
|
+
}
|
|
2785
|
+
/** Complete every review that is due. Runs on reads and on `POST /__admin/tick`. */
|
|
2786
|
+
tick() {
|
|
2787
|
+
let settled = 0;
|
|
2788
|
+
for (const { value } of this.state.reviews.list()) {
|
|
2789
|
+
if (this.settle(value) !== value) settled++;
|
|
2790
|
+
}
|
|
2791
|
+
return settled;
|
|
2792
|
+
}
|
|
2793
|
+
reviewBody(review, isMostRecent) {
|
|
2794
|
+
return {
|
|
2795
|
+
id: review.id,
|
|
2796
|
+
labTestId: review.labTestId,
|
|
2797
|
+
reviewType: review.reviewType,
|
|
2798
|
+
status: review.status,
|
|
2799
|
+
scriptContent: review.scriptContent,
|
|
2800
|
+
errorMessage: review.errorMessage,
|
|
2801
|
+
metadata: {
|
|
2802
|
+
inputTokens: 0,
|
|
2803
|
+
outputTokens: 0,
|
|
2804
|
+
model: "mockingbird",
|
|
2805
|
+
partialParse: false,
|
|
2806
|
+
generatedAt: review.updatedAt
|
|
2807
|
+
},
|
|
2808
|
+
isMostRecent,
|
|
2809
|
+
createdAt: review.createdAt,
|
|
2810
|
+
updatedAt: review.updatedAt
|
|
2811
|
+
};
|
|
2812
|
+
}
|
|
2813
|
+
getReview(context) {
|
|
2814
|
+
const userId = context.params.userId ?? "";
|
|
2815
|
+
const labTestId = context.params.labTestId ?? "";
|
|
2816
|
+
const latest = this.state.reviewsOf(userId, labTestId)[0];
|
|
2817
|
+
if (!latest) return notFound("No review script found for this lab test");
|
|
2818
|
+
return annotateResponse(jsonRes(200, { review: this.reviewBody(this.settle(latest), true) }), {
|
|
2819
|
+
ids: { userId, labTestId, reviewId: String(latest.id) }
|
|
2820
|
+
});
|
|
2821
|
+
}
|
|
2822
|
+
generateReview(context, mode) {
|
|
2823
|
+
const issues = bodyIssues(context);
|
|
2824
|
+
if (issues.length > 0) return badRequest(describeIssues(issues));
|
|
2825
|
+
const body = this.body(context);
|
|
2826
|
+
const userId = mode === "generate" ? String(body.userId).trim() : context.params.userId ?? "";
|
|
2827
|
+
const labTestId = mode === "generate" ? String(body.labTestId).trim() : context.params.labTestId ?? "";
|
|
2828
|
+
if (!userId || !labTestId) return badRequest("userId and labTestId are required");
|
|
2829
|
+
const previous = this.state.reviewsOf(userId, labTestId)[0];
|
|
2830
|
+
if (mode === "regenerate" && !previous) {
|
|
2831
|
+
return notFound("No review script found for this lab test");
|
|
2832
|
+
}
|
|
2833
|
+
const reviewType = previous?.reviewType ?? (this.state.reviewsOf(userId).some((r) => r.labTestId !== labTestId) ? "comparative" : "initial");
|
|
2834
|
+
const content = this.state.reviewFixture(userId, labTestId) ?? defaultScriptContent(labTestId);
|
|
2835
|
+
const failed = faultEffect(context.request, "generation_failed") !== void 0;
|
|
2836
|
+
const processingMs = this.state.current().processingMs;
|
|
2837
|
+
const now = this.now();
|
|
2838
|
+
const status = failed ? "failed" : processingMs > 0 ? "processing" : "complete";
|
|
2839
|
+
const review = {
|
|
2840
|
+
id: this.state.nextReviewId(),
|
|
2841
|
+
userId,
|
|
2842
|
+
labTestId,
|
|
2843
|
+
reviewType,
|
|
2844
|
+
status,
|
|
2845
|
+
pending: content,
|
|
2846
|
+
scriptContent: status === "complete" ? content : null,
|
|
2847
|
+
errorMessage: failed ? "Review generation failed: upstream model error (mock)" : null,
|
|
2848
|
+
createdAt: this.iso(now),
|
|
2849
|
+
updatedAt: this.iso(now),
|
|
2850
|
+
readyAtMs: now + processingMs
|
|
2851
|
+
};
|
|
2852
|
+
this.state.reviews.insert(String(review.id), review);
|
|
2853
|
+
const ids = { userId, labTestId, reviewId: String(review.id) };
|
|
2854
|
+
if (failed) {
|
|
2855
|
+
return annotateResponse(
|
|
2856
|
+
jsonRes(500, {
|
|
2857
|
+
message: "Failed to generate review script",
|
|
2858
|
+
reviewId: review.id,
|
|
2859
|
+
status: "failed",
|
|
2860
|
+
reviewType,
|
|
2861
|
+
scriptContent: null,
|
|
2862
|
+
errorMessage: review.errorMessage
|
|
2863
|
+
}),
|
|
2864
|
+
{ ids }
|
|
2865
|
+
);
|
|
2866
|
+
}
|
|
2867
|
+
const verb = mode === "generate" ? "generated" : "regenerated";
|
|
2868
|
+
return annotateResponse(
|
|
2869
|
+
jsonRes(200, {
|
|
2870
|
+
message: status === "complete" ? `Review script ${verb} successfully` : `Review script generation started`,
|
|
2871
|
+
reviewId: review.id,
|
|
2872
|
+
status,
|
|
2873
|
+
reviewType,
|
|
2874
|
+
scriptContent: review.scriptContent
|
|
2875
|
+
}),
|
|
2876
|
+
{ ids }
|
|
2877
|
+
);
|
|
2878
|
+
}
|
|
2879
|
+
};
|
|
2880
|
+
|
|
2881
|
+
export {
|
|
2882
|
+
document,
|
|
2883
|
+
operationIds,
|
|
2884
|
+
supportedOperationIds,
|
|
2885
|
+
DEFAULT_SETTINGS,
|
|
2886
|
+
MAKOR_CPG_PRESETS,
|
|
2887
|
+
CORS_HEADERS,
|
|
2888
|
+
withCors,
|
|
2889
|
+
createRuntime2 as createRuntime,
|
|
2890
|
+
MAKOR_CPG_NAMESPACE,
|
|
2891
|
+
NO_CARE_PLAN_MESSAGE,
|
|
2892
|
+
apiKeyCredential,
|
|
2893
|
+
defaultScriptContent,
|
|
2894
|
+
MakorCpgAPI
|
|
2895
|
+
};
|
|
2896
|
+
//# sourceMappingURL=chunk-326MF4C4.js.map
|