@crvouga/mockingbird-service-vpi 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 +164 -0
- package/dist/chunk-32KSYN2C.js +3210 -0
- package/dist/chunk-32KSYN2C.js.map +7 -0
- package/dist/chunk-JYMS3YHP.js +348 -0
- package/dist/chunk-JYMS3YHP.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +1038 -0
- package/dist/index.js +43 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1344 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +89 -0
|
@@ -0,0 +1,3210 @@
|
|
|
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 bearerToken = (request) => {
|
|
393
|
+
const header = request.headers.get("authorization");
|
|
394
|
+
if (!header)
|
|
395
|
+
return void 0;
|
|
396
|
+
const match = /^Bearer\s+(.+)$/i.exec(header.trim());
|
|
397
|
+
return match?.[1]?.trim() || void 0;
|
|
398
|
+
};
|
|
399
|
+
var createCredentialRegistry = () => {
|
|
400
|
+
const map = /* @__PURE__ */ new Map();
|
|
401
|
+
return {
|
|
402
|
+
set: (credential, namespace) => {
|
|
403
|
+
map.set(credential, namespace);
|
|
404
|
+
},
|
|
405
|
+
get: (credential) => map.get(credential),
|
|
406
|
+
remove: (credential) => map.delete(credential),
|
|
407
|
+
clear: () => map.clear(),
|
|
408
|
+
entries: () => [...map].map(([credential, namespace]) => ({ credential, namespace })).sort((a, b) => a.credential.localeCompare(b.credential))
|
|
409
|
+
};
|
|
410
|
+
};
|
|
411
|
+
var maskCredential = (credential) => credential.length <= 8 ? `${credential.slice(0, 2)}\u2026` : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`;
|
|
412
|
+
|
|
413
|
+
// ../core/dist/rng.js
|
|
414
|
+
var seedFrom = (value) => {
|
|
415
|
+
let hash = 2166136261;
|
|
416
|
+
for (let i = 0; i < value.length; i++) {
|
|
417
|
+
hash ^= value.charCodeAt(i);
|
|
418
|
+
hash = Math.imul(hash, 16777619);
|
|
419
|
+
}
|
|
420
|
+
return hash >>> 0;
|
|
421
|
+
};
|
|
422
|
+
var createRng = (seed = 0) => {
|
|
423
|
+
const numeric = typeof seed === "string" ? seedFrom(seed) : seed >>> 0;
|
|
424
|
+
let state = numeric;
|
|
425
|
+
const next = () => {
|
|
426
|
+
state = state + 1831565813 >>> 0;
|
|
427
|
+
let t = state;
|
|
428
|
+
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
429
|
+
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
430
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
431
|
+
};
|
|
432
|
+
return {
|
|
433
|
+
next,
|
|
434
|
+
int: (min, max) => min + Math.floor(next() * (max - min + 1)),
|
|
435
|
+
reset: () => {
|
|
436
|
+
state = numeric;
|
|
437
|
+
},
|
|
438
|
+
state: () => state,
|
|
439
|
+
setState: (next2) => {
|
|
440
|
+
if (!Number.isSafeInteger(next2) || next2 < 0 || next2 > 4294967295) {
|
|
441
|
+
throw new RangeError("rng state must be an unsigned 32-bit integer");
|
|
442
|
+
}
|
|
443
|
+
state = next2 >>> 0;
|
|
444
|
+
},
|
|
445
|
+
seed: numeric
|
|
446
|
+
};
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
// ../core/dist/faults.js
|
|
450
|
+
var matches = (rule, candidate) => {
|
|
451
|
+
if (rule.namespace !== void 0 && rule.namespace !== "*" && rule.namespace !== candidate.namespace) {
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
if (rule.operationId !== void 0 && rule.operationId !== candidate.operationId)
|
|
455
|
+
return false;
|
|
456
|
+
if (rule.method !== void 0 && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {
|
|
457
|
+
return false;
|
|
458
|
+
}
|
|
459
|
+
if (rule.pathPrefix !== void 0 && !candidate.path.startsWith(rule.pathPrefix))
|
|
460
|
+
return false;
|
|
461
|
+
return true;
|
|
462
|
+
};
|
|
463
|
+
var faultResponse = (rule) => {
|
|
464
|
+
const status = rule.status ?? 500;
|
|
465
|
+
const headers = { "content-type": "application/json", ...rule.headers };
|
|
466
|
+
if (typeof rule.body === "string")
|
|
467
|
+
return new Response(rule.body, { status, headers });
|
|
468
|
+
if (rule.body === null)
|
|
469
|
+
return new Response(null, { status, headers: rule.headers ?? {} });
|
|
470
|
+
const body = rule.body === void 0 ? { detail: "Injected by Mockingbird" } : rule.body;
|
|
471
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
472
|
+
};
|
|
473
|
+
var createFaultRegistry = (rng = createRng(0), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) => {
|
|
474
|
+
const entries = [];
|
|
475
|
+
return {
|
|
476
|
+
add(rule) {
|
|
477
|
+
const existing = entries.findIndex((e) => e.rule.id === rule.id);
|
|
478
|
+
const entry = { rule, remaining: rule.count ?? null, hits: 0 };
|
|
479
|
+
if (existing >= 0)
|
|
480
|
+
entries[existing] = entry;
|
|
481
|
+
else
|
|
482
|
+
entries.push(entry);
|
|
483
|
+
return rule;
|
|
484
|
+
},
|
|
485
|
+
list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),
|
|
486
|
+
remove(id) {
|
|
487
|
+
const index = entries.findIndex((e) => e.rule.id === id);
|
|
488
|
+
if (index < 0)
|
|
489
|
+
return false;
|
|
490
|
+
entries.splice(index, 1);
|
|
491
|
+
return true;
|
|
492
|
+
},
|
|
493
|
+
clear() {
|
|
494
|
+
entries.length = 0;
|
|
495
|
+
},
|
|
496
|
+
async take(candidate) {
|
|
497
|
+
const hits = [];
|
|
498
|
+
for (const entry of entries) {
|
|
499
|
+
if (entry.remaining === 0)
|
|
500
|
+
continue;
|
|
501
|
+
if (!matches(entry.rule, candidate))
|
|
502
|
+
continue;
|
|
503
|
+
const rate = entry.rule.rate ?? 1;
|
|
504
|
+
if (rng.next() >= rate)
|
|
505
|
+
continue;
|
|
506
|
+
entry.hits++;
|
|
507
|
+
if (entry.remaining !== null)
|
|
508
|
+
entry.remaining--;
|
|
509
|
+
const delay = entry.rule.delayMs ?? entry.rule.latencyMs;
|
|
510
|
+
if (delay !== void 0 && delay > 0) {
|
|
511
|
+
await sleep(delay);
|
|
512
|
+
}
|
|
513
|
+
const hit = { id: entry.rule.id };
|
|
514
|
+
if (entry.rule.effect !== void 0) {
|
|
515
|
+
hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} };
|
|
516
|
+
}
|
|
517
|
+
if (entry.rule.drop === true)
|
|
518
|
+
hit.drop = true;
|
|
519
|
+
else if (entry.rule.status !== void 0)
|
|
520
|
+
hit.response = faultResponse(entry.rule);
|
|
521
|
+
hits.push(hit);
|
|
522
|
+
if (hit.drop || hit.response)
|
|
523
|
+
break;
|
|
524
|
+
}
|
|
525
|
+
return hits;
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
};
|
|
529
|
+
|
|
530
|
+
// ../../openapi/core/dist/refs.js
|
|
531
|
+
var OpenAPIReferenceError = class extends Error {
|
|
532
|
+
ref;
|
|
533
|
+
constructor(ref) {
|
|
534
|
+
super(`unresolvable $ref: ${ref}`);
|
|
535
|
+
this.ref = ref;
|
|
536
|
+
this.name = "OpenAPIReferenceError";
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
540
|
+
var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
|
|
541
|
+
var resolveRef = (document2, ref) => {
|
|
542
|
+
if (!ref.startsWith("#/"))
|
|
543
|
+
throw new OpenAPIReferenceError(ref);
|
|
544
|
+
let cursor = document2;
|
|
545
|
+
for (const raw of ref.slice(2).split("/")) {
|
|
546
|
+
const segment = unescapePointer(raw);
|
|
547
|
+
if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
|
|
548
|
+
throw new OpenAPIReferenceError(ref);
|
|
549
|
+
}
|
|
550
|
+
cursor = cursor[segment];
|
|
551
|
+
}
|
|
552
|
+
if (cursor === void 0)
|
|
553
|
+
throw new OpenAPIReferenceError(ref);
|
|
554
|
+
return cursor;
|
|
555
|
+
};
|
|
556
|
+
var deref = (document2, value) => {
|
|
557
|
+
let current = value;
|
|
558
|
+
const seen = /* @__PURE__ */ new Set();
|
|
559
|
+
while (isReference(current)) {
|
|
560
|
+
if (seen.has(current.$ref))
|
|
561
|
+
throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
|
|
562
|
+
seen.add(current.$ref);
|
|
563
|
+
current = resolveRef(document2, current.$ref);
|
|
564
|
+
}
|
|
565
|
+
return current;
|
|
566
|
+
};
|
|
567
|
+
|
|
568
|
+
// ../../openapi/core/dist/types.js
|
|
569
|
+
var HTTP_METHODS = [
|
|
570
|
+
"get",
|
|
571
|
+
"put",
|
|
572
|
+
"post",
|
|
573
|
+
"delete",
|
|
574
|
+
"options",
|
|
575
|
+
"head",
|
|
576
|
+
"patch",
|
|
577
|
+
"trace"
|
|
578
|
+
];
|
|
579
|
+
|
|
580
|
+
// ../../openapi/core/dist/document.js
|
|
581
|
+
var mergeParameters = (document2, item, own) => {
|
|
582
|
+
const merged = /* @__PURE__ */ new Map();
|
|
583
|
+
for (const raw of item.parameters ?? []) {
|
|
584
|
+
const parameter = deref(document2, raw);
|
|
585
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
586
|
+
}
|
|
587
|
+
for (const raw of own ?? []) {
|
|
588
|
+
const parameter = deref(document2, raw);
|
|
589
|
+
merged.set(`${parameter.in}:${parameter.name}`, parameter);
|
|
590
|
+
}
|
|
591
|
+
return [...merged.values()];
|
|
592
|
+
};
|
|
593
|
+
var listOperations = (document2) => {
|
|
594
|
+
const operations = [];
|
|
595
|
+
for (const [path, item] of Object.entries(document2.paths)) {
|
|
596
|
+
for (const method of HTTP_METHODS) {
|
|
597
|
+
const operation = item[method];
|
|
598
|
+
if (operation?.operationId === void 0)
|
|
599
|
+
continue;
|
|
600
|
+
const responses = {};
|
|
601
|
+
for (const [status, response] of Object.entries(operation.responses)) {
|
|
602
|
+
responses[status] = deref(document2, response);
|
|
603
|
+
}
|
|
604
|
+
operations.push({
|
|
605
|
+
operationId: operation.operationId,
|
|
606
|
+
method,
|
|
607
|
+
path,
|
|
608
|
+
operation,
|
|
609
|
+
parameters: mergeParameters(document2, item, operation.parameters),
|
|
610
|
+
requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
|
|
611
|
+
responses
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
return operations;
|
|
616
|
+
};
|
|
617
|
+
|
|
618
|
+
// ../../openapi/core/dist/schema.js
|
|
619
|
+
var resolveSchema = (document2, schema) => {
|
|
620
|
+
let current = schema;
|
|
621
|
+
const seen = /* @__PURE__ */ new Set();
|
|
622
|
+
while (typeof current.$ref === "string") {
|
|
623
|
+
const ref = current.$ref;
|
|
624
|
+
if (seen.has(ref))
|
|
625
|
+
break;
|
|
626
|
+
seen.add(ref);
|
|
627
|
+
const { $ref: _ignored, ...siblings } = current;
|
|
628
|
+
const target = resolveRef(document2, ref);
|
|
629
|
+
current = { ...target, ...siblings };
|
|
630
|
+
}
|
|
631
|
+
if (current.nullable === true) {
|
|
632
|
+
const { nullable: _nullable, ...rest } = current;
|
|
633
|
+
const types = schemaTypes(rest);
|
|
634
|
+
if (types.length > 0 && !types.includes("null"))
|
|
635
|
+
current = { ...rest, type: [...types, "null"] };
|
|
636
|
+
else
|
|
637
|
+
current = rest;
|
|
638
|
+
}
|
|
639
|
+
return current;
|
|
640
|
+
};
|
|
641
|
+
var schemaTypes = (schema) => {
|
|
642
|
+
if (Array.isArray(schema.type))
|
|
643
|
+
return schema.type;
|
|
644
|
+
if (schema.type !== void 0)
|
|
645
|
+
return [schema.type];
|
|
646
|
+
const inferred = [];
|
|
647
|
+
if (schema.properties || schema.required || schema.additionalProperties !== void 0)
|
|
648
|
+
inferred.push("object");
|
|
649
|
+
if (schema.items || schema.prefixItems || schema.minItems !== void 0 || schema.maxItems !== void 0)
|
|
650
|
+
inferred.push("array");
|
|
651
|
+
if (schema.minLength !== void 0 || schema.maxLength !== void 0 || schema.pattern !== void 0)
|
|
652
|
+
inferred.push("string");
|
|
653
|
+
if (schema.minimum !== void 0 || schema.maximum !== void 0 || schema.multipleOf !== void 0)
|
|
654
|
+
inferred.push("number");
|
|
655
|
+
return inferred;
|
|
656
|
+
};
|
|
657
|
+
var jsonTypeOf = (value) => {
|
|
658
|
+
if (value === null)
|
|
659
|
+
return "null";
|
|
660
|
+
if (Array.isArray(value))
|
|
661
|
+
return "array";
|
|
662
|
+
switch (typeof value) {
|
|
663
|
+
case "string":
|
|
664
|
+
return "string";
|
|
665
|
+
case "boolean":
|
|
666
|
+
return "boolean";
|
|
667
|
+
case "number":
|
|
668
|
+
return Number.isInteger(value) ? "integer" : "number";
|
|
669
|
+
case "object":
|
|
670
|
+
return "object";
|
|
671
|
+
default:
|
|
672
|
+
return "undefined";
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
var deepEqual = (a, b) => {
|
|
676
|
+
if (a === b)
|
|
677
|
+
return true;
|
|
678
|
+
if (typeof a !== typeof b || a === null || b === null)
|
|
679
|
+
return false;
|
|
680
|
+
if (Array.isArray(a)) {
|
|
681
|
+
return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
|
|
682
|
+
}
|
|
683
|
+
if (typeof a === "object" && typeof b === "object" && !Array.isArray(b)) {
|
|
684
|
+
const ka = Object.keys(a);
|
|
685
|
+
const kb = Object.keys(b);
|
|
686
|
+
return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
|
|
687
|
+
}
|
|
688
|
+
return false;
|
|
689
|
+
};
|
|
690
|
+
var FORMAT_PATTERNS = {
|
|
691
|
+
uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
|
|
692
|
+
date: /^\d{4}-\d{2}-\d{2}$/,
|
|
693
|
+
"date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,
|
|
694
|
+
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
|
|
695
|
+
uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
|
|
696
|
+
ipv4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
|
|
697
|
+
};
|
|
698
|
+
var graphemeLength = (value) => [...value].length;
|
|
699
|
+
var validateValue = (document2, schema, value, path = []) => {
|
|
700
|
+
const errors = [];
|
|
701
|
+
const s = resolveSchema(document2, schema);
|
|
702
|
+
const fail = (message) => errors.push({ path, message });
|
|
703
|
+
const actual = jsonTypeOf(value);
|
|
704
|
+
if (actual === "undefined") {
|
|
705
|
+
fail("value is undefined");
|
|
706
|
+
return errors;
|
|
707
|
+
}
|
|
708
|
+
const types = schemaTypes(s);
|
|
709
|
+
if (types.length > 0) {
|
|
710
|
+
const ok = types.some((t) => t === actual || t === "number" && actual === "integer");
|
|
711
|
+
if (!ok) {
|
|
712
|
+
fail(`expected type ${types.join("|")}, got ${actual}`);
|
|
713
|
+
return errors;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (s.enum && !(value === null && types.includes("null")) && !s.enum.some((candidate) => deepEqual(candidate, value))) {
|
|
717
|
+
fail("value not in enum");
|
|
718
|
+
}
|
|
719
|
+
if (s.const !== void 0 && !deepEqual(s.const, value))
|
|
720
|
+
fail("value does not equal const");
|
|
721
|
+
if (typeof value === "string") {
|
|
722
|
+
const length = graphemeLength(value);
|
|
723
|
+
if (s.minLength !== void 0 && length < s.minLength)
|
|
724
|
+
fail(`length ${length} < minLength ${s.minLength}`);
|
|
725
|
+
if (s.maxLength !== void 0 && length > s.maxLength)
|
|
726
|
+
fail(`length ${length} > maxLength ${s.maxLength}`);
|
|
727
|
+
if (s.pattern !== void 0) {
|
|
728
|
+
try {
|
|
729
|
+
if (!new RegExp(s.pattern, "u").test(value))
|
|
730
|
+
fail(`does not match pattern ${s.pattern}`);
|
|
731
|
+
} catch {
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
if (s.format !== void 0) {
|
|
735
|
+
const pattern = FORMAT_PATTERNS[s.format];
|
|
736
|
+
if (pattern && !pattern.test(value))
|
|
737
|
+
fail(`does not match format ${s.format}`);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
if (typeof value === "number") {
|
|
741
|
+
if (s.minimum !== void 0 && value < s.minimum)
|
|
742
|
+
fail(`${value} < minimum ${s.minimum}`);
|
|
743
|
+
if (s.maximum !== void 0 && value > s.maximum)
|
|
744
|
+
fail(`${value} > maximum ${s.maximum}`);
|
|
745
|
+
if (s.exclusiveMinimum !== void 0 && value <= s.exclusiveMinimum)
|
|
746
|
+
fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`);
|
|
747
|
+
if (s.exclusiveMaximum !== void 0 && value >= s.exclusiveMaximum)
|
|
748
|
+
fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`);
|
|
749
|
+
if (s.multipleOf !== void 0 && Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9) {
|
|
750
|
+
fail(`${value} is not a multiple of ${s.multipleOf}`);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
if (Array.isArray(value)) {
|
|
754
|
+
if (s.minItems !== void 0 && value.length < s.minItems)
|
|
755
|
+
fail(`${value.length} items < minItems ${s.minItems}`);
|
|
756
|
+
if (s.maxItems !== void 0 && value.length > s.maxItems)
|
|
757
|
+
fail(`${value.length} items > maxItems ${s.maxItems}`);
|
|
758
|
+
if (s.uniqueItems && value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item))))
|
|
759
|
+
fail("items are not unique");
|
|
760
|
+
value.forEach((item, i) => {
|
|
761
|
+
const itemSchema = s.prefixItems?.[i] ?? s.items;
|
|
762
|
+
if (itemSchema)
|
|
763
|
+
errors.push(...validateValue(document2, itemSchema, item, [...path, i]));
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
if (actual === "object") {
|
|
767
|
+
const record2 = value;
|
|
768
|
+
const keys = Object.keys(record2);
|
|
769
|
+
for (const name of s.required ?? [])
|
|
770
|
+
if (!(name in record2))
|
|
771
|
+
fail(`missing required property ${name}`);
|
|
772
|
+
if (s.minProperties !== void 0 && keys.length < s.minProperties)
|
|
773
|
+
fail(`${keys.length} properties < minProperties ${s.minProperties}`);
|
|
774
|
+
if (s.maxProperties !== void 0 && keys.length > s.maxProperties)
|
|
775
|
+
fail(`${keys.length} properties > maxProperties ${s.maxProperties}`);
|
|
776
|
+
for (const key of keys) {
|
|
777
|
+
const property = s.properties?.[key];
|
|
778
|
+
if (property) {
|
|
779
|
+
errors.push(...validateValue(document2, property, record2[key], [...path, key]));
|
|
780
|
+
continue;
|
|
781
|
+
}
|
|
782
|
+
if (s.additionalProperties === false)
|
|
783
|
+
fail(`unexpected property ${key}`);
|
|
784
|
+
else if (typeof s.additionalProperties === "object") {
|
|
785
|
+
errors.push(...validateValue(document2, s.additionalProperties, record2[key], [...path, key]));
|
|
786
|
+
}
|
|
787
|
+
if (s.propertyNames) {
|
|
788
|
+
const nameErrors = validateValue(document2, s.propertyNames, key, [...path, key]);
|
|
789
|
+
if (nameErrors.length > 0)
|
|
790
|
+
fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
if (s.allOf)
|
|
795
|
+
for (const branch of s.allOf)
|
|
796
|
+
errors.push(...validateValue(document2, branch, value, path));
|
|
797
|
+
if (s.anyOf && !s.anyOf.some((branch) => validateValue(document2, branch, value).length === 0))
|
|
798
|
+
fail("matches no anyOf branch");
|
|
799
|
+
if (s.oneOf) {
|
|
800
|
+
const matches2 = s.oneOf.filter((branch) => validateValue(document2, branch, value).length === 0).length;
|
|
801
|
+
if (matches2 !== 1)
|
|
802
|
+
fail(`matches ${matches2} oneOf branches, expected exactly 1`);
|
|
803
|
+
}
|
|
804
|
+
if (s.not && validateValue(document2, s.not, value).length === 0)
|
|
805
|
+
fail("matches forbidden `not` schema");
|
|
806
|
+
return errors;
|
|
807
|
+
};
|
|
808
|
+
|
|
809
|
+
// ../../http/codec/dist/form.js
|
|
810
|
+
var parsePath = (rawKey) => {
|
|
811
|
+
const open = rawKey.indexOf("[");
|
|
812
|
+
if (open === -1)
|
|
813
|
+
return [rawKey];
|
|
814
|
+
const path = [rawKey.slice(0, open)];
|
|
815
|
+
const rest = rawKey.slice(open);
|
|
816
|
+
const pattern = /\[([^\]]*)\]/g;
|
|
817
|
+
let match = pattern.exec(rest);
|
|
818
|
+
let consumed = 0;
|
|
819
|
+
while (match !== null) {
|
|
820
|
+
if (match.index !== consumed)
|
|
821
|
+
return [rawKey];
|
|
822
|
+
path.push(match[1] ?? "");
|
|
823
|
+
consumed = match.index + match[0].length;
|
|
824
|
+
match = pattern.exec(rest);
|
|
825
|
+
}
|
|
826
|
+
if (consumed !== rest.length)
|
|
827
|
+
return [rawKey];
|
|
828
|
+
return path;
|
|
829
|
+
};
|
|
830
|
+
var isIndex = (segment) => /^(0|[1-9][0-9]*)$/.test(segment);
|
|
831
|
+
var put = (target, key, value) => {
|
|
832
|
+
if (key === "__proto__") {
|
|
833
|
+
Object.defineProperty(target, key, {
|
|
834
|
+
value,
|
|
835
|
+
enumerable: true,
|
|
836
|
+
writable: true,
|
|
837
|
+
configurable: true
|
|
838
|
+
});
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
;
|
|
842
|
+
target[key] = value;
|
|
843
|
+
};
|
|
844
|
+
var assign = (target, path, value) => {
|
|
845
|
+
let cursor = target;
|
|
846
|
+
for (let i = 0; i < path.length; i++) {
|
|
847
|
+
const segment = path[i];
|
|
848
|
+
const last = i === path.length - 1;
|
|
849
|
+
if (Array.isArray(cursor)) {
|
|
850
|
+
const index = segment === "" ? cursor.length : isIndex(segment) ? Number(segment) : void 0;
|
|
851
|
+
if (index === void 0)
|
|
852
|
+
return;
|
|
853
|
+
if (last) {
|
|
854
|
+
put(cursor, index, value);
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
const next = Object.hasOwn(cursor, index) ? cursor[index] : void 0;
|
|
858
|
+
if (next === void 0 || typeof next === "string") {
|
|
859
|
+
const created = path[i + 1] === "" || isIndex(path[i + 1]) ? [] : {};
|
|
860
|
+
put(cursor, index, created);
|
|
861
|
+
cursor = created;
|
|
862
|
+
} else {
|
|
863
|
+
cursor = next;
|
|
864
|
+
}
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
if (typeof cursor === "string")
|
|
868
|
+
return;
|
|
869
|
+
if (last) {
|
|
870
|
+
put(cursor, segment, value);
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
const nextSegment = path[i + 1];
|
|
874
|
+
const existing = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
|
|
875
|
+
if (existing === void 0 || typeof existing === "string") {
|
|
876
|
+
const created = nextSegment === "" || isIndex(nextSegment) ? [] : {};
|
|
877
|
+
put(cursor, segment, created);
|
|
878
|
+
cursor = created;
|
|
879
|
+
} else {
|
|
880
|
+
cursor = existing;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
};
|
|
884
|
+
var decodeFormPairs = (pairs) => {
|
|
885
|
+
const out = {};
|
|
886
|
+
for (const [rawKey, value] of pairs)
|
|
887
|
+
assign(out, parsePath(rawKey), value);
|
|
888
|
+
return densify(out);
|
|
889
|
+
};
|
|
890
|
+
var densify = (value) => {
|
|
891
|
+
if (typeof value === "string")
|
|
892
|
+
return value;
|
|
893
|
+
if (Array.isArray(value))
|
|
894
|
+
return value.filter((item) => item !== void 0).map(densify);
|
|
895
|
+
const out = {};
|
|
896
|
+
for (const [key, item] of Object.entries(value))
|
|
897
|
+
put(out, key, densify(item));
|
|
898
|
+
return out;
|
|
899
|
+
};
|
|
900
|
+
var decodeForm = (text) => {
|
|
901
|
+
const source = text.startsWith("?") ? text.slice(1) : text;
|
|
902
|
+
return decodeFormPairs(new URLSearchParams(source).entries());
|
|
903
|
+
};
|
|
904
|
+
|
|
905
|
+
// ../../http/codec/dist/content.js
|
|
906
|
+
var JSON_MEDIA_TYPE = "application/json";
|
|
907
|
+
var FORM_MEDIA_TYPE = "application/x-www-form-urlencoded";
|
|
908
|
+
var mediaTypeOf = (contentType) => {
|
|
909
|
+
if (!contentType)
|
|
910
|
+
return void 0;
|
|
911
|
+
const essence = contentType.split(";")[0]?.trim().toLowerCase();
|
|
912
|
+
return essence ? essence : void 0;
|
|
913
|
+
};
|
|
914
|
+
var isJsonMediaType = (mediaType) => mediaType === JSON_MEDIA_TYPE || mediaType.endsWith("+json") || mediaType === "text/json";
|
|
915
|
+
var utf8 = new TextDecoder("utf-8", { fatal: false });
|
|
916
|
+
var decodeBody = (contentType, bytes) => {
|
|
917
|
+
if (bytes.byteLength === 0)
|
|
918
|
+
return { kind: "empty" };
|
|
919
|
+
const mediaType = mediaTypeOf(contentType);
|
|
920
|
+
if (mediaType === void 0)
|
|
921
|
+
return { kind: "bytes", value: bytes };
|
|
922
|
+
if (isJsonMediaType(mediaType)) {
|
|
923
|
+
const text = utf8.decode(bytes);
|
|
924
|
+
try {
|
|
925
|
+
return { kind: "json", value: JSON.parse(text) };
|
|
926
|
+
} catch (error2) {
|
|
927
|
+
return {
|
|
928
|
+
kind: "invalid",
|
|
929
|
+
mediaType,
|
|
930
|
+
text,
|
|
931
|
+
error: error2 instanceof Error ? error2.message : String(error2)
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
if (mediaType === FORM_MEDIA_TYPE) {
|
|
936
|
+
return { kind: "form", value: decodeForm(utf8.decode(bytes)) };
|
|
937
|
+
}
|
|
938
|
+
if (mediaType.startsWith("text/"))
|
|
939
|
+
return { kind: "text", value: utf8.decode(bytes) };
|
|
940
|
+
return { kind: "bytes", value: bytes };
|
|
941
|
+
};
|
|
942
|
+
var readBody = async (message) => {
|
|
943
|
+
const bytes = new Uint8Array(await message.arrayBuffer());
|
|
944
|
+
return decodeBody(message.headers.get("content-type"), bytes);
|
|
945
|
+
};
|
|
946
|
+
|
|
947
|
+
// ../core/dist/http.js
|
|
948
|
+
var jsonRes = (status, body, headers = {}) => new Response(JSON.stringify(body), {
|
|
949
|
+
status,
|
|
950
|
+
headers: { "content-type": JSON_MEDIA_TYPE, ...headers }
|
|
951
|
+
});
|
|
952
|
+
var HttpError = class extends Error {
|
|
953
|
+
status;
|
|
954
|
+
body;
|
|
955
|
+
headers;
|
|
956
|
+
constructor(status, body, headers = {}) {
|
|
957
|
+
super(`HTTP ${status}`);
|
|
958
|
+
this.status = status;
|
|
959
|
+
this.body = body;
|
|
960
|
+
this.headers = headers;
|
|
961
|
+
this.name = "HttpError";
|
|
962
|
+
}
|
|
963
|
+
toResponse() {
|
|
964
|
+
const contentType = this.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
|
|
965
|
+
if (contentType === "text/plain") {
|
|
966
|
+
return new Response(String(this.body), {
|
|
967
|
+
status: this.status,
|
|
968
|
+
headers: this.headers
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
return jsonRes(this.status, this.body, this.headers);
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
|
|
975
|
+
// ../core/dist/ids.js
|
|
976
|
+
var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
977
|
+
var mix = (input) => {
|
|
978
|
+
let hash = 2166136261;
|
|
979
|
+
for (let i = 0; i < input.length; i++) {
|
|
980
|
+
hash ^= input.charCodeAt(i);
|
|
981
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
982
|
+
}
|
|
983
|
+
hash ^= hash >>> 16;
|
|
984
|
+
hash = Math.imul(hash, 2246822507) >>> 0;
|
|
985
|
+
hash ^= hash >>> 13;
|
|
986
|
+
return hash >>> 0;
|
|
987
|
+
};
|
|
988
|
+
var opaqueToken = (input, length) => {
|
|
989
|
+
let out = "";
|
|
990
|
+
let round = 0;
|
|
991
|
+
while (out.length < length) {
|
|
992
|
+
let hash = mix(`${input}:${round++}`);
|
|
993
|
+
for (let i = 0; i < 5 && out.length < length; i++) {
|
|
994
|
+
out += ALPHABET.charAt(hash % ALPHABET.length);
|
|
995
|
+
hash = Math.floor(hash / ALPHABET.length);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
return out;
|
|
999
|
+
};
|
|
1000
|
+
|
|
1001
|
+
// ../core/dist/journal.js
|
|
1002
|
+
var DEFAULT_JOURNAL_SIZE = 1e3;
|
|
1003
|
+
var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
|
|
1004
|
+
const capacity = Math.max(0, Math.floor(size));
|
|
1005
|
+
const rings = /* @__PURE__ */ new Map();
|
|
1006
|
+
let sequence = 0;
|
|
1007
|
+
const order = /* @__PURE__ */ new WeakMap();
|
|
1008
|
+
const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
|
|
1009
|
+
return {
|
|
1010
|
+
size: capacity,
|
|
1011
|
+
record(entry) {
|
|
1012
|
+
if (capacity === 0)
|
|
1013
|
+
return;
|
|
1014
|
+
order.set(entry, sequence++);
|
|
1015
|
+
let ring = rings.get(entry.namespace);
|
|
1016
|
+
if (!ring) {
|
|
1017
|
+
ring = { entries: [], next: 0 };
|
|
1018
|
+
rings.set(entry.namespace, ring);
|
|
1019
|
+
}
|
|
1020
|
+
if (ring.entries.length < capacity)
|
|
1021
|
+
ring.entries.push(entry);
|
|
1022
|
+
else {
|
|
1023
|
+
ring.entries[ring.next] = entry;
|
|
1024
|
+
ring.next = (ring.next + 1) % capacity;
|
|
1025
|
+
}
|
|
1026
|
+
},
|
|
1027
|
+
list(query = {}) {
|
|
1028
|
+
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));
|
|
1029
|
+
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));
|
|
1030
|
+
return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
|
|
1031
|
+
},
|
|
1032
|
+
clear(namespace) {
|
|
1033
|
+
if (namespace === void 0)
|
|
1034
|
+
rings.clear();
|
|
1035
|
+
else
|
|
1036
|
+
rings.delete(namespace);
|
|
1037
|
+
}
|
|
1038
|
+
};
|
|
1039
|
+
};
|
|
1040
|
+
var notes = /* @__PURE__ */ new WeakMap();
|
|
1041
|
+
var annotateResponse = (response, extra) => {
|
|
1042
|
+
const existing = notes.get(response);
|
|
1043
|
+
notes.set(response, {
|
|
1044
|
+
...existing,
|
|
1045
|
+
...extra,
|
|
1046
|
+
...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
|
|
1047
|
+
});
|
|
1048
|
+
return response;
|
|
1049
|
+
};
|
|
1050
|
+
var responseNotes = (response) => notes.get(response);
|
|
1051
|
+
|
|
1052
|
+
// ../core/dist/metrics.js
|
|
1053
|
+
var createMetrics = () => {
|
|
1054
|
+
let requests = 0;
|
|
1055
|
+
let faults = 0;
|
|
1056
|
+
let totalDurationMs = 0;
|
|
1057
|
+
const byOperation = /* @__PURE__ */ new Map();
|
|
1058
|
+
const unmatched = /* @__PURE__ */ new Map();
|
|
1059
|
+
return {
|
|
1060
|
+
record(entry) {
|
|
1061
|
+
requests++;
|
|
1062
|
+
totalDurationMs += entry.durationMs;
|
|
1063
|
+
if (entry.faultId !== void 0)
|
|
1064
|
+
faults++;
|
|
1065
|
+
const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
|
|
1066
|
+
byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
|
|
1067
|
+
if (entry.unmatched) {
|
|
1068
|
+
const route = `${entry.method} ${entry.path}`;
|
|
1069
|
+
unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
|
|
1070
|
+
}
|
|
1071
|
+
},
|
|
1072
|
+
report: () => ({
|
|
1073
|
+
requests,
|
|
1074
|
+
byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
|
|
1075
|
+
unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
|
|
1076
|
+
const space = route.indexOf(" ");
|
|
1077
|
+
return { method: route.slice(0, space), path: route.slice(space + 1), count };
|
|
1078
|
+
}),
|
|
1079
|
+
faults,
|
|
1080
|
+
totalDurationMs
|
|
1081
|
+
}),
|
|
1082
|
+
reset() {
|
|
1083
|
+
requests = 0;
|
|
1084
|
+
faults = 0;
|
|
1085
|
+
totalDurationMs = 0;
|
|
1086
|
+
byOperation.clear();
|
|
1087
|
+
unmatched.clear();
|
|
1088
|
+
}
|
|
1089
|
+
};
|
|
1090
|
+
};
|
|
1091
|
+
|
|
1092
|
+
// ../../core/dist/timeline.js
|
|
1093
|
+
var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1094
|
+
var Timeline = class {
|
|
1095
|
+
maxCheckpoints;
|
|
1096
|
+
now;
|
|
1097
|
+
makeId;
|
|
1098
|
+
nodes = /* @__PURE__ */ new Map();
|
|
1099
|
+
heads = /* @__PURE__ */ new Map();
|
|
1100
|
+
/** Unreferenced nodes in the exact order they became collectible. */
|
|
1101
|
+
evictable = /* @__PURE__ */ new Set();
|
|
1102
|
+
/** Branch heads plus explicit retainers. Absent means zero. */
|
|
1103
|
+
references = /* @__PURE__ */ new Map();
|
|
1104
|
+
explicitPins = /* @__PURE__ */ new Map();
|
|
1105
|
+
sequence = 0;
|
|
1106
|
+
constructor(options = {}) {
|
|
1107
|
+
const max = options.maxCheckpoints ?? 1e3;
|
|
1108
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1109
|
+
throw new RangeError("maxCheckpoints must be a positive integer");
|
|
1110
|
+
this.maxCheckpoints = max;
|
|
1111
|
+
this.now = options.now ?? (() => this.sequence);
|
|
1112
|
+
this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
|
|
1113
|
+
}
|
|
1114
|
+
/** Capture a new immutable value and move `branch` to it. */
|
|
1115
|
+
commit(value, options = {}) {
|
|
1116
|
+
const branch = options.branch ?? "main";
|
|
1117
|
+
this.assertBranch(branch);
|
|
1118
|
+
const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
|
|
1119
|
+
if (parent !== null && !this.nodes.has(parent))
|
|
1120
|
+
throw new RangeError(`no checkpoint ${parent}`);
|
|
1121
|
+
const id = this.makeId(++this.sequence);
|
|
1122
|
+
if (this.nodes.has(id))
|
|
1123
|
+
throw new RangeError(`duplicate checkpoint id ${id}`);
|
|
1124
|
+
const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
|
|
1125
|
+
this.nodes.set(id, checkpoint);
|
|
1126
|
+
this.moveHead(branch, id);
|
|
1127
|
+
this.collect(this.maxCheckpoints);
|
|
1128
|
+
return checkpoint;
|
|
1129
|
+
}
|
|
1130
|
+
/** Create a branch pointer without copying its checkpoint value. */
|
|
1131
|
+
fork(branch, options = {}) {
|
|
1132
|
+
this.assertBranch(branch);
|
|
1133
|
+
if (this.heads.has(branch))
|
|
1134
|
+
throw new RangeError(`branch already exists: ${branch}`);
|
|
1135
|
+
const from = options.from ?? this.heads.get("main");
|
|
1136
|
+
if (from === void 0)
|
|
1137
|
+
return void 0;
|
|
1138
|
+
const checkpoint = this.get(from);
|
|
1139
|
+
this.moveHead(branch, checkpoint.id);
|
|
1140
|
+
return checkpoint;
|
|
1141
|
+
}
|
|
1142
|
+
/** Move a branch pointer to an existing checkpoint. */
|
|
1143
|
+
checkout(branch, id) {
|
|
1144
|
+
this.assertBranch(branch);
|
|
1145
|
+
const checkpoint = this.get(id);
|
|
1146
|
+
this.moveHead(branch, checkpoint.id);
|
|
1147
|
+
return checkpoint;
|
|
1148
|
+
}
|
|
1149
|
+
get(id) {
|
|
1150
|
+
const checkpoint = this.nodes.get(id);
|
|
1151
|
+
if (!checkpoint)
|
|
1152
|
+
throw new RangeError(`no checkpoint ${id}`);
|
|
1153
|
+
return checkpoint;
|
|
1154
|
+
}
|
|
1155
|
+
head(branch = "main") {
|
|
1156
|
+
const id = this.heads.get(branch);
|
|
1157
|
+
return id === void 0 ? void 0 : this.get(id);
|
|
1158
|
+
}
|
|
1159
|
+
hasBranch(branch) {
|
|
1160
|
+
return this.heads.has(branch);
|
|
1161
|
+
}
|
|
1162
|
+
branches() {
|
|
1163
|
+
return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
|
|
1164
|
+
}
|
|
1165
|
+
checkpoints() {
|
|
1166
|
+
return [...this.nodes.values()];
|
|
1167
|
+
}
|
|
1168
|
+
/** Number of retained checkpoints without allocating an array. */
|
|
1169
|
+
get size() {
|
|
1170
|
+
return this.nodes.size;
|
|
1171
|
+
}
|
|
1172
|
+
/** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
|
|
1173
|
+
retain(id) {
|
|
1174
|
+
const checkpoint = this.get(id);
|
|
1175
|
+
this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
|
|
1176
|
+
this.addReference(id);
|
|
1177
|
+
return checkpoint;
|
|
1178
|
+
}
|
|
1179
|
+
/** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
|
|
1180
|
+
release(id) {
|
|
1181
|
+
if (!this.nodes.has(id))
|
|
1182
|
+
return false;
|
|
1183
|
+
const pins = this.explicitPins.get(id) ?? 0;
|
|
1184
|
+
if (pins === 0)
|
|
1185
|
+
return false;
|
|
1186
|
+
if (pins === 1)
|
|
1187
|
+
this.explicitPins.delete(id);
|
|
1188
|
+
else
|
|
1189
|
+
this.explicitPins.set(id, pins - 1);
|
|
1190
|
+
this.removeReference(id);
|
|
1191
|
+
this.collect(this.maxCheckpoints);
|
|
1192
|
+
return true;
|
|
1193
|
+
}
|
|
1194
|
+
deleteBranch(branch) {
|
|
1195
|
+
if (branch === "main")
|
|
1196
|
+
throw new RangeError("cannot delete main branch");
|
|
1197
|
+
const previous = this.heads.get(branch);
|
|
1198
|
+
const deleted = this.heads.delete(branch);
|
|
1199
|
+
if (previous !== void 0)
|
|
1200
|
+
this.removeReference(previous);
|
|
1201
|
+
this.collect(this.maxCheckpoints);
|
|
1202
|
+
return deleted;
|
|
1203
|
+
}
|
|
1204
|
+
/**
|
|
1205
|
+
* Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
|
|
1206
|
+
* commits never scan pinned nodes or the retained history. Parents are metadata rather than a
|
|
1207
|
+
* storage dependency, so a retained node remains usable after pruning.
|
|
1208
|
+
*/
|
|
1209
|
+
gc(max = this.maxCheckpoints) {
|
|
1210
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1211
|
+
throw new RangeError("max must be a positive integer");
|
|
1212
|
+
const removed = [];
|
|
1213
|
+
this.collect(max, removed);
|
|
1214
|
+
return removed;
|
|
1215
|
+
}
|
|
1216
|
+
collect(max, removed) {
|
|
1217
|
+
while (this.nodes.size > max && this.evictable.size > 0) {
|
|
1218
|
+
const id = this.evictable.values().next().value;
|
|
1219
|
+
this.evictable.delete(id);
|
|
1220
|
+
this.nodes.delete(id);
|
|
1221
|
+
removed?.push(id);
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
moveHead(branch, id) {
|
|
1225
|
+
const previous = this.heads.get(branch);
|
|
1226
|
+
if (previous === id)
|
|
1227
|
+
return;
|
|
1228
|
+
if (previous !== void 0)
|
|
1229
|
+
this.removeReference(previous);
|
|
1230
|
+
this.heads.set(branch, id);
|
|
1231
|
+
this.addReference(id);
|
|
1232
|
+
}
|
|
1233
|
+
addReference(id) {
|
|
1234
|
+
this.references.set(id, (this.references.get(id) ?? 0) + 1);
|
|
1235
|
+
this.evictable.delete(id);
|
|
1236
|
+
}
|
|
1237
|
+
removeReference(id) {
|
|
1238
|
+
const next = (this.references.get(id) ?? 0) - 1;
|
|
1239
|
+
if (next > 0)
|
|
1240
|
+
this.references.set(id, next);
|
|
1241
|
+
else {
|
|
1242
|
+
this.references.delete(id);
|
|
1243
|
+
if (this.nodes.has(id))
|
|
1244
|
+
this.evictable.add(id);
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
assertBranch(branch) {
|
|
1248
|
+
if (!BRANCH_PATTERN.test(branch))
|
|
1249
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
|
|
1250
|
+
}
|
|
1251
|
+
};
|
|
1252
|
+
|
|
1253
|
+
// ../../sqlite/dist/default.js
|
|
1254
|
+
import { Database } from "@crvouga/mockingbird-service-sqlite";
|
|
1255
|
+
var createDefaultSqlite = () => new Database();
|
|
1256
|
+
var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
|
|
1257
|
+
|
|
1258
|
+
// ../../sqlite/dist/migrate.js
|
|
1259
|
+
var ensureMigrationsTable = (sqlite) => {
|
|
1260
|
+
sqlite.exec(`
|
|
1261
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
1262
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
1263
|
+
applied_at INTEGER NOT NULL
|
|
1264
|
+
)
|
|
1265
|
+
`);
|
|
1266
|
+
};
|
|
1267
|
+
var migrate = (sqlite, migrations) => {
|
|
1268
|
+
ensureMigrationsTable(sqlite);
|
|
1269
|
+
const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
|
|
1270
|
+
const pending = migrations.filter((migration) => !applied.has(migration.id));
|
|
1271
|
+
if (pending.length === 0)
|
|
1272
|
+
return;
|
|
1273
|
+
const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
|
|
1274
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1275
|
+
sqlite.transaction(() => {
|
|
1276
|
+
for (const migration of pending) {
|
|
1277
|
+
sqlite.exec(migration.sql);
|
|
1278
|
+
insert.run(migration.id, now);
|
|
1279
|
+
}
|
|
1280
|
+
});
|
|
1281
|
+
};
|
|
1282
|
+
|
|
1283
|
+
// ../../sqlite/dist/schema.js
|
|
1284
|
+
var CORE_MIGRATIONS = [
|
|
1285
|
+
{
|
|
1286
|
+
id: "20260322_core_records_sequences",
|
|
1287
|
+
sql: `
|
|
1288
|
+
CREATE TABLE IF NOT EXISTS mockingbird_records (
|
|
1289
|
+
namespace TEXT NOT NULL,
|
|
1290
|
+
collection TEXT NOT NULL,
|
|
1291
|
+
id TEXT NOT NULL,
|
|
1292
|
+
seq INTEGER NOT NULL,
|
|
1293
|
+
value TEXT NOT NULL,
|
|
1294
|
+
PRIMARY KEY (namespace, collection, id)
|
|
1295
|
+
);
|
|
1296
|
+
CREATE INDEX IF NOT EXISTS mockingbird_records_seq
|
|
1297
|
+
ON mockingbird_records (namespace, collection, seq);
|
|
1298
|
+
CREATE TABLE IF NOT EXISTS mockingbird_sequences (
|
|
1299
|
+
namespace TEXT NOT NULL,
|
|
1300
|
+
name TEXT NOT NULL,
|
|
1301
|
+
kind TEXT NOT NULL,
|
|
1302
|
+
value INTEGER NOT NULL,
|
|
1303
|
+
PRIMARY KEY (namespace, name, kind)
|
|
1304
|
+
);
|
|
1305
|
+
`
|
|
1306
|
+
}
|
|
1307
|
+
];
|
|
1308
|
+
var migrateCore = (sqlite) => {
|
|
1309
|
+
migrate(sqlite, CORE_MIGRATIONS);
|
|
1310
|
+
};
|
|
1311
|
+
var clearNamespace = (sqlite, namespace) => {
|
|
1312
|
+
sqlite.transaction(() => {
|
|
1313
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1314
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1315
|
+
});
|
|
1316
|
+
};
|
|
1317
|
+
|
|
1318
|
+
// ../../openapi/metadata/dist/types.js
|
|
1319
|
+
var EXTENSION_KEYS = {
|
|
1320
|
+
operation: "x-mockingbird",
|
|
1321
|
+
resource: "x-mockingbird-resource",
|
|
1322
|
+
resourceRef: "x-mockingbird-resource-ref",
|
|
1323
|
+
volatile: "x-mockingbird-volatile",
|
|
1324
|
+
scope: "x-mockingbird-scope",
|
|
1325
|
+
unsupported: "x-mockingbird-unsupported",
|
|
1326
|
+
parityHeader: "x-mockingbird-parity-header"
|
|
1327
|
+
};
|
|
1328
|
+
|
|
1329
|
+
// ../../openapi/metadata/dist/read.js
|
|
1330
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1331
|
+
var extensionOf = (holder, key) => holder[key];
|
|
1332
|
+
var operationMetadata = (operation) => {
|
|
1333
|
+
const raw = extensionOf(operation, EXTENSION_KEYS.operation);
|
|
1334
|
+
const ext = isRecord2(raw) ? raw : {};
|
|
1335
|
+
const supported = ext.supported ?? true;
|
|
1336
|
+
const parity = ext.parity ?? {};
|
|
1337
|
+
return {
|
|
1338
|
+
supported,
|
|
1339
|
+
reason: typeof ext.reason === "string" ? ext.reason : void 0,
|
|
1340
|
+
parity: {
|
|
1341
|
+
enabled: supported && (parity.enabled ?? true),
|
|
1342
|
+
safe: parity.safe ?? true,
|
|
1343
|
+
reason: typeof parity.reason === "string" ? parity.reason : void 0
|
|
1344
|
+
}
|
|
1345
|
+
};
|
|
1346
|
+
};
|
|
1347
|
+
|
|
1348
|
+
// ../core/dist/service.js
|
|
1349
|
+
import { Hono } from "hono";
|
|
1350
|
+
var defineOperations = (handlers) => handlers;
|
|
1351
|
+
var OperationRegistryError = class extends Error {
|
|
1352
|
+
problems;
|
|
1353
|
+
constructor(problems) {
|
|
1354
|
+
super(`operation registry is inconsistent:
|
|
1355
|
+
${problems.map((p) => ` - ${p}`).join("\n")}`);
|
|
1356
|
+
this.problems = problems;
|
|
1357
|
+
this.name = "OperationRegistryError";
|
|
1358
|
+
}
|
|
1359
|
+
};
|
|
1360
|
+
var verifyOperations = (document2, handlers) => {
|
|
1361
|
+
const problems = [];
|
|
1362
|
+
const operations = listOperations(document2);
|
|
1363
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1364
|
+
for (const operation of operations) {
|
|
1365
|
+
if (seen.has(operation.operationId))
|
|
1366
|
+
problems.push(`duplicate operationId ${operation.operationId}`);
|
|
1367
|
+
seen.add(operation.operationId);
|
|
1368
|
+
const supported = operationMetadata(operation.operation).supported;
|
|
1369
|
+
const handler = handlers[operation.operationId];
|
|
1370
|
+
if (supported && !handler)
|
|
1371
|
+
problems.push(`supported operation ${operation.operationId} has no handler`);
|
|
1372
|
+
if (!supported && handler)
|
|
1373
|
+
problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
|
|
1374
|
+
}
|
|
1375
|
+
for (const id of Object.keys(handlers)) {
|
|
1376
|
+
if (!seen.has(id))
|
|
1377
|
+
problems.push(`handler ${id} has no OpenAPI operation`);
|
|
1378
|
+
}
|
|
1379
|
+
return problems;
|
|
1380
|
+
};
|
|
1381
|
+
var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
|
|
1382
|
+
var routeOrder = (a, b) => {
|
|
1383
|
+
const sa = a.path.split("/");
|
|
1384
|
+
const sb = b.path.split("/");
|
|
1385
|
+
for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
|
|
1386
|
+
const x = sa[i] ?? "";
|
|
1387
|
+
const y = sb[i] ?? "";
|
|
1388
|
+
const px = x.startsWith("{");
|
|
1389
|
+
const py = y.startsWith("{");
|
|
1390
|
+
if (px !== py)
|
|
1391
|
+
return px ? 1 : -1;
|
|
1392
|
+
if (x !== y)
|
|
1393
|
+
return x < y ? -1 : 1;
|
|
1394
|
+
}
|
|
1395
|
+
return 0;
|
|
1396
|
+
};
|
|
1397
|
+
var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
|
|
1398
|
+
var bootSqlite = (sqlite) => {
|
|
1399
|
+
const client = resolveSqlite(sqlite);
|
|
1400
|
+
migrateCore(client);
|
|
1401
|
+
return client;
|
|
1402
|
+
};
|
|
1403
|
+
var createService = (options) => {
|
|
1404
|
+
const problems = verifyOperations(options.document, options.handlers);
|
|
1405
|
+
if (problems.length > 0)
|
|
1406
|
+
throw new OperationRegistryError(problems);
|
|
1407
|
+
migrateCore(options.sqlite);
|
|
1408
|
+
const now = options.now ?? (() => Date.now());
|
|
1409
|
+
const app = new Hono();
|
|
1410
|
+
app.notFound((c) => options.notFound(c.req.raw));
|
|
1411
|
+
app.onError((error2, c) => options.onError(error2, c.req.raw));
|
|
1412
|
+
const operations = [...listOperations(options.document)].sort(routeOrder);
|
|
1413
|
+
for (const operation of operations) {
|
|
1414
|
+
const metadata = operationMetadata(operation.operation);
|
|
1415
|
+
const handler = options.handlers[operation.operationId];
|
|
1416
|
+
const route = async (c) => {
|
|
1417
|
+
const request = c.req.raw;
|
|
1418
|
+
if (!metadata.supported || !handler) {
|
|
1419
|
+
return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
|
|
1420
|
+
}
|
|
1421
|
+
const url = new URL(request.url);
|
|
1422
|
+
const context = {
|
|
1423
|
+
request,
|
|
1424
|
+
url,
|
|
1425
|
+
params: c.req.param(),
|
|
1426
|
+
query: queryOf(url),
|
|
1427
|
+
body: await readBody(request),
|
|
1428
|
+
sqlite: options.sqlite,
|
|
1429
|
+
namespace: options.namespace,
|
|
1430
|
+
operation,
|
|
1431
|
+
document: options.document,
|
|
1432
|
+
now
|
|
1433
|
+
};
|
|
1434
|
+
const short = await options.before?.(context);
|
|
1435
|
+
if (short)
|
|
1436
|
+
return short;
|
|
1437
|
+
return handler(context);
|
|
1438
|
+
};
|
|
1439
|
+
app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
|
|
1440
|
+
}
|
|
1441
|
+
return {
|
|
1442
|
+
app,
|
|
1443
|
+
sqlite: options.sqlite,
|
|
1444
|
+
namespace: options.namespace,
|
|
1445
|
+
fetch: async (request) => app.fetch(request),
|
|
1446
|
+
reset: async () => {
|
|
1447
|
+
clearNamespace(options.sqlite, options.namespace);
|
|
1448
|
+
}
|
|
1449
|
+
};
|
|
1450
|
+
};
|
|
1451
|
+
|
|
1452
|
+
// ../core/dist/snapshot.js
|
|
1453
|
+
var snapshotNamespace = (sqlite, namespace) => ({
|
|
1454
|
+
namespace,
|
|
1455
|
+
records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
|
|
1456
|
+
sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
|
|
1457
|
+
});
|
|
1458
|
+
var restoreNamespace = (sqlite, namespace, snapshot) => {
|
|
1459
|
+
sqlite.transaction(() => {
|
|
1460
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1461
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1462
|
+
const record2 = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
|
|
1463
|
+
for (const row of snapshot.records) {
|
|
1464
|
+
record2.run(namespace, row.collection, row.id, row.seq, row.value);
|
|
1465
|
+
}
|
|
1466
|
+
const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
|
|
1467
|
+
for (const row of snapshot.sequences) {
|
|
1468
|
+
sequence.run(namespace, row.name, row.kind, row.value);
|
|
1469
|
+
}
|
|
1470
|
+
});
|
|
1471
|
+
};
|
|
1472
|
+
|
|
1473
|
+
// ../core/dist/version.js
|
|
1474
|
+
var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
|
|
1475
|
+
|
|
1476
|
+
// ../core/dist/signing.js
|
|
1477
|
+
var encoder = new TextEncoder();
|
|
1478
|
+
var toBase64 = (bytes) => {
|
|
1479
|
+
let binary = "";
|
|
1480
|
+
for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {
|
|
1481
|
+
binary += String.fromCharCode(byte);
|
|
1482
|
+
}
|
|
1483
|
+
return btoa(binary);
|
|
1484
|
+
};
|
|
1485
|
+
var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
|
|
1486
|
+
|
|
1487
|
+
// ../core/dist/webhooks.js
|
|
1488
|
+
var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1489
|
+
var adminError2 = (status, message) => json2(status, { error: { type: "mockingbird_admin", message } });
|
|
1490
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1491
|
+
var parseEndpoint = (value) => {
|
|
1492
|
+
if (!isRecord3(value) || typeof value.url !== "string")
|
|
1493
|
+
return "each endpoint needs a url";
|
|
1494
|
+
try {
|
|
1495
|
+
new URL(value.url);
|
|
1496
|
+
} catch {
|
|
1497
|
+
return `not a URL: ${value.url}`;
|
|
1498
|
+
}
|
|
1499
|
+
const endpoint = { url: value.url };
|
|
1500
|
+
if (typeof value.id === "string")
|
|
1501
|
+
endpoint.id = value.id;
|
|
1502
|
+
if (typeof value.secret === "string")
|
|
1503
|
+
endpoint.secret = value.secret;
|
|
1504
|
+
if (typeof value.signUrl === "string")
|
|
1505
|
+
endpoint.signUrl = value.signUrl;
|
|
1506
|
+
const events = value.events ?? value.enabledEvents;
|
|
1507
|
+
if (Array.isArray(events))
|
|
1508
|
+
endpoint.events = events.map(String);
|
|
1509
|
+
if (isRecord3(value.tags)) {
|
|
1510
|
+
endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
|
|
1511
|
+
}
|
|
1512
|
+
if (typeof value.account === "string")
|
|
1513
|
+
endpoint.tags = { ...endpoint.tags, account: value.account };
|
|
1514
|
+
if (isRecord3(value.headers)) {
|
|
1515
|
+
endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
|
|
1516
|
+
}
|
|
1517
|
+
return endpoint;
|
|
1518
|
+
};
|
|
1519
|
+
var webhookAdminRoutes = (hub) => ({
|
|
1520
|
+
"GET /webhooks": ({ url, namespace }) => json2(200, {
|
|
1521
|
+
deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
|
|
1522
|
+
const type = url.searchParams.get("type");
|
|
1523
|
+
return type === null || d.type === type;
|
|
1524
|
+
})
|
|
1525
|
+
}),
|
|
1526
|
+
"GET /webhooks/events": ({ url, namespace }) => {
|
|
1527
|
+
const type = url.searchParams.get("type");
|
|
1528
|
+
return json2(200, {
|
|
1529
|
+
events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
|
|
1530
|
+
});
|
|
1531
|
+
},
|
|
1532
|
+
"POST /webhooks/:id/replay": async ({ params }) => {
|
|
1533
|
+
const replayed = await hub.replay(params.id);
|
|
1534
|
+
return replayed ? json2(200, replayed) : adminError2(404, `no delivery ${params.id}`);
|
|
1535
|
+
},
|
|
1536
|
+
"POST /webhooks/flush": async () => {
|
|
1537
|
+
await hub.flush();
|
|
1538
|
+
return json2(200, { status: "ok" });
|
|
1539
|
+
},
|
|
1540
|
+
"POST /webhooks/faults": ({ body, namespace }) => {
|
|
1541
|
+
if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
|
|
1542
|
+
return adminError2(400, "mode must be duplicate, reorder or drop");
|
|
1543
|
+
}
|
|
1544
|
+
const fault = { mode: body.mode };
|
|
1545
|
+
if (typeof body.count === "number")
|
|
1546
|
+
fault.count = body.count;
|
|
1547
|
+
hub.fault(namespace, fault);
|
|
1548
|
+
return json2(201, { namespace, ...fault });
|
|
1549
|
+
},
|
|
1550
|
+
"GET /webhook-endpoints": ({ namespace }) => json2(200, {
|
|
1551
|
+
endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
|
|
1552
|
+
...rest,
|
|
1553
|
+
secret: secret ? "(set)" : null
|
|
1554
|
+
}))
|
|
1555
|
+
}),
|
|
1556
|
+
"PUT /webhook-endpoints": ({ body, namespace }) => {
|
|
1557
|
+
const list = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
|
|
1558
|
+
if (!Array.isArray(list))
|
|
1559
|
+
return adminError2(400, "expected [{url, secret?, events?}]");
|
|
1560
|
+
const parsed = [];
|
|
1561
|
+
for (const each of list) {
|
|
1562
|
+
const endpoint = parseEndpoint(each);
|
|
1563
|
+
if (typeof endpoint === "string")
|
|
1564
|
+
return adminError2(400, endpoint);
|
|
1565
|
+
parsed.push(endpoint);
|
|
1566
|
+
}
|
|
1567
|
+
const set = hub.setEndpoints(namespace, parsed);
|
|
1568
|
+
return json2(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
|
|
1569
|
+
},
|
|
1570
|
+
"DELETE /webhook-endpoints": ({ namespace }) => {
|
|
1571
|
+
hub.setEndpoints(namespace, []);
|
|
1572
|
+
return json2(200, { status: "ok" });
|
|
1573
|
+
}
|
|
1574
|
+
});
|
|
1575
|
+
var parsePayload = (message) => {
|
|
1576
|
+
if (message.contentType.startsWith("application/json")) {
|
|
1577
|
+
try {
|
|
1578
|
+
return JSON.parse(message.body);
|
|
1579
|
+
} catch {
|
|
1580
|
+
return message.body;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
|
|
1584
|
+
return Object.fromEntries(new URLSearchParams(message.body));
|
|
1585
|
+
}
|
|
1586
|
+
return message.body;
|
|
1587
|
+
};
|
|
1588
|
+
|
|
1589
|
+
// ../core/dist/runtime.js
|
|
1590
|
+
var MOCKINGBIRD_HEADER = "x-mockingbird";
|
|
1591
|
+
var BRANCH_HEADER = "x-mockingbird-branch";
|
|
1592
|
+
var AT_HEADER = "x-mockingbird-at";
|
|
1593
|
+
var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
|
|
1594
|
+
var DEFAULT_NAMESPACE = "default";
|
|
1595
|
+
var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1596
|
+
var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
|
|
1597
|
+
var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1598
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
1599
|
+
var effects = /* @__PURE__ */ new WeakMap();
|
|
1600
|
+
var reuseSorted = (fresh, previous, compare, equal) => {
|
|
1601
|
+
if (!previous || previous.length === 0)
|
|
1602
|
+
return fresh.map((row) => Object.freeze(row));
|
|
1603
|
+
const result = new Array(fresh.length);
|
|
1604
|
+
let unchanged = fresh.length === previous.length;
|
|
1605
|
+
let oldIndex = 0;
|
|
1606
|
+
for (let index = 0; index < fresh.length; index++) {
|
|
1607
|
+
const row = fresh[index];
|
|
1608
|
+
while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
|
|
1609
|
+
oldIndex++;
|
|
1610
|
+
}
|
|
1611
|
+
const old = previous[oldIndex];
|
|
1612
|
+
result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
|
|
1613
|
+
if (result[index] !== previous[index])
|
|
1614
|
+
unchanged = false;
|
|
1615
|
+
}
|
|
1616
|
+
return unchanged ? previous : result;
|
|
1617
|
+
};
|
|
1618
|
+
var faultEffects = (request) => (effects.get(request) ?? []).filter((e) => e !== void 0);
|
|
1619
|
+
var faultEffect = (request, name) => faultEffects(request).find((e) => e.name === name)?.params;
|
|
1620
|
+
var DroppedConnectionError = class extends TypeError {
|
|
1621
|
+
code = "MOCKINGBIRD_DROP";
|
|
1622
|
+
constructor() {
|
|
1623
|
+
super("fetch failed: connection dropped by Mockingbird fault");
|
|
1624
|
+
this.name = "TypeError";
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
var operationMatcher = (document2) => {
|
|
1628
|
+
const matchers = listOperations(document2).map((operation) => ({
|
|
1629
|
+
operationId: operation.operationId,
|
|
1630
|
+
method: operation.method.toUpperCase(),
|
|
1631
|
+
pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
|
|
1632
|
+
params: (operation.path.match(/\{/g) ?? []).length
|
|
1633
|
+
})).sort((a, b) => a.params - b.params);
|
|
1634
|
+
return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
|
|
1635
|
+
};
|
|
1636
|
+
var createRuntime = (options) => {
|
|
1637
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
1638
|
+
const clock = options.clock ?? createClock();
|
|
1639
|
+
const rng = createRng(options.seed ?? 0);
|
|
1640
|
+
const wallNow = options.io?.wallNow ?? Date.now;
|
|
1641
|
+
const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
|
|
1642
|
+
const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1643
|
+
const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
|
|
1644
|
+
const metrics = createMetrics();
|
|
1645
|
+
const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
|
|
1646
|
+
const version = options.version ?? PACKAGE_VERSION;
|
|
1647
|
+
const instances = /* @__PURE__ */ new Map();
|
|
1648
|
+
const publicNamespaces = /* @__PURE__ */ new Set();
|
|
1649
|
+
const branchRngs = /* @__PURE__ */ new Map();
|
|
1650
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
1651
|
+
const branchStorage = /* @__PURE__ */ new Map();
|
|
1652
|
+
const captured = /* @__PURE__ */ new Map();
|
|
1653
|
+
const credentials = createCredentialRegistry();
|
|
1654
|
+
const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
|
|
1655
|
+
const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
|
|
1656
|
+
const instanceFor = (key, publicNamespace = key, isolatedRng) => {
|
|
1657
|
+
const existing = instances.get(key);
|
|
1658
|
+
if (existing)
|
|
1659
|
+
return existing;
|
|
1660
|
+
if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
|
|
1661
|
+
throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
|
|
1662
|
+
}
|
|
1663
|
+
const created = options.create({
|
|
1664
|
+
namespace: storageNamespace(key),
|
|
1665
|
+
publicNamespace,
|
|
1666
|
+
sqlite,
|
|
1667
|
+
clock,
|
|
1668
|
+
rng: isolatedRng ?? rng
|
|
1669
|
+
});
|
|
1670
|
+
instances.set(key, created);
|
|
1671
|
+
publicNamespaces.add(publicNamespace);
|
|
1672
|
+
if (isolatedRng)
|
|
1673
|
+
branchRngs.set(key, isolatedRng);
|
|
1674
|
+
return created;
|
|
1675
|
+
};
|
|
1676
|
+
const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
|
|
1677
|
+
const capture = (storage) => {
|
|
1678
|
+
const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
|
|
1679
|
+
const previous = captured.get(storage);
|
|
1680
|
+
const snapshot2 = {
|
|
1681
|
+
namespace: fresh.namespace,
|
|
1682
|
+
records: reuseSorted(fresh.records, previous?.records, (left, right) => left.collection < right.collection ? -1 : left.collection > right.collection ? 1 : left.seq - right.seq, (left, right) => left.id === right.id && left.value === right.value),
|
|
1683
|
+
sequences: reuseSorted(fresh.sequences, previous?.sequences, (left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : left.kind < right.kind ? -1 : left.kind > right.kind ? 1 : 0, (left, right) => left.value === right.value)
|
|
1684
|
+
};
|
|
1685
|
+
Object.freeze(snapshot2.records);
|
|
1686
|
+
Object.freeze(snapshot2.sequences);
|
|
1687
|
+
Object.freeze(snapshot2);
|
|
1688
|
+
captured.set(storage, snapshot2);
|
|
1689
|
+
return Object.freeze({
|
|
1690
|
+
snapshot: snapshot2,
|
|
1691
|
+
clock: Object.freeze(clock.state()),
|
|
1692
|
+
rngState: (branchRngs.get(storage) ?? rng).state()
|
|
1693
|
+
});
|
|
1694
|
+
};
|
|
1695
|
+
const timeline = (name = DEFAULT_NAMESPACE) => {
|
|
1696
|
+
let found = timelines.get(name);
|
|
1697
|
+
if (found)
|
|
1698
|
+
return found;
|
|
1699
|
+
instance(name);
|
|
1700
|
+
found = new Timeline({
|
|
1701
|
+
now: clock.now,
|
|
1702
|
+
...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
|
|
1703
|
+
});
|
|
1704
|
+
found.commit(capture(name));
|
|
1705
|
+
timelines.set(name, found);
|
|
1706
|
+
return found;
|
|
1707
|
+
};
|
|
1708
|
+
const physicalBranch = (namespace, branch2) => {
|
|
1709
|
+
if (branch2 === "main")
|
|
1710
|
+
return namespace;
|
|
1711
|
+
const mapKey = `${namespace}\0${branch2}`;
|
|
1712
|
+
const existing = branchStorage.get(mapKey);
|
|
1713
|
+
if (existing)
|
|
1714
|
+
return existing;
|
|
1715
|
+
const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
|
|
1716
|
+
branchStorage.set(mapKey, key);
|
|
1717
|
+
return key;
|
|
1718
|
+
};
|
|
1719
|
+
const ensureBranch = (namespace, branch2, at) => {
|
|
1720
|
+
if (!BRANCH_PATTERN2.test(branch2))
|
|
1721
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
|
|
1722
|
+
const history = timeline(namespace);
|
|
1723
|
+
if (branch2 === "main") {
|
|
1724
|
+
if (at !== void 0) {
|
|
1725
|
+
const point = history.checkout("main", at);
|
|
1726
|
+
restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
|
|
1727
|
+
captured.set(namespace, point.value.snapshot);
|
|
1728
|
+
rng.setState(point.value.rngState);
|
|
1729
|
+
clock.set(point.value.clock.now);
|
|
1730
|
+
if (point.value.clock.frozen)
|
|
1731
|
+
clock.freeze();
|
|
1732
|
+
else
|
|
1733
|
+
clock.unfreeze();
|
|
1734
|
+
}
|
|
1735
|
+
return namespace;
|
|
1736
|
+
}
|
|
1737
|
+
const storage = physicalBranch(namespace, branch2);
|
|
1738
|
+
if (!history.hasBranch(branch2)) {
|
|
1739
|
+
if (at === void 0)
|
|
1740
|
+
history.commit(capture(namespace));
|
|
1741
|
+
const point = history.fork(branch2, at === void 0 ? {} : { from: at });
|
|
1742
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1743
|
+
if (point)
|
|
1744
|
+
branchRng.setState(point.value.rngState);
|
|
1745
|
+
instanceFor(storage, namespace, branchRng);
|
|
1746
|
+
if (point)
|
|
1747
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1748
|
+
if (point)
|
|
1749
|
+
captured.set(storage, point.value.snapshot);
|
|
1750
|
+
} else if (at !== void 0 && history.head(branch2)?.id !== at) {
|
|
1751
|
+
const point = history.checkout(branch2, at);
|
|
1752
|
+
if (!instances.has(storage)) {
|
|
1753
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1754
|
+
branchRng.setState(point.value.rngState);
|
|
1755
|
+
instanceFor(storage, namespace, branchRng);
|
|
1756
|
+
}
|
|
1757
|
+
branchRngs.get(storage)?.setState(point.value.rngState);
|
|
1758
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1759
|
+
captured.set(storage, point.value.snapshot);
|
|
1760
|
+
} else {
|
|
1761
|
+
if (!instances.has(storage)) {
|
|
1762
|
+
const point = history.head(branch2);
|
|
1763
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
1764
|
+
if (point)
|
|
1765
|
+
branchRng.setState(point.value.rngState);
|
|
1766
|
+
instanceFor(storage, namespace, branchRng);
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
return storage;
|
|
1770
|
+
};
|
|
1771
|
+
const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
|
|
1772
|
+
const storage = ensureBranch(namespace, branch2);
|
|
1773
|
+
return timeline(namespace).commit(capture(storage), { branch: branch2 });
|
|
1774
|
+
};
|
|
1775
|
+
const branch = (name, branchOptions = {}) => {
|
|
1776
|
+
const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1777
|
+
ensureBranch(namespace, name, branchOptions.at);
|
|
1778
|
+
const head = timeline(namespace).head(name);
|
|
1779
|
+
if (!head)
|
|
1780
|
+
throw new RangeError(`branch ${name} has no checkpoint`);
|
|
1781
|
+
return head;
|
|
1782
|
+
};
|
|
1783
|
+
const checkout = (checkpointId, checkoutOptions = {}) => {
|
|
1784
|
+
const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
1785
|
+
const branchName = checkoutOptions.branch ?? "main";
|
|
1786
|
+
const history = timeline(namespace);
|
|
1787
|
+
const point = history.checkout(branchName, checkpointId);
|
|
1788
|
+
const storage = ensureBranch(namespace, branchName);
|
|
1789
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1790
|
+
captured.set(storage, point.value.snapshot);
|
|
1791
|
+
clock.set(point.value.clock.now);
|
|
1792
|
+
if (point.value.clock.frozen)
|
|
1793
|
+
clock.freeze();
|
|
1794
|
+
else
|
|
1795
|
+
clock.unfreeze();
|
|
1796
|
+
(branchRngs.get(storage) ?? rng).setState(point.value.rngState);
|
|
1797
|
+
};
|
|
1798
|
+
const reset = async (name = DEFAULT_NAMESPACE) => {
|
|
1799
|
+
if (name === "*") {
|
|
1800
|
+
options.webhooks?.clear();
|
|
1801
|
+
for (const each of instances.values())
|
|
1802
|
+
await each.reset();
|
|
1803
|
+
timelines.clear();
|
|
1804
|
+
branchStorage.clear();
|
|
1805
|
+
branchRngs.clear();
|
|
1806
|
+
captured.clear();
|
|
1807
|
+
return;
|
|
1808
|
+
}
|
|
1809
|
+
options.webhooks?.clear(name);
|
|
1810
|
+
const target = instances.get(name);
|
|
1811
|
+
if (target)
|
|
1812
|
+
await target.reset();
|
|
1813
|
+
else
|
|
1814
|
+
clearNamespace(sqlite, storageNamespace(name));
|
|
1815
|
+
for (const [mapping, storage] of branchStorage) {
|
|
1816
|
+
if (!mapping.startsWith(`${name}\0`))
|
|
1817
|
+
continue;
|
|
1818
|
+
const branchInstance = instances.get(storage);
|
|
1819
|
+
if (branchInstance)
|
|
1820
|
+
await branchInstance.reset();
|
|
1821
|
+
else
|
|
1822
|
+
clearNamespace(sqlite, storageNamespace(storage));
|
|
1823
|
+
branchStorage.delete(mapping);
|
|
1824
|
+
branchRngs.delete(storage);
|
|
1825
|
+
captured.delete(storage);
|
|
1826
|
+
}
|
|
1827
|
+
timelines.delete(name);
|
|
1828
|
+
captured.delete(name);
|
|
1829
|
+
};
|
|
1830
|
+
const snapshot = (name = DEFAULT_NAMESPACE) => {
|
|
1831
|
+
return checkpoint(name, "main").value.snapshot;
|
|
1832
|
+
};
|
|
1833
|
+
const restore = (from, name = DEFAULT_NAMESPACE) => {
|
|
1834
|
+
instance(name);
|
|
1835
|
+
restoreNamespace(sqlite, storageNamespace(name), from);
|
|
1836
|
+
captured.set(name, from);
|
|
1837
|
+
const history = timelines.get(name);
|
|
1838
|
+
if (history)
|
|
1839
|
+
history.commit(capture(name), { branch: "main" });
|
|
1840
|
+
else
|
|
1841
|
+
timeline(name);
|
|
1842
|
+
};
|
|
1843
|
+
const runtime = {
|
|
1844
|
+
name: options.name,
|
|
1845
|
+
sqlite,
|
|
1846
|
+
clock,
|
|
1847
|
+
faults,
|
|
1848
|
+
metrics,
|
|
1849
|
+
journal,
|
|
1850
|
+
rng,
|
|
1851
|
+
credentials,
|
|
1852
|
+
webhooks: options.webhooks,
|
|
1853
|
+
applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
|
|
1854
|
+
const preset = options.presets?.[name];
|
|
1855
|
+
if (!preset)
|
|
1856
|
+
throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
|
|
1857
|
+
const added = (preset.rules ?? []).map((rule, index) => faults.add({
|
|
1858
|
+
namespace,
|
|
1859
|
+
...rule,
|
|
1860
|
+
...overrides,
|
|
1861
|
+
preset: name,
|
|
1862
|
+
id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
|
|
1863
|
+
}));
|
|
1864
|
+
if (preset.webhook && options.webhooks) {
|
|
1865
|
+
options.webhooks.fault(namespace, {
|
|
1866
|
+
...preset.webhook,
|
|
1867
|
+
...overrides.count !== void 0 ? { count: overrides.count } : {}
|
|
1868
|
+
});
|
|
1869
|
+
}
|
|
1870
|
+
return added;
|
|
1871
|
+
},
|
|
1872
|
+
instance,
|
|
1873
|
+
namespaces: () => [...publicNamespaces].sort(),
|
|
1874
|
+
reset,
|
|
1875
|
+
snapshot,
|
|
1876
|
+
restore,
|
|
1877
|
+
checkpoint,
|
|
1878
|
+
branch,
|
|
1879
|
+
checkout,
|
|
1880
|
+
timeline,
|
|
1881
|
+
fetch: async (incoming) => {
|
|
1882
|
+
let request = incoming;
|
|
1883
|
+
const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
|
|
1884
|
+
if (prefixed) {
|
|
1885
|
+
const url2 = new URL(request.url);
|
|
1886
|
+
url2.pathname = prefixed[2] ?? "/";
|
|
1887
|
+
const headers = new Headers(request.headers);
|
|
1888
|
+
if (!headers.has(NAMESPACE_HEADER)) {
|
|
1889
|
+
headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
|
|
1890
|
+
}
|
|
1891
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
|
1892
|
+
request = new Request(url2, {
|
|
1893
|
+
method: request.method,
|
|
1894
|
+
headers,
|
|
1895
|
+
...hasBody ? { body: await request.arrayBuffer() } : {},
|
|
1896
|
+
signal: request.signal
|
|
1897
|
+
});
|
|
1898
|
+
}
|
|
1899
|
+
let namespace = control.namespaceOf(request);
|
|
1900
|
+
if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
|
|
1901
|
+
const credential = options.credential(request);
|
|
1902
|
+
const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
|
|
1903
|
+
if (mapped !== void 0)
|
|
1904
|
+
namespace = mapped;
|
|
1905
|
+
}
|
|
1906
|
+
const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
|
|
1907
|
+
const at = request.headers.get(AT_HEADER) ?? void 0;
|
|
1908
|
+
const stamp = (response2) => {
|
|
1909
|
+
const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
|
|
1910
|
+
try {
|
|
1911
|
+
response2.headers.set(MOCKINGBIRD_HEADER, value);
|
|
1912
|
+
return response2;
|
|
1913
|
+
} catch {
|
|
1914
|
+
const copy = new Response(response2.body, response2);
|
|
1915
|
+
copy.headers.set(MOCKINGBIRD_HEADER, value);
|
|
1916
|
+
return copy;
|
|
1917
|
+
}
|
|
1918
|
+
};
|
|
1919
|
+
const handled = await control.handle(request);
|
|
1920
|
+
if (handled)
|
|
1921
|
+
return stamp(handled);
|
|
1922
|
+
const started = monotonicNow();
|
|
1923
|
+
const url = new URL(request.url);
|
|
1924
|
+
const operationId = operationIdFor(request, url.pathname);
|
|
1925
|
+
const log = (status, faultId, response2) => {
|
|
1926
|
+
const noted = response2 ? responseNotes(response2) : void 0;
|
|
1927
|
+
const entry = {
|
|
1928
|
+
service: options.name,
|
|
1929
|
+
namespace,
|
|
1930
|
+
operationId,
|
|
1931
|
+
method: request.method,
|
|
1932
|
+
path: url.pathname,
|
|
1933
|
+
status,
|
|
1934
|
+
durationMs: Math.round((monotonicNow() - started) * 100) / 100,
|
|
1935
|
+
unmatched: options.document !== void 0 && operationId === void 0,
|
|
1936
|
+
...faultId !== void 0 ? { faultId } : {},
|
|
1937
|
+
...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
|
|
1938
|
+
...noted?.adopted ? { adopted: true } : {}
|
|
1939
|
+
};
|
|
1940
|
+
metrics.record(entry);
|
|
1941
|
+
journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
|
|
1942
|
+
options.onLog?.(entry);
|
|
1943
|
+
};
|
|
1944
|
+
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
1945
|
+
log(400);
|
|
1946
|
+
return stamp(new Response(JSON.stringify({
|
|
1947
|
+
error: {
|
|
1948
|
+
type: "mockingbird_admin",
|
|
1949
|
+
message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
|
|
1950
|
+
}
|
|
1951
|
+
}), { status: 400, headers: { "content-type": "application/json" } }));
|
|
1952
|
+
}
|
|
1953
|
+
if (!BRANCH_PATTERN2.test(selectedBranch)) {
|
|
1954
|
+
log(400);
|
|
1955
|
+
return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
|
|
1956
|
+
}
|
|
1957
|
+
let storage;
|
|
1958
|
+
try {
|
|
1959
|
+
if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
|
|
1960
|
+
const point = timeline(namespace).get(at);
|
|
1961
|
+
storage = physicalBranch(namespace, `at_${at}`);
|
|
1962
|
+
let viewRng = branchRngs.get(storage);
|
|
1963
|
+
if (!viewRng) {
|
|
1964
|
+
viewRng = createRng(options.seed ?? 0);
|
|
1965
|
+
instanceFor(storage, namespace, viewRng);
|
|
1966
|
+
}
|
|
1967
|
+
viewRng.setState(point.value.rngState);
|
|
1968
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
1969
|
+
captured.set(storage, point.value.snapshot);
|
|
1970
|
+
} else {
|
|
1971
|
+
storage = ensureBranch(namespace, selectedBranch, at);
|
|
1972
|
+
}
|
|
1973
|
+
} catch (error2) {
|
|
1974
|
+
log(409);
|
|
1975
|
+
return stamp(adminFail(409, error2 instanceof Error ? error2.message : String(error2)));
|
|
1976
|
+
}
|
|
1977
|
+
const hits = await faults.take({
|
|
1978
|
+
operationId,
|
|
1979
|
+
method: request.method,
|
|
1980
|
+
path: url.pathname,
|
|
1981
|
+
namespace
|
|
1982
|
+
});
|
|
1983
|
+
const final = hits.find((hit) => hit.drop || hit.response);
|
|
1984
|
+
if (final?.drop) {
|
|
1985
|
+
log(0, final.id);
|
|
1986
|
+
throw new DroppedConnectionError();
|
|
1987
|
+
}
|
|
1988
|
+
if (final?.response) {
|
|
1989
|
+
log(final.response.status, final.id);
|
|
1990
|
+
return stamp(final.response);
|
|
1991
|
+
}
|
|
1992
|
+
const fired = hits.filter((hit) => hit.effect !== void 0);
|
|
1993
|
+
if (fired.length > 0)
|
|
1994
|
+
effects.set(request, fired.map((hit) => hit.effect));
|
|
1995
|
+
let response = await instanceFor(storage, namespace).fetch(request);
|
|
1996
|
+
if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
|
|
1997
|
+
const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
|
|
1998
|
+
response = mutableResponse(response);
|
|
1999
|
+
response.headers.set(CHECKPOINT_HEADER, point.id);
|
|
2000
|
+
}
|
|
2001
|
+
if (selectedBranch !== "main") {
|
|
2002
|
+
response = mutableResponse(response);
|
|
2003
|
+
response.headers.set(BRANCH_HEADER, selectedBranch);
|
|
2004
|
+
}
|
|
2005
|
+
if (at !== void 0) {
|
|
2006
|
+
response = mutableResponse(response);
|
|
2007
|
+
response.headers.set(AT_HEADER, at);
|
|
2008
|
+
}
|
|
2009
|
+
log(response.status, fired[0]?.id, response);
|
|
2010
|
+
return stamp(response);
|
|
2011
|
+
}
|
|
2012
|
+
};
|
|
2013
|
+
const control = createControlPlane({
|
|
2014
|
+
name: options.name,
|
|
2015
|
+
startedAt: wallNow(),
|
|
2016
|
+
wallNow,
|
|
2017
|
+
clock,
|
|
2018
|
+
faults,
|
|
2019
|
+
metrics,
|
|
2020
|
+
journal,
|
|
2021
|
+
defaultNamespace: DEFAULT_NAMESPACE,
|
|
2022
|
+
namespaces: runtime.namespaces,
|
|
2023
|
+
reset,
|
|
2024
|
+
timeTravel: {
|
|
2025
|
+
checkpoint: (name, branchName) => {
|
|
2026
|
+
const point = checkpoint(name, branchName);
|
|
2027
|
+
return {
|
|
2028
|
+
id: point.id,
|
|
2029
|
+
branch: point.branch,
|
|
2030
|
+
parent: point.parent,
|
|
2031
|
+
at: point.at,
|
|
2032
|
+
records: point.value.snapshot.records.length
|
|
2033
|
+
};
|
|
2034
|
+
},
|
|
2035
|
+
branch: (branchName, branchOptions) => {
|
|
2036
|
+
const point = branch(branchName, branchOptions);
|
|
2037
|
+
return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
|
|
2038
|
+
},
|
|
2039
|
+
checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
|
|
2040
|
+
retain: (name, checkpointId) => {
|
|
2041
|
+
timeline(name).retain(checkpointId);
|
|
2042
|
+
},
|
|
2043
|
+
release: (name, checkpointId) => timeline(name).release(checkpointId),
|
|
2044
|
+
inspect: (name) => {
|
|
2045
|
+
const history = timeline(name);
|
|
2046
|
+
return {
|
|
2047
|
+
branches: history.branches(),
|
|
2048
|
+
checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
|
|
2049
|
+
id,
|
|
2050
|
+
branch: branchName,
|
|
2051
|
+
parent,
|
|
2052
|
+
at
|
|
2053
|
+
}))
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
},
|
|
2057
|
+
describe: options.describe ?? (() => ({})),
|
|
2058
|
+
...options.presets ? {
|
|
2059
|
+
applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
|
|
2060
|
+
} : {},
|
|
2061
|
+
routes: {
|
|
2062
|
+
...credentialRoutes(credentials),
|
|
2063
|
+
...options.presets ? presetRoutes(options.presets, runtime) : {},
|
|
2064
|
+
...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
|
|
2065
|
+
...options.admin?.(runtime) ?? {}
|
|
2066
|
+
},
|
|
2067
|
+
adminKey: options.adminKey
|
|
2068
|
+
});
|
|
2069
|
+
return runtime;
|
|
2070
|
+
};
|
|
2071
|
+
var mutableResponse = (response) => {
|
|
2072
|
+
try {
|
|
2073
|
+
response.headers.set("x-mockingbird-mutable-probe", "1");
|
|
2074
|
+
response.headers.delete("x-mockingbird-mutable-probe");
|
|
2075
|
+
return response;
|
|
2076
|
+
} catch {
|
|
2077
|
+
return new Response(response.body, response);
|
|
2078
|
+
}
|
|
2079
|
+
};
|
|
2080
|
+
var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2081
|
+
var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
|
|
2082
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2083
|
+
var credentialRoutes = (registry) => ({
|
|
2084
|
+
"GET /credentials": () => adminJson(200, {
|
|
2085
|
+
credentials: registry.entries().map(({ credential, namespace }) => ({
|
|
2086
|
+
credential: maskCredential(credential),
|
|
2087
|
+
namespace
|
|
2088
|
+
}))
|
|
2089
|
+
}),
|
|
2090
|
+
"PUT /credentials": ({ body, namespace }) => {
|
|
2091
|
+
const pairs = [];
|
|
2092
|
+
const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
|
|
2093
|
+
if (Array.isArray(list)) {
|
|
2094
|
+
for (const each of list) {
|
|
2095
|
+
if (typeof each === "string")
|
|
2096
|
+
pairs.push([each, namespace]);
|
|
2097
|
+
else if (isObject(each) && typeof each.credential === "string") {
|
|
2098
|
+
pairs.push([
|
|
2099
|
+
each.credential,
|
|
2100
|
+
typeof each.namespace === "string" ? each.namespace : namespace
|
|
2101
|
+
]);
|
|
2102
|
+
} else
|
|
2103
|
+
return adminFail(400, "each entry is a credential string or {credential, namespace}");
|
|
2104
|
+
}
|
|
2105
|
+
} else if (isObject(list)) {
|
|
2106
|
+
for (const [credential, target] of Object.entries(list)) {
|
|
2107
|
+
if (typeof target !== "string")
|
|
2108
|
+
return adminFail(400, `namespace for ${credential} must be a string`);
|
|
2109
|
+
pairs.push([credential, target]);
|
|
2110
|
+
}
|
|
2111
|
+
} else if (isObject(body) && typeof body.credential === "string") {
|
|
2112
|
+
pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
|
|
2113
|
+
} else {
|
|
2114
|
+
return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
|
|
2115
|
+
}
|
|
2116
|
+
for (const [credential, target] of pairs) {
|
|
2117
|
+
if (!NAMESPACE_PATTERN.test(target))
|
|
2118
|
+
return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
|
|
2119
|
+
registry.set(credential, target);
|
|
2120
|
+
}
|
|
2121
|
+
return adminJson(200, { mapped: pairs.length });
|
|
2122
|
+
},
|
|
2123
|
+
"DELETE /credentials": ({ url }) => {
|
|
2124
|
+
const credential = url.searchParams.get("credential");
|
|
2125
|
+
if (credential === null)
|
|
2126
|
+
registry.clear();
|
|
2127
|
+
else
|
|
2128
|
+
registry.remove(credential);
|
|
2129
|
+
return adminJson(200, { status: "ok" });
|
|
2130
|
+
}
|
|
2131
|
+
});
|
|
2132
|
+
var presetRoutes = (presets, runtime) => ({
|
|
2133
|
+
"GET /faults/presets": () => adminJson(200, {
|
|
2134
|
+
presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
|
|
2135
|
+
}),
|
|
2136
|
+
"POST /faults/presets/:name": ({ params, body, namespace }) => {
|
|
2137
|
+
const name = params.name;
|
|
2138
|
+
if (!presets[name])
|
|
2139
|
+
return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
|
|
2140
|
+
const overrides = isObject(body) ? body : {};
|
|
2141
|
+
return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
|
|
2142
|
+
}
|
|
2143
|
+
});
|
|
2144
|
+
|
|
2145
|
+
// ../core/dist/validation.js
|
|
2146
|
+
var bodyIssues = (context, contentType = "application/json") => {
|
|
2147
|
+
const requestBody = context.operation.operation.requestBody;
|
|
2148
|
+
if (!requestBody)
|
|
2149
|
+
return [];
|
|
2150
|
+
const resolved = deref(context.document, requestBody);
|
|
2151
|
+
const schema = resolved.content?.[contentType]?.schema;
|
|
2152
|
+
if (!schema)
|
|
2153
|
+
return [];
|
|
2154
|
+
const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
|
|
2155
|
+
if (context.body.kind === "invalid") {
|
|
2156
|
+
return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
|
|
2157
|
+
}
|
|
2158
|
+
if (value === void 0) {
|
|
2159
|
+
return resolved.required ? [{ path: "", message: "request body is required" }] : [];
|
|
2160
|
+
}
|
|
2161
|
+
return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
|
|
2162
|
+
};
|
|
2163
|
+
|
|
2164
|
+
// src/catalog.ts
|
|
2165
|
+
var DEFAULT_USER_ID = "65a1c0de00000000000000a1";
|
|
2166
|
+
var DEFAULT_CLINIC_ID = "65a1c0de00000000000000c1";
|
|
2167
|
+
var DEFAULT_CLINIC_LOCATION_ID = "65a1c0de00000000000000d1";
|
|
2168
|
+
var DEFAULT_PROVIDER_ID = "65a1c0de00000000000000e1";
|
|
2169
|
+
var DEFAULT_PATIENT_ID = "65a1c0de00000000000000f1";
|
|
2170
|
+
var REASONS = [
|
|
2171
|
+
"Product Discontinued - commercial product no longer available or in shortage",
|
|
2172
|
+
"Dosage Form Change - patient needs a different dosage form",
|
|
2173
|
+
"Different Strength - patient needs a strength not commercially available",
|
|
2174
|
+
"Excipient Allergy - patient is allergic to an inactive ingredient",
|
|
2175
|
+
"Other - reason not otherwise listed"
|
|
2176
|
+
];
|
|
2177
|
+
var DEFAULT_PRODUCTS = [
|
|
2178
|
+
{
|
|
2179
|
+
id: "64f1c2a9e4b0a1b2c3d4e5f6",
|
|
2180
|
+
productId: "2185_INJ",
|
|
2181
|
+
name: "Testosterone Cypionate",
|
|
2182
|
+
unitPrice: 45.5,
|
|
2183
|
+
family: "Hormone Restoration",
|
|
2184
|
+
subCategory1: "Testosterone",
|
|
2185
|
+
subCategory2: "Injectables",
|
|
2186
|
+
commonName: "Testosterone Cypionate",
|
|
2187
|
+
sigOptions: ["Inject 0.5 mL intramuscularly once weekly"],
|
|
2188
|
+
productSize: "10mL",
|
|
2189
|
+
medicalAccessories: "0",
|
|
2190
|
+
coldShipped: "0",
|
|
2191
|
+
controlledSubstance: "0",
|
|
2192
|
+
dispenseType: "Vial",
|
|
2193
|
+
reasonForCompoundedMedication: REASONS,
|
|
2194
|
+
isReasonForCompoundedMedicationNeeded: true,
|
|
2195
|
+
productType: "S",
|
|
2196
|
+
patientPayAmount: 62.5,
|
|
2197
|
+
ndc: 12345678901,
|
|
2198
|
+
discountedPercentage: 10
|
|
2199
|
+
},
|
|
2200
|
+
{
|
|
2201
|
+
id: "64f1c2a9e4b0a1b2c3d4e5f7",
|
|
2202
|
+
productId: "3097_POW",
|
|
2203
|
+
name: "Semaglutide / B6 Troche",
|
|
2204
|
+
unitPrice: 7.5,
|
|
2205
|
+
family: "Weight Management",
|
|
2206
|
+
subCategory1: "GLP-1",
|
|
2207
|
+
subCategory2: "Troches",
|
|
2208
|
+
commonName: "Semaglutide",
|
|
2209
|
+
sigOptions: ["Dissolve 1 troche under the tongue daily"],
|
|
2210
|
+
productSize: "30ea",
|
|
2211
|
+
medicalAccessories: "0",
|
|
2212
|
+
coldShipped: "1",
|
|
2213
|
+
controlledSubstance: "0",
|
|
2214
|
+
dispenseType: "Troche",
|
|
2215
|
+
reasonForCompoundedMedication: REASONS,
|
|
2216
|
+
isReasonForCompoundedMedicationNeeded: true,
|
|
2217
|
+
productType: "NS",
|
|
2218
|
+
patientPayAmount: 30,
|
|
2219
|
+
ndc: null,
|
|
2220
|
+
discountedPercentage: 0
|
|
2221
|
+
},
|
|
2222
|
+
{
|
|
2223
|
+
id: "64f1c2a9e4b0a1b2c3d4e5f8",
|
|
2224
|
+
productId: "4410_CAP",
|
|
2225
|
+
name: "Enclomiphene Citrate 25 mg",
|
|
2226
|
+
unitPrice: 1.2,
|
|
2227
|
+
family: "Hormone Restoration",
|
|
2228
|
+
subCategory1: "Testosterone",
|
|
2229
|
+
subCategory2: "Capsules",
|
|
2230
|
+
commonName: "Enclomiphene",
|
|
2231
|
+
sigOptions: ["Take 1 capsule by mouth daily"],
|
|
2232
|
+
productSize: "30ea",
|
|
2233
|
+
medicalAccessories: "0",
|
|
2234
|
+
coldShipped: "0",
|
|
2235
|
+
controlledSubstance: "0",
|
|
2236
|
+
dispenseType: "Capsule",
|
|
2237
|
+
reasonForCompoundedMedication: null,
|
|
2238
|
+
isReasonForCompoundedMedicationNeeded: false,
|
|
2239
|
+
productType: "NS",
|
|
2240
|
+
patientPayAmount: 40,
|
|
2241
|
+
ndc: null,
|
|
2242
|
+
discountedPercentage: 5
|
|
2243
|
+
},
|
|
2244
|
+
{
|
|
2245
|
+
id: "64f1c2a9e4b0a1b2c3d4e5f9",
|
|
2246
|
+
productId: "5120_INJ",
|
|
2247
|
+
name: "Nandrolone Decanoate",
|
|
2248
|
+
unitPrice: 55,
|
|
2249
|
+
family: "Hormone Restoration",
|
|
2250
|
+
subCategory1: "Testosterone",
|
|
2251
|
+
subCategory2: "Injectables",
|
|
2252
|
+
commonName: "Nandrolone",
|
|
2253
|
+
sigOptions: [],
|
|
2254
|
+
productSize: "5mL",
|
|
2255
|
+
medicalAccessories: "0",
|
|
2256
|
+
coldShipped: "0",
|
|
2257
|
+
controlledSubstance: "1",
|
|
2258
|
+
dispenseType: "Vial",
|
|
2259
|
+
reasonForCompoundedMedication: REASONS,
|
|
2260
|
+
isReasonForCompoundedMedicationNeeded: true,
|
|
2261
|
+
productType: "S",
|
|
2262
|
+
patientPayAmount: 80,
|
|
2263
|
+
ndc: null,
|
|
2264
|
+
discountedPercentage: 0
|
|
2265
|
+
}
|
|
2266
|
+
];
|
|
2267
|
+
var DEFAULT_CLINIC_LOCATION = {
|
|
2268
|
+
id: DEFAULT_CLINIC_LOCATION_ID,
|
|
2269
|
+
clinicId: DEFAULT_CLINIC_ID,
|
|
2270
|
+
locationName: "Geviti Main",
|
|
2271
|
+
email: "pharmacy@example.com",
|
|
2272
|
+
fax: "5555550100",
|
|
2273
|
+
addressLine1: "100 Clinic Way",
|
|
2274
|
+
addressLine2: null,
|
|
2275
|
+
city: "Phoenix",
|
|
2276
|
+
zipcode: "85004",
|
|
2277
|
+
state: "AZ"
|
|
2278
|
+
};
|
|
2279
|
+
var DEFAULT_PROVIDERS = [
|
|
2280
|
+
{
|
|
2281
|
+
id: DEFAULT_PROVIDER_ID,
|
|
2282
|
+
firstName: "Grace",
|
|
2283
|
+
lastName: "Hopper",
|
|
2284
|
+
npi: "1234567893",
|
|
2285
|
+
clinicLocationId: DEFAULT_CLINIC_LOCATION_ID
|
|
2286
|
+
},
|
|
2287
|
+
{
|
|
2288
|
+
id: "65a1c0de00000000000000e2",
|
|
2289
|
+
firstName: "Alan",
|
|
2290
|
+
lastName: "Turing",
|
|
2291
|
+
npi: "1987654320",
|
|
2292
|
+
clinicLocationId: DEFAULT_CLINIC_LOCATION_ID
|
|
2293
|
+
}
|
|
2294
|
+
];
|
|
2295
|
+
var DEFAULT_PATIENTS = [
|
|
2296
|
+
{
|
|
2297
|
+
id: DEFAULT_PATIENT_ID,
|
|
2298
|
+
clinicId: DEFAULT_CLINIC_ID,
|
|
2299
|
+
firstName: "Ada",
|
|
2300
|
+
lastName: "Lovelace",
|
|
2301
|
+
dateOfBirth: "1985-02-14",
|
|
2302
|
+
email: "ada@example.com",
|
|
2303
|
+
phoneNumber: "6025550142",
|
|
2304
|
+
cellPhone: null,
|
|
2305
|
+
addresses: [
|
|
2306
|
+
{
|
|
2307
|
+
id: "65a1c0de0000000000000af1",
|
|
2308
|
+
addressLine1: "1 Main St",
|
|
2309
|
+
addressLine2: null,
|
|
2310
|
+
city: "Phoenix",
|
|
2311
|
+
state: "AZ",
|
|
2312
|
+
zipcode: "85004"
|
|
2313
|
+
}
|
|
2314
|
+
]
|
|
2315
|
+
}
|
|
2316
|
+
];
|
|
2317
|
+
var SHIPPING_STATES = [
|
|
2318
|
+
"Alabama",
|
|
2319
|
+
"Alaska",
|
|
2320
|
+
"Arizona",
|
|
2321
|
+
"Arkansas",
|
|
2322
|
+
"California",
|
|
2323
|
+
"Colorado",
|
|
2324
|
+
"Connecticut",
|
|
2325
|
+
"Delaware",
|
|
2326
|
+
"Florida",
|
|
2327
|
+
"Georgia",
|
|
2328
|
+
"Hawaii",
|
|
2329
|
+
"Idaho",
|
|
2330
|
+
"Illinois",
|
|
2331
|
+
"Indiana",
|
|
2332
|
+
"Iowa",
|
|
2333
|
+
"Kansas",
|
|
2334
|
+
"Kentucky",
|
|
2335
|
+
"Louisiana",
|
|
2336
|
+
"Maine",
|
|
2337
|
+
"Maryland",
|
|
2338
|
+
"Massachusetts",
|
|
2339
|
+
"Michigan",
|
|
2340
|
+
"Minnesota",
|
|
2341
|
+
"Mississippi",
|
|
2342
|
+
"Missouri",
|
|
2343
|
+
"Montana",
|
|
2344
|
+
"Nebraska",
|
|
2345
|
+
"Nevada",
|
|
2346
|
+
"New Hampshire",
|
|
2347
|
+
"New Jersey",
|
|
2348
|
+
"New Mexico",
|
|
2349
|
+
"New York",
|
|
2350
|
+
"North Carolina",
|
|
2351
|
+
"North Dakota",
|
|
2352
|
+
"Ohio",
|
|
2353
|
+
"Oklahoma",
|
|
2354
|
+
"Oregon",
|
|
2355
|
+
"Pennsylvania",
|
|
2356
|
+
"Rhode Island",
|
|
2357
|
+
"South Carolina",
|
|
2358
|
+
"South Dakota",
|
|
2359
|
+
"Tennessee",
|
|
2360
|
+
"Texas",
|
|
2361
|
+
"Utah",
|
|
2362
|
+
"Vermont",
|
|
2363
|
+
"Virginia",
|
|
2364
|
+
"Washington",
|
|
2365
|
+
"West Virginia",
|
|
2366
|
+
"Wisconsin",
|
|
2367
|
+
"Wyoming",
|
|
2368
|
+
"District of Columbia"
|
|
2369
|
+
].map((name) => ({
|
|
2370
|
+
name,
|
|
2371
|
+
booleanCheck: name !== "District of Columbia",
|
|
2372
|
+
nonSterile: true,
|
|
2373
|
+
sterile: name !== "Alabama" && name !== "District of Columbia"
|
|
2374
|
+
}));
|
|
2375
|
+
var STATE_CODES = {
|
|
2376
|
+
Alabama: "AL",
|
|
2377
|
+
Alaska: "AK",
|
|
2378
|
+
Arizona: "AZ",
|
|
2379
|
+
Arkansas: "AR",
|
|
2380
|
+
California: "CA",
|
|
2381
|
+
Colorado: "CO",
|
|
2382
|
+
Connecticut: "CT",
|
|
2383
|
+
Delaware: "DE",
|
|
2384
|
+
Florida: "FL",
|
|
2385
|
+
Georgia: "GA",
|
|
2386
|
+
Hawaii: "HI",
|
|
2387
|
+
Idaho: "ID",
|
|
2388
|
+
Illinois: "IL",
|
|
2389
|
+
Indiana: "IN",
|
|
2390
|
+
Iowa: "IA",
|
|
2391
|
+
Kansas: "KS",
|
|
2392
|
+
Kentucky: "KY",
|
|
2393
|
+
Louisiana: "LA",
|
|
2394
|
+
Maine: "ME",
|
|
2395
|
+
Maryland: "MD",
|
|
2396
|
+
Massachusetts: "MA",
|
|
2397
|
+
Michigan: "MI",
|
|
2398
|
+
Minnesota: "MN",
|
|
2399
|
+
Mississippi: "MS",
|
|
2400
|
+
Missouri: "MO",
|
|
2401
|
+
Montana: "MT",
|
|
2402
|
+
Nebraska: "NE",
|
|
2403
|
+
Nevada: "NV",
|
|
2404
|
+
"New Hampshire": "NH",
|
|
2405
|
+
"New Jersey": "NJ",
|
|
2406
|
+
"New Mexico": "NM",
|
|
2407
|
+
"New York": "NY",
|
|
2408
|
+
"North Carolina": "NC",
|
|
2409
|
+
"North Dakota": "ND",
|
|
2410
|
+
Ohio: "OH",
|
|
2411
|
+
Oklahoma: "OK",
|
|
2412
|
+
Oregon: "OR",
|
|
2413
|
+
Pennsylvania: "PA",
|
|
2414
|
+
"Rhode Island": "RI",
|
|
2415
|
+
"South Carolina": "SC",
|
|
2416
|
+
"South Dakota": "SD",
|
|
2417
|
+
Tennessee: "TN",
|
|
2418
|
+
Texas: "TX",
|
|
2419
|
+
Utah: "UT",
|
|
2420
|
+
Vermont: "VT",
|
|
2421
|
+
Virginia: "VA",
|
|
2422
|
+
Washington: "WA",
|
|
2423
|
+
"West Virginia": "WV",
|
|
2424
|
+
Wisconsin: "WI",
|
|
2425
|
+
Wyoming: "WY",
|
|
2426
|
+
"District of Columbia": "DC",
|
|
2427
|
+
"American Samoa": "AS",
|
|
2428
|
+
Guam: "GU",
|
|
2429
|
+
"Northern Mariana Islands": "MP",
|
|
2430
|
+
"Puerto Rico": "PR",
|
|
2431
|
+
"U.S. Virgin Islands": "VI"
|
|
2432
|
+
};
|
|
2433
|
+
|
|
2434
|
+
// src/generated/openapi.ts
|
|
2435
|
+
var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"VPI compounding pharmacy API (Mockingbird subset)","description":"Stateful mock subset of the VPI (vpicompounding.net) clinic API our backend drives as a\\ndraft-only eRx rail: JWT authentication, product taxonomy/details/discounts, day supply,\\nshipping states and rates, clinic location, providers, patients, the provider-signature\\nduplicate check, saveNewPrescription, and the three paged prescription status lists.\\nHand-derived from the consumer's zod contracts (the vendor publishes no spec).\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-derived from apps/backend/src/modules/erx/clients/vpi-api.contracts.ts and the client-local schemas in vpi-api.client.ts (request bodies are exactly what the client sends; responses are what its zod schemas accept)."}},"servers":[{"url":"https://api.vpicompounding.net"}],"security":[{"bearerAuth":[]}],"paths":{"/accounts/authenticate":{"post":{"operationId":"Authenticate","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["email","password"],"properties":{"email":{"type":"string","minLength":1,"maxLength":120},"password":{"type":"string","minLength":1,"maxLength":120},"isPatientLogin":{"type":"boolean"}}}}}},"responses":{"200":{"description":"JWT and refresh token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AuthTokens"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/products/getAllFamiliesAndCategories":{"get":{"operationId":"GetAllFamiliesAndCategories","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Product families and their categories (subCategory1)","content":{"application/json":{"schema":{"type":"array","items":{"type":"object","required":["family","categories"],"properties":{"family":{"type":"string"},"categories":{"type":"array","items":{"type":"string"}}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/products/getProductsByCategory":{"post":{"operationId":"GetProductsByCategory","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["category","subCategory1"],"examples":[{"category":"Hormone Restoration","subCategory1":"Testosterone"},{"category":"Weight Management","subCategory1":"GLP-1"}],"properties":{"category":{"type":"string","minLength":1,"maxLength":80,"examples":["Hormone Restoration","Weight Management"]},"subCategory1":{"type":"string","minLength":1,"maxLength":80,"examples":["Testosterone","GLP-1"]}}}}}},"responses":{"200":{"description":"Products grouped by subCategory2, then common name","content":{"application/json":{"schema":{"type":"array","items":{"type":"object","required":["subCategory2_item","commonNames"],"properties":{"subCategory2_item":{"type":"string"},"commonNames":{"type":"array","items":{"type":"object","required":["commonName","products"],"properties":{"commonName":{"type":"string"},"products":{"type":"array","items":{"$ref":"#/components/schemas/ProductSummary"}}}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/products/getProductDetailsByProductId/{productId}":{"parameters":[{"name":"productId","in":"path","required":true,"description":"The product's Mongo id (\`id\`), not its catalog code.","schema":{"type":"string","x-mockingbird-resource-ref":{"type":"product","missing":0}}}],"get":{"operationId":"GetProductDetailsByProductId","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Product details","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProductDetails"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/products/getProductDiscountByProductIds":{"post":{"operationId":"GetProductDiscountByProductIds","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["clinicId","productIds"],"properties":{"clinicId":{"$ref":"#/components/schemas/ClinicId"},"productIds":{"type":"array","minItems":1,"maxItems":5,"items":{"type":"string","minLength":1,"x-mockingbird-resource-ref":{"type":"product","missing":0}}}}}}}},"responses":{"200":{"description":"The clinic's discount for each known product","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/ProductDiscount"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/products/calculateDaySupply":{"post":{"operationId":"CalculateDaySupply","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["productId","quantity","sig"],"properties":{"productId":{"type":"string","minLength":1,"x-mockingbird-resource-ref":{"type":"product","missing":0}},"quantity":{"type":"number","exclusiveMinimum":0,"maximum":1000},"sig":{"type":"string","minLength":1,"maxLength":500}}}}}},"responses":{"200":{"description":"Day supply","content":{"application/json":{"schema":{"type":"object","required":["daySupply"],"properties":{"daySupply":{"type":"integer","minimum":1},"daySupplyReason":{"type":["string","null"]}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/admin/rxOrdering/getShippingStates":{"get":{"operationId":"GetShippingStates","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"States VPI ships to, by full name","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"type":"object","required":["states"],"properties":{"states":{"type":"array","items":{"type":"object","required":["name","booleanCheck","nonSterile","sterile"],"properties":{"name":{"type":"string"},"booleanCheck":{"type":"boolean"},"nonSterile":{"type":"boolean"},"sterile":{"type":"boolean"}}}}}}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/portal/getShippingRate":{"post":{"operationId":"GetShippingRate","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["clinicId","clinicLocationId","patientId","productIds","shippingState","isRushOrder"],"properties":{"clinicId":{"$ref":"#/components/schemas/ClinicId"},"clinicLocationId":{"$ref":"#/components/schemas/ClinicLocationId"},"patientId":{"type":"string","minLength":1,"x-mockingbird-resource-ref":{"type":"patient","missing":0}},"productIds":{"type":"array","minItems":1,"maxItems":5,"items":{"type":"string","minLength":1,"x-mockingbird-resource-ref":{"type":"product","missing":0}}},"shippingState":{"type":"string","pattern":"^[A-Za-z]{2}$","examples":["AZ","TX","NY"]},"isRushOrder":{"type":"boolean"}}}}}},"responses":{"200":{"description":"Shipping method and rush cost","content":{"application/json":{"schema":{"type":"object","required":["shippingMethod","rushOrderCost","rushOrderMethod","isSignatureRequired"],"properties":{"shippingMethod":{"type":"string"},"rushOrderCost":{"type":"number","minimum":0},"rushOrderMethod":{"type":"string"},"isSignatureRequired":{"type":"boolean"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/clinic/rxOrdering/checkProviderSignatureNeededDuplicate":{"post":{"operationId":"CheckProviderSignatureNeededDuplicate","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["clinicId","patientIds","productIds","clinicLocationIds"],"properties":{"clinicId":{"$ref":"#/components/schemas/ClinicId"},"patientIds":{"type":"array","minItems":1,"maxItems":3,"items":{"type":"string","minLength":1,"x-mockingbird-resource-ref":{"type":"patient","missing":0}}},"productIds":{"type":"array","minItems":1,"maxItems":3,"items":{"type":"string","minLength":1,"x-mockingbird-resource-ref":{"type":"product","missing":0}}},"clinicLocationIds":{"type":"array","minItems":1,"maxItems":3,"items":{"$ref":"#/components/schemas/ClinicLocationId"}}}}}}},"responses":{"200":{"description":"Duplicate and provider-signature flags","content":{"application/json":{"schema":{"type":"object","required":["isDuplicate","isProviderSignatureNeeded"],"properties":{"isDuplicate":{"type":"boolean"},"isProviderSignatureNeeded":{"type":"boolean"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"}}}},"/clinic/rxOrdering/saveNewPrescription":{"post":{"operationId":"SaveNewPrescription","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SavePrescriptionBody"}}}},"responses":{"200":{"description":"Draft saved (awaiting provider signature)","content":{"application/json":{"schema":{"type":"object","required":["message","prescriptionId","isRefillRequest","refillFromPrescriptionId"],"properties":{"message":{"type":"string"},"prescriptionId":{"type":"string","x-mockingbird-resource":{"type":"prescription","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"isRefillRequest":{"type":"boolean"},"refillFromPrescriptionId":{"type":["string","null"]}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"429":{"$ref":"#/components/responses/Conflict"}}}},"/patients/getPatientByPatientId":{"post":{"operationId":"GetPatientByPatientId","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientLookupBody"}}}},"responses":{"200":{"description":"Patient","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Patient"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/patients/getPatientAddressesByPatientId":{"post":{"operationId":"GetPatientAddressesByPatientId","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientLookupBody"}}}},"responses":{"200":{"description":"The patient's addresses","content":{"application/json":{"schema":{"type":"object","required":["addresses"],"properties":{"addresses":{"type":"array","items":{"$ref":"#/components/schemas/Address"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/patients/getPatientsInClinic":{"post":{"operationId":"GetPatientsInClinic","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["clinicId","userId","limit","currentPage"],"examples":[{"clinicId":"65a1c0de00000000000000c1","userId":"65a1c0de00000000000000a1","limit":100,"currentPage":1}],"properties":{"clinicId":{"$ref":"#/components/schemas/ClinicId"},"userId":{"$ref":"#/components/schemas/UserId"},"limit":{"type":"integer","minimum":1,"maximum":100},"currentPage":{"type":"integer","minimum":1,"maximum":50}}}}}},"responses":{"200":{"description":"One page of the clinic's patient roster","content":{"application/json":{"schema":{"type":"object","required":["pagination","patients"],"properties":{"pagination":{"type":"object","required":["hasNextPage"],"properties":{"hasNextPage":{"type":"boolean"},"currentPage":{"type":"integer"},"limit":{"type":"integer"},"totalCount":{"type":"integer"}}},"patients":{"type":"array","items":{"$ref":"#/components/schemas/Patient"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/staffs/getAllProvidersByClinicLocationId":{"post":{"operationId":"GetAllProvidersByClinicLocationId","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["clinicLocationId","clinicId"],"properties":{"clinicLocationId":{"$ref":"#/components/schemas/ClinicLocationId"},"clinicId":{"$ref":"#/components/schemas/ClinicId"}}}}}},"responses":{"200":{"description":"Providers at the location","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Provider"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/clinicLocations/getClinicLocationByClinicLocationId":{"post":{"operationId":"GetClinicLocationByClinicLocationId","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["clinicLocationId"],"properties":{"clinicLocationId":{"$ref":"#/components/schemas/ClinicLocationId"}}}}}},"responses":{"200":{"description":"Clinic location","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicLocation"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/clinic/rxOrdering/getIncompleteSavedPrescriptionsInClinicLocation":{"post":{"operationId":"GetIncompleteSavedPrescriptionsInClinicLocation","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PrescriptionPageBody"}}}},"responses":{"200":{"$ref":"#/components/responses/PrescriptionRows"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/clinic/rxOrdering/getSubmittedPrescriptionsInClinicLocation":{"post":{"operationId":"GetSubmittedPrescriptionsInClinicLocation","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PrescriptionPageBody"}}}},"responses":{"200":{"$ref":"#/components/responses/PrescriptionRows"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/clinic/rxOrdering/getArchivedPrescriptionsInClinic":{"post":{"operationId":"GetArchivedPrescriptionsInClinic","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PrescriptionPageBody"}}}},"responses":{"200":{"$ref":"#/components/responses/PrescriptionRows"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"JWT"}},"responses":{"BadRequest":{"description":"Invalid request body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"Unauthorized":{"description":"Missing, invalid or expired JWT (or bad credentials)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"NotFound":{"description":"Unknown clinic, location, patient, product or provider","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"Conflict":{"description":"The request could not be completed right now","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorBody"}}}},"PrescriptionRows":{"description":"One page of prescription status rows, in one of the four envelopes our client accepts (bare array, {prescriptions}, {message: [...]}, {message: {prescriptions}}).","content":{"application/json":{"schema":{"anyOf":[{"type":"array","items":{"$ref":"#/components/schemas/PrescriptionRow"}},{"type":"object","required":["prescriptions"],"properties":{"prescriptions":{"type":"array","items":{"$ref":"#/components/schemas/PrescriptionRow"}}}},{"type":"object","required":["message"],"properties":{"message":{"anyOf":[{"type":"array","items":{"$ref":"#/components/schemas/PrescriptionRow"}},{"type":"object","required":["prescriptions"],"properties":{"prescriptions":{"type":"array","items":{"$ref":"#/components/schemas/PrescriptionRow"}}}}]}}}]}}}}},"schemas":{"ErrorBody":{"type":"object","required":["message"],"properties":{"message":{"type":"string"},"errors":{"type":"array","items":{"type":"object","required":["path","message"],"properties":{"path":{"type":"string"},"message":{"type":"string"}}}}}},"ClinicId":{"type":"string","minLength":1,"maxLength":64,"examples":["65a1c0de00000000000000c1"]},"ClinicLocationId":{"type":"string","minLength":1,"maxLength":64,"examples":["65a1c0de00000000000000d1"]},"UserId":{"type":"string","minLength":1,"maxLength":64,"examples":["65a1c0de00000000000000a1"]},"AuthTokens":{"type":"object","required":["id","jwtToken","refreshToken"],"properties":{"id":{"type":"string"},"jwtToken":{"type":"string","x-mockingbird-volatile":{"kind":"token"}},"refreshToken":{"type":"string","x-mockingbird-volatile":{"kind":"token"}}}},"ProductSummary":{"type":"object","required":["id","name","unitPrice","productId","productSize","medicalAccessories","coldShipped","controlledSubstance","dispenseType","productType","isReasonForCompoundedMedicationNeeded"],"properties":{"id":{"type":"string","x-mockingbird-resource":{"type":"product","identity":true}},"name":{"type":"string"},"unitPrice":{"type":"number","minimum":0},"productId":{"type":"string"},"productSize":{"type":"string"},"medicalAccessories":{"type":"string","enum":["0","1"]},"coldShipped":{"type":"string","enum":["0","1"]},"controlledSubstance":{"type":"string","enum":["0","1"]},"dispenseType":{"type":"string"},"productType":{"type":"string","enum":["S","NS"]},"isReasonForCompoundedMedicationNeeded":{"type":"boolean"}}},"ProductDetails":{"type":"object","required":["id","productId","name","unitPrice","family","subCategory1","subCategory2","commonName","sigOptions","productSize","medicalAccessories","coldShipped","controlledSubstance","dispenseType","isReasonForCompoundedMedicationNeeded","productType"],"properties":{"id":{"type":"string"},"productId":{"type":"string"},"name":{"type":"string"},"unitPrice":{"type":"number","minimum":0},"family":{"type":"string"},"subCategory1":{"type":"string"},"subCategory2":{"type":"string"},"commonName":{"type":"string"},"sigOptions":{"type":"array","items":{"type":"string"}},"productSize":{"type":"string"},"medicalAccessories":{"type":"string","enum":["0","1"]},"coldShipped":{"type":"string","enum":["0","1"]},"controlledSubstance":{"type":"string","enum":["0","1"]},"dispenseType":{"type":"string"},"reasonForCompoundedMedication":{"type":["array","null"],"items":{"type":"string"}},"isReasonForCompoundedMedicationNeeded":{"type":"boolean"},"productType":{"type":"string","enum":["S","NS"]},"patientPayAmount":{"type":["number","null"]},"ndc":{"type":["number","null"]},"isActive":{"type":"boolean"},"isAvailable":{"type":"boolean"}}},"ProductDiscount":{"type":"object","required":["id","productId","discountedPrice","unitPrice","discountedPercentage","controlledSubstance"],"properties":{"id":{"type":"string"},"productId":{"type":"string"},"discountedPrice":{"type":"number","minimum":0},"unitPrice":{"type":"number","minimum":0},"discountedPercentage":{"type":"number","minimum":0,"maximum":100},"controlledSubstance":{"type":"string","enum":["0","1"]}}},"Patient":{"type":"object","required":["id","firstName","lastName","dateOfBirth"],"properties":{"id":{"type":"string","x-mockingbird-resource":{"type":"patient","identity":true}},"firstName":{"type":"string"},"lastName":{"type":"string"},"dateOfBirth":{"type":"string"},"email":{"type":["string","null"]},"phoneNumber":{"type":["string","null"]},"cellPhone":{"type":["string","null"]}}},"Address":{"type":"object","required":["id","addressLine1","addressLine2","city","state","zipcode"],"properties":{"id":{"type":"string"},"addressLine1":{"type":"string"},"addressLine2":{"type":["string","null"]},"city":{"type":"string"},"state":{"type":"string"},"zipcode":{"type":"string"}}},"Provider":{"type":"object","required":["id","firstName","lastName","npi"],"properties":{"id":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"npi":{"type":["string","null"]},"deaInfo":{"type":"array","items":{"type":"object"}},"providerLicenses":{"type":"array","items":{"type":"object"}},"allowExostar":{"type":"boolean"},"isSuperUserSameAsProvider":{"type":"boolean"}}},"ClinicLocation":{"type":"object","required":["id","clinicId","locationName"],"properties":{"id":{"type":"string"},"clinicId":{"type":"string"},"locationName":{"type":"string"},"email":{"type":["string","null"]},"fax":{"type":["string","null"]},"addressLine1":{"type":["string","null"]},"addressLine2":{"type":["string","null"]},"city":{"type":["string","null"]},"zipcode":{"type":["string","null"]},"state":{"type":["string","null"]}}},"PatientLookupBody":{"type":"object","required":["patientId","userId"],"properties":{"patientId":{"type":"string","minLength":1,"x-mockingbird-resource-ref":{"type":"patient","missing":0}},"userId":{"$ref":"#/components/schemas/UserId"}}},"PrescriptionPageBody":{"type":"object","required":["clinicLocationId","userId","limit","currentPage"],"properties":{"clinicLocationId":{"$ref":"#/components/schemas/ClinicLocationId"},"userId":{"$ref":"#/components/schemas/UserId"},"limit":{"type":"integer","minimum":1,"maximum":100},"currentPage":{"type":"integer","minimum":1,"maximum":50}}},"PrescriptionRow":{"type":"object","required":["prescriptionStatus"],"properties":{"prescriptionId":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"prescriptionStatus":{"type":"string"},"trackingNumber":{"type":["string","null"]},"patientId":{"type":"string"},"createdAt":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"SavePrescriptionProduct":{"type":"object","required":["id","productId","name","unitPrice","family","subCategory1","subCategory2","commonName","sigOptions","productSize","medicalAccessories","coldShipped","controlledSubstance","dispenseType","reasonForCompoundedMedication","isReasonForCompoundedMedicationNeeded","productType","patientPay","ndc","quantity","sig","daySupply","daySupplyReason","refills","isCustomSig","discountedPercentage","discountedPrice","displayedGeneratedSig"],"properties":{"id":{"type":"string","minLength":1,"x-mockingbird-resource-ref":{"type":"product","missing":0}},"productId":{"type":"string","minLength":1,"maxLength":40},"name":{"type":"string","minLength":1,"maxLength":120},"unitPrice":{"type":"number","minimum":0,"maximum":10000},"family":{"type":"string","minLength":1,"maxLength":80},"subCategory1":{"type":"string","minLength":1,"maxLength":80},"subCategory2":{"type":"string","minLength":1,"maxLength":80},"commonName":{"type":"string","minLength":1,"maxLength":120},"sigOptions":{"type":"array","maxItems":3,"items":{"type":"string","minLength":1,"maxLength":120}},"productSize":{"type":"string","minLength":1,"maxLength":40},"medicalAccessories":{"type":"array","maxItems":2,"items":{"type":"object"}},"coldShipped":{"type":"string","enum":["0","1"]},"controlledSubstance":{"description":"VPI's API rail excludes controlled substances.","type":"string","enum":["0"]},"dispenseType":{"type":"string","minLength":1,"maxLength":40},"reasonForCompoundedMedication":{"type":"string","maxLength":200},"isReasonForCompoundedMedicationNeeded":{"type":"boolean"},"productType":{"type":"string","enum":["S","NS"]},"patientPay":{"type":"number","minimum":0,"maximum":10000},"ndc":{"type":"string","maxLength":11},"quantity":{"type":"number","exclusiveMinimum":0,"maximum":1000},"sig":{"type":"string","minLength":1,"maxLength":500},"daySupply":{"type":"integer","minimum":1,"maximum":365},"daySupplyReason":{"type":"string","maxLength":200},"refills":{"type":"integer","minimum":0,"maximum":12},"isCustomSig":{"type":"boolean"},"discountedPercentage":{"type":"number","minimum":0,"maximum":100},"discountedPrice":{"type":"number","minimum":0,"maximum":10000},"displayedGeneratedSig":{"type":"string","minLength":1,"maxLength":500}}},"SavePrescriptionBody":{"type":"object","required":["patientIds","clinicLocationId","providerId","clinicId","userId","products","rxPadProducts","shippingInfo","patientNotificationRecipients"],"properties":{"patientIds":{"type":"array","minItems":1,"maxItems":1,"items":{"type":"string","minLength":1,"x-mockingbird-resource-ref":{"type":"patient","missing":0}}},"clinicLocationId":{"$ref":"#/components/schemas/ClinicLocationId"},"providerId":{"type":"string","minLength":1,"maxLength":64,"examples":["65a1c0de00000000000000e1"]},"clinicId":{"$ref":"#/components/schemas/ClinicId"},"userId":{"$ref":"#/components/schemas/UserId"},"products":{"type":"array","minItems":1,"maxItems":2,"items":{"$ref":"#/components/schemas/SavePrescriptionProduct"}},"rxPadProducts":{"type":"array","maxItems":2,"items":{"type":"object"}},"shippingInfo":{"type":"object","required":["isRushOrder","isSignatureRequired","orderNotes","shipTo","isNewAddressUsed","shippingMethod","shippingAddress","rushOrderCost","rushOrderMethod"],"properties":{"isRushOrder":{"type":"boolean"},"isSignatureRequired":{"type":"boolean"},"orderNotes":{"type":"string","maxLength":500},"shipTo":{"type":"string","minLength":1,"maxLength":40},"isNewAddressUsed":{"type":"boolean"},"shippingMethod":{"type":"string","minLength":1,"maxLength":40},"shippingAddress":{"type":"object","required":["addressLine1","addressLine2","city","state","zipcode"],"properties":{"addressLine1":{"type":"string","minLength":1,"maxLength":80},"addressLine2":{"type":"string","maxLength":80},"city":{"type":"string","minLength":1,"maxLength":40},"state":{"description":"The canonical full state name (never the 2-letter code).","type":"string","enum":["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming","District of Columbia","American Samoa","Guam","Northern Mariana Islands","Puerto Rico","U.S. Virgin Islands"]},"zipcode":{"type":"string","minLength":1,"maxLength":10}}},"rushOrderCost":{"type":"number","minimum":0,"maximum":1000},"rushOrderMethod":{"type":"string","maxLength":40}}},"creditRequested":{"type":"boolean"},"encryptedBillingInfo":{"type":"string","minLength":1,"maxLength":2000},"patientNotificationRecipients":{"type":"array","maxItems":2,"items":{"type":"object"}}}}}}}`);
|
|
2436
|
+
var operationIds = ["Authenticate", "GetAllFamiliesAndCategories", "GetProductsByCategory", "GetProductDetailsByProductId", "GetProductDiscountByProductIds", "CalculateDaySupply", "GetShippingStates", "GetShippingRate", "CheckProviderSignatureNeededDuplicate", "SaveNewPrescription", "GetPatientByPatientId", "GetPatientAddressesByPatientId", "GetPatientsInClinic", "GetAllProvidersByClinicLocationId", "GetClinicLocationByClinicLocationId", "GetIncompleteSavedPrescriptionsInClinicLocation", "GetSubmittedPrescriptionsInClinicLocation", "GetArchivedPrescriptionsInClinic"];
|
|
2437
|
+
var supportedOperationIds = ["Authenticate", "GetAllFamiliesAndCategories", "GetProductsByCategory", "GetProductDetailsByProductId", "GetProductDiscountByProductIds", "CalculateDaySupply", "GetShippingStates", "GetShippingRate", "CheckProviderSignatureNeededDuplicate", "SaveNewPrescription", "GetPatientByPatientId", "GetPatientAddressesByPatientId", "GetPatientsInClinic", "GetAllProvidersByClinicLocationId", "GetClinicLocationByClinicLocationId", "GetIncompleteSavedPrescriptionsInClinicLocation", "GetSubmittedPrescriptionsInClinicLocation", "GetArchivedPrescriptionsInClinic"];
|
|
2438
|
+
|
|
2439
|
+
// src/state.ts
|
|
2440
|
+
var DEFAULT_SETTINGS = {
|
|
2441
|
+
tokenTtlSeconds: 3600,
|
|
2442
|
+
accounts: [],
|
|
2443
|
+
statusEnvelope: "vendor",
|
|
2444
|
+
isProviderSignatureNeeded: true
|
|
2445
|
+
};
|
|
2446
|
+
var VpiState = class {
|
|
2447
|
+
constructor(sqlite, namespace, seed) {
|
|
2448
|
+
this.seed = seed;
|
|
2449
|
+
this.products = new Collection(sqlite, namespace, "products");
|
|
2450
|
+
this.providers = new Collection(sqlite, namespace, "providers");
|
|
2451
|
+
this.locations = new Collection(sqlite, namespace, "clinic_locations");
|
|
2452
|
+
this.patients = new Collection(sqlite, namespace, "patients");
|
|
2453
|
+
this.prescriptions = new Collection(sqlite, namespace, "prescriptions");
|
|
2454
|
+
this.settings = new Collection(sqlite, namespace, "settings");
|
|
2455
|
+
this.ensureSeeded();
|
|
2456
|
+
}
|
|
2457
|
+
seed;
|
|
2458
|
+
products;
|
|
2459
|
+
providers;
|
|
2460
|
+
locations;
|
|
2461
|
+
patients;
|
|
2462
|
+
prescriptions;
|
|
2463
|
+
settings;
|
|
2464
|
+
/** Re-apply the seed after a reset. */
|
|
2465
|
+
ensureSeeded() {
|
|
2466
|
+
const { data } = this.seed;
|
|
2467
|
+
if (this.products.count() === 0) {
|
|
2468
|
+
for (const p of data.products ?? DEFAULT_PRODUCTS) this.products.insert(p.id, p);
|
|
2469
|
+
}
|
|
2470
|
+
if (this.providers.count() === 0) {
|
|
2471
|
+
for (const p of data.providers ?? DEFAULT_PROVIDERS) this.providers.insert(p.id, p);
|
|
2472
|
+
}
|
|
2473
|
+
if (this.locations.count() === 0) {
|
|
2474
|
+
for (const l of data.clinicLocations ?? [DEFAULT_CLINIC_LOCATION]) {
|
|
2475
|
+
this.locations.insert(l.id, l);
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2478
|
+
if (this.patients.count() === 0) {
|
|
2479
|
+
for (const p of data.patients ?? DEFAULT_PATIENTS) this.patients.insert(p.id, p);
|
|
2480
|
+
}
|
|
2481
|
+
if (!this.settings.has("settings")) {
|
|
2482
|
+
this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed.settings });
|
|
2483
|
+
}
|
|
2484
|
+
}
|
|
2485
|
+
current() {
|
|
2486
|
+
return this.settings.get("settings") ?? DEFAULT_SETTINGS;
|
|
2487
|
+
}
|
|
2488
|
+
update(patch) {
|
|
2489
|
+
const next = { ...this.current(), ...patch };
|
|
2490
|
+
this.settings.insert("settings", next);
|
|
2491
|
+
return next;
|
|
2492
|
+
}
|
|
2493
|
+
/** Clinic ids that exist (every location's clinic). */
|
|
2494
|
+
hasClinic(clinicId) {
|
|
2495
|
+
return this.locations.list().some((row) => row.value.clinicId === clinicId);
|
|
2496
|
+
}
|
|
2497
|
+
/** A Mongo-looking prescription id, deterministic per namespace history. */
|
|
2498
|
+
nextPrescriptionId() {
|
|
2499
|
+
return `66b2${this.prescriptions.nextSequence().toString(16).padStart(20, "0")}`;
|
|
2500
|
+
}
|
|
2501
|
+
/** A patient id for seeded patients that omit one. */
|
|
2502
|
+
nextPatientId() {
|
|
2503
|
+
return `66b4${this.patients.nextSequence().toString(16).padStart(20, "0")}`;
|
|
2504
|
+
}
|
|
2505
|
+
/** A patient-address id for seeded addresses that omit one. */
|
|
2506
|
+
nextAddressId() {
|
|
2507
|
+
return `66b3${this.patients.nextSequence().toString(16).padStart(20, "0")}`;
|
|
2508
|
+
}
|
|
2509
|
+
/**
|
|
2510
|
+
* A list's rows, newest first. The incomplete and submitted lists are per clinic location;
|
|
2511
|
+
* the archived list is per clinic (`getArchivedPrescriptionsInClinic`).
|
|
2512
|
+
*/
|
|
2513
|
+
list(list, location) {
|
|
2514
|
+
return this.prescriptions.list({
|
|
2515
|
+
where: (row) => row.list === list && (list === "archived" ? row.clinicId === location.clinicId : row.clinicLocationId === location.id)
|
|
2516
|
+
}).map((row) => row.value);
|
|
2517
|
+
}
|
|
2518
|
+
};
|
|
2519
|
+
|
|
2520
|
+
// src/statuses.ts
|
|
2521
|
+
var DRAFT_STATUS = "Provider Signature Needed";
|
|
2522
|
+
var CANONICAL = {
|
|
2523
|
+
"provider signature needed": { status: "Provider Signature Needed", list: "incomplete" },
|
|
2524
|
+
"signature needed": { status: "Signature Needed", list: "incomplete" },
|
|
2525
|
+
"new formula pending": { status: "New Formula Pending", list: "incomplete" },
|
|
2526
|
+
received: { status: "Received", list: "submitted" },
|
|
2527
|
+
"order received": { status: "Order Received", list: "submitted" },
|
|
2528
|
+
"in process": { status: "In Process", list: "submitted" },
|
|
2529
|
+
"order in process": { status: "Order In Process", list: "submitted" },
|
|
2530
|
+
"prescriptions in process": { status: "Prescriptions In Process", list: "submitted" },
|
|
2531
|
+
"on hold": { status: "On Hold", list: "submitted" },
|
|
2532
|
+
"order on hold": { status: "Order On Hold", list: "submitted" },
|
|
2533
|
+
completed: { status: "Completed", list: "submitted" },
|
|
2534
|
+
"order complete": { status: "Order Complete", list: "submitted" },
|
|
2535
|
+
"order completed": { status: "Order Completed", list: "submitted" },
|
|
2536
|
+
cancelled: { status: "Cancelled", list: "archived" },
|
|
2537
|
+
"order cancelled": { status: "Order Cancelled", list: "archived" },
|
|
2538
|
+
archived: { status: "Archived", list: "archived" }
|
|
2539
|
+
};
|
|
2540
|
+
var resolveStatus = (to) => CANONICAL[to.trim().toLowerCase()] ?? { status: to.trim(), list: "submitted" };
|
|
2541
|
+
var isCompleted = (status) => /complete/i.test(status);
|
|
2542
|
+
var isActive = (list) => list !== "archived";
|
|
2543
|
+
|
|
2544
|
+
// src/runtime.ts
|
|
2545
|
+
var AUTHORIZED_OPERATIONS = supportedOperationIds.filter((id) => id !== "Authenticate");
|
|
2546
|
+
var everyAuthorized = (rule) => AUTHORIZED_OPERATIONS.map((operationId) => ({ operationId, ...rule }));
|
|
2547
|
+
var VPI_PRESETS = {
|
|
2548
|
+
token_expired: {
|
|
2549
|
+
description: 'Authorized calls answer 401 "jwt expired" before exp; with count 1 our client re-authenticates once and the retry succeeds',
|
|
2550
|
+
rules: everyAuthorized({ status: 401, body: { message: "jwt expired" } })
|
|
2551
|
+
},
|
|
2552
|
+
unauthorized_twice: {
|
|
2553
|
+
description: "Authorized calls answer 401 twice: the single re-auth retry fails too (VpiApiHttpError 401)",
|
|
2554
|
+
rules: everyAuthorized({ status: 401, body: { message: "Unauthorized" }, count: 2 })
|
|
2555
|
+
},
|
|
2556
|
+
auth_rejected: {
|
|
2557
|
+
description: "POST /accounts/authenticate answers 401 (bad credentials)",
|
|
2558
|
+
rules: [
|
|
2559
|
+
{
|
|
2560
|
+
operationId: "Authenticate",
|
|
2561
|
+
status: 401,
|
|
2562
|
+
body: { message: "Email or password is incorrect" }
|
|
2563
|
+
}
|
|
2564
|
+
]
|
|
2565
|
+
},
|
|
2566
|
+
server_error: {
|
|
2567
|
+
description: "Every call answers 500",
|
|
2568
|
+
rules: [{ status: 500, body: { message: "Internal Server Error" } }]
|
|
2569
|
+
},
|
|
2570
|
+
duplicate_prescription: {
|
|
2571
|
+
description: "checkProviderSignatureNeededDuplicate reports isDuplicate: true",
|
|
2572
|
+
rules: [
|
|
2573
|
+
{ operationId: "CheckProviderSignatureNeededDuplicate", effect: "duplicate_prescription" }
|
|
2574
|
+
]
|
|
2575
|
+
},
|
|
2576
|
+
save_ambiguous_409: {
|
|
2577
|
+
description: "saveNewPrescription saves the draft, then answers 409: the draft state is unknown (needs_review)",
|
|
2578
|
+
rules: [{ operationId: "SaveNewPrescription", effect: "save_ambiguous_409" }]
|
|
2579
|
+
},
|
|
2580
|
+
save_rate_limited: {
|
|
2581
|
+
description: "saveNewPrescription answers 429 without saving (ambiguous: needs_review)",
|
|
2582
|
+
rules: [
|
|
2583
|
+
{ operationId: "SaveNewPrescription", status: 429, body: { message: "Too Many Requests" } }
|
|
2584
|
+
]
|
|
2585
|
+
},
|
|
2586
|
+
save_400: {
|
|
2587
|
+
description: "saveNewPrescription answers 400 without saving (definitive: retry via the browser agent)",
|
|
2588
|
+
rules: [{ operationId: "SaveNewPrescription", status: 400, body: { message: "Bad Request" } }]
|
|
2589
|
+
},
|
|
2590
|
+
response_drift: {
|
|
2591
|
+
description: "Taxonomy answers categories as a string and product details unitPrice as a string: our zod parse fails closed",
|
|
2592
|
+
rules: [
|
|
2593
|
+
{ operationId: "GetAllFamiliesAndCategories", effect: "response_drift" },
|
|
2594
|
+
{ operationId: "GetProductDetailsByProductId", effect: "response_drift" }
|
|
2595
|
+
]
|
|
2596
|
+
}
|
|
2597
|
+
};
|
|
2598
|
+
var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2599
|
+
var adminError3 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
|
|
2600
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2601
|
+
var isString = (value) => typeof value === "string" && value.trim().length > 0;
|
|
2602
|
+
var ENVELOPES = [
|
|
2603
|
+
"vendor",
|
|
2604
|
+
"array",
|
|
2605
|
+
"prescriptions",
|
|
2606
|
+
"message",
|
|
2607
|
+
"message.prescriptions"
|
|
2608
|
+
];
|
|
2609
|
+
var LISTS = ["incomplete", "submitted", "archived"];
|
|
2610
|
+
var parsePatient = (body) => {
|
|
2611
|
+
if (!isRecord4(body)) return "expected a JSON object";
|
|
2612
|
+
for (const key of ["firstName", "lastName", "dateOfBirth"]) {
|
|
2613
|
+
if (!isString(body[key])) return `${key}: non-empty string`;
|
|
2614
|
+
}
|
|
2615
|
+
const addresses = body.addresses ?? [];
|
|
2616
|
+
if (!Array.isArray(addresses)) return "addresses: [{addressLine1, city, state, zipcode}]";
|
|
2617
|
+
for (const a of addresses) {
|
|
2618
|
+
if (!isRecord4(a) || !["addressLine1", "city", "state", "zipcode"].every((k) => isString(a[k])))
|
|
2619
|
+
return "addresses: [{addressLine1, addressLine2?, city, state, zipcode}]";
|
|
2620
|
+
}
|
|
2621
|
+
const optional = (key) => typeof body[key] === "string" || body[key] === null ? { [key]: body[key] } : {};
|
|
2622
|
+
return {
|
|
2623
|
+
firstName: body.firstName,
|
|
2624
|
+
lastName: body.lastName,
|
|
2625
|
+
dateOfBirth: body.dateOfBirth,
|
|
2626
|
+
...optional("id"),
|
|
2627
|
+
...optional("clinicId"),
|
|
2628
|
+
...optional("email"),
|
|
2629
|
+
...optional("phoneNumber"),
|
|
2630
|
+
...optional("cellPhone"),
|
|
2631
|
+
addresses: addresses.map((a) => ({
|
|
2632
|
+
addressLine1: a.addressLine1,
|
|
2633
|
+
city: a.city,
|
|
2634
|
+
state: a.state,
|
|
2635
|
+
zipcode: a.zipcode,
|
|
2636
|
+
...typeof a.id === "string" ? { id: a.id } : {},
|
|
2637
|
+
...typeof a.addressLine2 === "string" || a.addressLine2 === null ? { addressLine2: a.addressLine2 } : {}
|
|
2638
|
+
}))
|
|
2639
|
+
};
|
|
2640
|
+
};
|
|
2641
|
+
var adminRoutes = (runtime) => ({
|
|
2642
|
+
"GET /prescriptions": ({ namespace }) => json3(200, { prescriptions: runtime.instance(namespace).prescriptions() }),
|
|
2643
|
+
"POST /prescriptions/:id/transition": ({ params, body, namespace }) => {
|
|
2644
|
+
if (!isRecord4(body) || !isString(body.to)) {
|
|
2645
|
+
return adminError3(400, 'expected {"to": "<VPI status>", "trackingNumber"?, "list"?}');
|
|
2646
|
+
}
|
|
2647
|
+
if (body.list !== void 0 && !LISTS.includes(body.list)) {
|
|
2648
|
+
return adminError3(400, `list: one of ${LISTS.join(", ")}`);
|
|
2649
|
+
}
|
|
2650
|
+
const updated = runtime.instance(namespace).transition(params.id, {
|
|
2651
|
+
to: body.to,
|
|
2652
|
+
...typeof body.trackingNumber === "string" ? { trackingNumber: body.trackingNumber } : {},
|
|
2653
|
+
...body.list !== void 0 ? { list: body.list } : {}
|
|
2654
|
+
});
|
|
2655
|
+
return updated ? json3(200, updated) : adminError3(404, `no prescription ${params.id}`);
|
|
2656
|
+
},
|
|
2657
|
+
"GET /patients": ({ namespace }) => json3(200, {
|
|
2658
|
+
patients: runtime.instance(namespace).state.patients.list({ order: "oldest" }).map((row) => row.value)
|
|
2659
|
+
}),
|
|
2660
|
+
"POST /patients": ({ body, namespace }) => {
|
|
2661
|
+
const parsed = parsePatient(body);
|
|
2662
|
+
if (typeof parsed === "string") return adminError3(400, parsed);
|
|
2663
|
+
return json3(201, runtime.instance(namespace).addPatient(parsed));
|
|
2664
|
+
},
|
|
2665
|
+
"GET /catalog": ({ namespace }) => {
|
|
2666
|
+
const state = runtime.instance(namespace).state;
|
|
2667
|
+
return json3(200, {
|
|
2668
|
+
products: state.products.list({ order: "oldest" }).map((row) => row.value),
|
|
2669
|
+
providers: state.providers.list({ order: "oldest" }).map((row) => row.value),
|
|
2670
|
+
clinicLocations: state.locations.list({ order: "oldest" }).map((row) => row.value)
|
|
2671
|
+
});
|
|
2672
|
+
},
|
|
2673
|
+
"GET /settings": ({ namespace }) => json3(200, runtime.instance(namespace).state.current()),
|
|
2674
|
+
"PUT /settings": ({ body, namespace }) => {
|
|
2675
|
+
if (!isRecord4(body)) return adminError3(400, "expected a JSON object");
|
|
2676
|
+
const patch = {};
|
|
2677
|
+
if (body.tokenTtlSeconds !== void 0) {
|
|
2678
|
+
if (typeof body.tokenTtlSeconds !== "number" || body.tokenTtlSeconds <= 0)
|
|
2679
|
+
return adminError3(400, "tokenTtlSeconds: positive number");
|
|
2680
|
+
patch.tokenTtlSeconds = body.tokenTtlSeconds;
|
|
2681
|
+
}
|
|
2682
|
+
if (body.accounts !== void 0) {
|
|
2683
|
+
if (!Array.isArray(body.accounts) || !body.accounts.every(isRecord4))
|
|
2684
|
+
return adminError3(400, "accounts: [{email, password, id}]");
|
|
2685
|
+
patch.accounts = body.accounts.map(
|
|
2686
|
+
(a) => ({
|
|
2687
|
+
email: String(a.email),
|
|
2688
|
+
password: String(a.password),
|
|
2689
|
+
id: String(a.id ?? "")
|
|
2690
|
+
})
|
|
2691
|
+
);
|
|
2692
|
+
}
|
|
2693
|
+
if (body.statusEnvelope !== void 0) {
|
|
2694
|
+
if (!ENVELOPES.includes(body.statusEnvelope))
|
|
2695
|
+
return adminError3(400, `statusEnvelope: one of ${ENVELOPES.join(", ")}`);
|
|
2696
|
+
patch.statusEnvelope = body.statusEnvelope;
|
|
2697
|
+
}
|
|
2698
|
+
if (body.isProviderSignatureNeeded !== void 0) {
|
|
2699
|
+
if (typeof body.isProviderSignatureNeeded !== "boolean")
|
|
2700
|
+
return adminError3(400, "isProviderSignatureNeeded: boolean");
|
|
2701
|
+
patch.isProviderSignatureNeeded = body.isProviderSignatureNeeded;
|
|
2702
|
+
}
|
|
2703
|
+
return json3(200, runtime.instance(namespace).state.update(patch));
|
|
2704
|
+
}
|
|
2705
|
+
});
|
|
2706
|
+
var createRuntime2 = (options = {}) => createRuntime({
|
|
2707
|
+
name: VPI_NAMESPACE,
|
|
2708
|
+
document,
|
|
2709
|
+
...options.sqlite ? { sqlite: options.sqlite } : {},
|
|
2710
|
+
...options.clock ? { clock: options.clock } : {},
|
|
2711
|
+
...options.seed !== void 0 ? { seed: options.seed } : {},
|
|
2712
|
+
...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
|
|
2713
|
+
...options.onLog ? { onLog: options.onLog } : {},
|
|
2714
|
+
credential: tokenCredential,
|
|
2715
|
+
presets: VPI_PRESETS,
|
|
2716
|
+
create: ({ sqlite, namespace, clock }) => new VpiAPI({
|
|
2717
|
+
sqlite,
|
|
2718
|
+
namespace,
|
|
2719
|
+
now: clock.now,
|
|
2720
|
+
...options.data ? { seed: options.data } : {},
|
|
2721
|
+
...options.settings ? { settings: options.settings } : {}
|
|
2722
|
+
}),
|
|
2723
|
+
admin: adminRoutes
|
|
2724
|
+
});
|
|
2725
|
+
|
|
2726
|
+
// src/index.ts
|
|
2727
|
+
var VPI_NAMESPACE = "vpi";
|
|
2728
|
+
var base64url = (value) => toBase64(new TextEncoder().encode(value)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
2729
|
+
var fromBase64url = (value) => {
|
|
2730
|
+
try {
|
|
2731
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(
|
|
2732
|
+
fromBase64(value.replace(/-/g, "+").replace(/_/g, "/"))
|
|
2733
|
+
);
|
|
2734
|
+
} catch {
|
|
2735
|
+
return void 0;
|
|
2736
|
+
}
|
|
2737
|
+
};
|
|
2738
|
+
var JWT_HEADER = base64url(JSON.stringify({ alg: "HS256", typ: "JWT" }));
|
|
2739
|
+
var signJwt = (unsigned) => opaqueToken(`vpi-jwt:${unsigned}`, 43);
|
|
2740
|
+
var issueJwt = (claims) => {
|
|
2741
|
+
const unsigned = `${JWT_HEADER}.${base64url(JSON.stringify(claims))}`;
|
|
2742
|
+
return `${unsigned}.${signJwt(unsigned)}`;
|
|
2743
|
+
};
|
|
2744
|
+
var readClaims = (token) => {
|
|
2745
|
+
const [header, payload, signature] = token.split(".");
|
|
2746
|
+
if (!header || !payload || !signature) return void 0;
|
|
2747
|
+
if (signature !== signJwt(`${header}.${payload}`)) return void 0;
|
|
2748
|
+
const json4 = fromBase64url(payload);
|
|
2749
|
+
if (!json4) return void 0;
|
|
2750
|
+
try {
|
|
2751
|
+
const claims = JSON.parse(json4);
|
|
2752
|
+
return typeof claims.exp === "number" && typeof claims.email === "string" ? claims : void 0;
|
|
2753
|
+
} catch {
|
|
2754
|
+
return void 0;
|
|
2755
|
+
}
|
|
2756
|
+
};
|
|
2757
|
+
var tokenCredential = (request) => {
|
|
2758
|
+
const token = bearerToken(request);
|
|
2759
|
+
if (!token) return void 0;
|
|
2760
|
+
const payload = token.split(".")[1];
|
|
2761
|
+
if (!payload) return void 0;
|
|
2762
|
+
const json4 = fromBase64url(payload);
|
|
2763
|
+
if (!json4) return void 0;
|
|
2764
|
+
try {
|
|
2765
|
+
const email = JSON.parse(json4).email;
|
|
2766
|
+
return typeof email === "string" ? email : void 0;
|
|
2767
|
+
} catch {
|
|
2768
|
+
return void 0;
|
|
2769
|
+
}
|
|
2770
|
+
};
|
|
2771
|
+
var error = (status, message, errors) => jsonRes(status, errors ? { message, errors } : { message });
|
|
2772
|
+
var notFound = (what) => {
|
|
2773
|
+
throw new HttpError(404, { message: `${what} not found` });
|
|
2774
|
+
};
|
|
2775
|
+
var record = (context) => {
|
|
2776
|
+
const issues = bodyIssues(context);
|
|
2777
|
+
if (issues.length > 0) {
|
|
2778
|
+
throw new HttpError(400, { message: "Validation failed", errors: issues });
|
|
2779
|
+
}
|
|
2780
|
+
return context.body.kind === "json" ? context.body.value : {};
|
|
2781
|
+
};
|
|
2782
|
+
var round2 = (value) => Math.round(value * 100) / 100;
|
|
2783
|
+
var patientBody = (patient) => ({
|
|
2784
|
+
id: patient.id,
|
|
2785
|
+
firstName: patient.firstName,
|
|
2786
|
+
lastName: patient.lastName,
|
|
2787
|
+
dateOfBirth: patient.dateOfBirth,
|
|
2788
|
+
email: patient.email,
|
|
2789
|
+
phoneNumber: patient.phoneNumber,
|
|
2790
|
+
cellPhone: patient.cellPhone
|
|
2791
|
+
});
|
|
2792
|
+
var productSummary = (p) => ({
|
|
2793
|
+
id: p.id,
|
|
2794
|
+
name: p.name,
|
|
2795
|
+
unitPrice: p.unitPrice,
|
|
2796
|
+
productId: p.productId,
|
|
2797
|
+
productSize: p.productSize,
|
|
2798
|
+
medicalAccessories: p.medicalAccessories,
|
|
2799
|
+
coldShipped: p.coldShipped,
|
|
2800
|
+
controlledSubstance: p.controlledSubstance,
|
|
2801
|
+
dispenseType: p.dispenseType,
|
|
2802
|
+
productType: p.productType,
|
|
2803
|
+
isReasonForCompoundedMedicationNeeded: p.isReasonForCompoundedMedicationNeeded
|
|
2804
|
+
});
|
|
2805
|
+
var productDetails = (p) => ({
|
|
2806
|
+
id: p.id,
|
|
2807
|
+
productId: p.productId,
|
|
2808
|
+
name: p.name,
|
|
2809
|
+
unitPrice: p.unitPrice,
|
|
2810
|
+
family: p.family,
|
|
2811
|
+
subCategory1: p.subCategory1,
|
|
2812
|
+
subCategory2: p.subCategory2,
|
|
2813
|
+
commonName: p.commonName,
|
|
2814
|
+
sigOptions: p.sigOptions,
|
|
2815
|
+
productSize: p.productSize,
|
|
2816
|
+
medicalAccessories: p.medicalAccessories,
|
|
2817
|
+
coldShipped: p.coldShipped,
|
|
2818
|
+
controlledSubstance: p.controlledSubstance,
|
|
2819
|
+
dispenseType: p.dispenseType,
|
|
2820
|
+
reasonForCompoundedMedication: p.reasonForCompoundedMedication,
|
|
2821
|
+
isReasonForCompoundedMedicationNeeded: p.isReasonForCompoundedMedicationNeeded,
|
|
2822
|
+
productType: p.productType,
|
|
2823
|
+
patientPayAmount: p.patientPayAmount,
|
|
2824
|
+
ndc: p.ndc,
|
|
2825
|
+
isActive: true,
|
|
2826
|
+
isAvailable: true
|
|
2827
|
+
});
|
|
2828
|
+
var VpiAPI = class {
|
|
2829
|
+
app;
|
|
2830
|
+
sqlite;
|
|
2831
|
+
state;
|
|
2832
|
+
service;
|
|
2833
|
+
now;
|
|
2834
|
+
constructor(options = {}) {
|
|
2835
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
2836
|
+
const namespace = options.namespace ?? VPI_NAMESPACE;
|
|
2837
|
+
this.now = options.now ?? (() => Date.now());
|
|
2838
|
+
this.state = new VpiState(sqlite, namespace, {
|
|
2839
|
+
data: options.seed ?? {},
|
|
2840
|
+
settings: options.settings ?? {}
|
|
2841
|
+
});
|
|
2842
|
+
const handlers = defineOperations({
|
|
2843
|
+
Authenticate: (context) => this.authenticate(context),
|
|
2844
|
+
GetAllFamiliesAndCategories: (context) => this.taxonomy(context),
|
|
2845
|
+
GetProductsByCategory: (context) => this.productsByCategory(context),
|
|
2846
|
+
GetProductDetailsByProductId: (context) => this.productDetails(context),
|
|
2847
|
+
GetProductDiscountByProductIds: (context) => this.discounts(context),
|
|
2848
|
+
CalculateDaySupply: (context) => this.daySupply(context),
|
|
2849
|
+
GetShippingStates: () => jsonRes(200, { data: [{ states: SHIPPING_STATES }] }),
|
|
2850
|
+
GetShippingRate: (context) => this.shippingRate(context),
|
|
2851
|
+
CheckProviderSignatureNeededDuplicate: (context) => this.duplicateCheck(context),
|
|
2852
|
+
SaveNewPrescription: (context) => this.savePrescription(context),
|
|
2853
|
+
GetPatientByPatientId: (context) => {
|
|
2854
|
+
const body = record(context);
|
|
2855
|
+
const patient = this.patient(String(body.patientId));
|
|
2856
|
+
return annotateResponse(jsonRes(200, patientBody(patient)), {
|
|
2857
|
+
ids: { patientId: patient.id }
|
|
2858
|
+
});
|
|
2859
|
+
},
|
|
2860
|
+
GetPatientAddressesByPatientId: (context) => {
|
|
2861
|
+
const body = record(context);
|
|
2862
|
+
const patient = this.patient(String(body.patientId));
|
|
2863
|
+
return annotateResponse(jsonRes(200, { addresses: patient.addresses }), {
|
|
2864
|
+
ids: { patientId: patient.id }
|
|
2865
|
+
});
|
|
2866
|
+
},
|
|
2867
|
+
GetPatientsInClinic: (context) => this.roster(context),
|
|
2868
|
+
GetAllProvidersByClinicLocationId: (context) => {
|
|
2869
|
+
const body = record(context);
|
|
2870
|
+
const location = this.location(String(body.clinicLocationId));
|
|
2871
|
+
if (location.clinicId !== body.clinicId) notFound("Clinic location");
|
|
2872
|
+
return jsonRes(
|
|
2873
|
+
200,
|
|
2874
|
+
this.state.providers.list({ order: "oldest", where: (p) => p.clinicLocationId === location.id }).map(({ value: p }) => ({
|
|
2875
|
+
id: p.id,
|
|
2876
|
+
firstName: p.firstName,
|
|
2877
|
+
lastName: p.lastName,
|
|
2878
|
+
npi: p.npi,
|
|
2879
|
+
deaInfo: [],
|
|
2880
|
+
providerLicenses: [],
|
|
2881
|
+
allowExostar: false,
|
|
2882
|
+
isSuperUserSameAsProvider: false
|
|
2883
|
+
}))
|
|
2884
|
+
);
|
|
2885
|
+
},
|
|
2886
|
+
GetClinicLocationByClinicLocationId: (context) => {
|
|
2887
|
+
const body = record(context);
|
|
2888
|
+
return jsonRes(200, this.location(String(body.clinicLocationId)));
|
|
2889
|
+
},
|
|
2890
|
+
GetIncompleteSavedPrescriptionsInClinicLocation: (context) => this.prescriptionPage(context, "incomplete"),
|
|
2891
|
+
GetSubmittedPrescriptionsInClinicLocation: (context) => this.prescriptionPage(context, "submitted"),
|
|
2892
|
+
GetArchivedPrescriptionsInClinic: (context) => this.prescriptionPage(context, "archived")
|
|
2893
|
+
});
|
|
2894
|
+
this.service = createService({
|
|
2895
|
+
document,
|
|
2896
|
+
handlers,
|
|
2897
|
+
sqlite,
|
|
2898
|
+
namespace,
|
|
2899
|
+
now: this.now,
|
|
2900
|
+
notFound: () => jsonRes(404, { message: "Cannot find the requested route" }),
|
|
2901
|
+
onError: (thrown) => {
|
|
2902
|
+
if (thrown instanceof HttpError) return thrown.toResponse();
|
|
2903
|
+
throw thrown;
|
|
2904
|
+
},
|
|
2905
|
+
before: (context) => {
|
|
2906
|
+
if (context.operation.operationId === "Authenticate") return void 0;
|
|
2907
|
+
const token = bearerToken(context.request);
|
|
2908
|
+
if (!token) return error(401, "Unauthorized");
|
|
2909
|
+
const claims = readClaims(token);
|
|
2910
|
+
if (!claims) return error(401, "Unauthorized");
|
|
2911
|
+
if (this.now() / 1e3 >= claims.exp) return error(401, "jwt expired");
|
|
2912
|
+
return void 0;
|
|
2913
|
+
}
|
|
2914
|
+
});
|
|
2915
|
+
this.app = this.service.app;
|
|
2916
|
+
this.sqlite = this.service.sqlite;
|
|
2917
|
+
}
|
|
2918
|
+
fetch(request) {
|
|
2919
|
+
return this.service.fetch(request);
|
|
2920
|
+
}
|
|
2921
|
+
async reset() {
|
|
2922
|
+
await this.service.reset();
|
|
2923
|
+
this.state.ensureSeeded();
|
|
2924
|
+
}
|
|
2925
|
+
iso() {
|
|
2926
|
+
return new Date(this.now()).toISOString();
|
|
2927
|
+
}
|
|
2928
|
+
authenticate(context) {
|
|
2929
|
+
const body = record(context);
|
|
2930
|
+
const email = String(body.email).trim();
|
|
2931
|
+
const settings = this.state.current();
|
|
2932
|
+
let userId = DEFAULT_USER_ID;
|
|
2933
|
+
if (settings.accounts.length > 0) {
|
|
2934
|
+
const account = settings.accounts.find(
|
|
2935
|
+
(a) => a.email.toLowerCase() === email.toLowerCase() && a.password === body.password
|
|
2936
|
+
);
|
|
2937
|
+
if (!account) return error(401, "Email or password is incorrect");
|
|
2938
|
+
userId = account.id;
|
|
2939
|
+
}
|
|
2940
|
+
if (body.isPatientLogin === true) return error(401, "Email or password is incorrect");
|
|
2941
|
+
const iat = Math.floor(this.now() / 1e3);
|
|
2942
|
+
const jwtToken = issueJwt({ sub: userId, email, iat, exp: iat + settings.tokenTtlSeconds });
|
|
2943
|
+
return jsonRes(200, {
|
|
2944
|
+
id: userId,
|
|
2945
|
+
jwtToken,
|
|
2946
|
+
refreshToken: opaqueToken(`vpi-refresh:${jwtToken}`, 80)
|
|
2947
|
+
});
|
|
2948
|
+
}
|
|
2949
|
+
product(id) {
|
|
2950
|
+
return this.state.products.get(id) ?? notFound("Product");
|
|
2951
|
+
}
|
|
2952
|
+
patient(id) {
|
|
2953
|
+
return this.state.patients.get(id) ?? notFound("Patient");
|
|
2954
|
+
}
|
|
2955
|
+
location(id) {
|
|
2956
|
+
return this.state.locations.get(id) ?? notFound("Clinic location");
|
|
2957
|
+
}
|
|
2958
|
+
clinic(id) {
|
|
2959
|
+
if (!this.state.hasClinic(id)) notFound("Clinic");
|
|
2960
|
+
}
|
|
2961
|
+
taxonomy(context) {
|
|
2962
|
+
const families = /* @__PURE__ */ new Map();
|
|
2963
|
+
for (const { value: p } of this.state.products.list({ order: "oldest" })) {
|
|
2964
|
+
const categories = families.get(p.family) ?? [];
|
|
2965
|
+
if (!categories.includes(p.subCategory1)) categories.push(p.subCategory1);
|
|
2966
|
+
families.set(p.family, categories);
|
|
2967
|
+
}
|
|
2968
|
+
const drift = faultEffect(context.request, "response_drift") !== void 0;
|
|
2969
|
+
return jsonRes(
|
|
2970
|
+
200,
|
|
2971
|
+
[...families].map(([family, categories]) => ({
|
|
2972
|
+
family,
|
|
2973
|
+
categories: drift ? categories.join(",") : categories
|
|
2974
|
+
}))
|
|
2975
|
+
);
|
|
2976
|
+
}
|
|
2977
|
+
productsByCategory(context) {
|
|
2978
|
+
const body = record(context);
|
|
2979
|
+
const groups = /* @__PURE__ */ new Map();
|
|
2980
|
+
for (const { value: p } of this.state.products.list({ order: "oldest" })) {
|
|
2981
|
+
if (p.family !== body.category || p.subCategory1 !== body.subCategory1) continue;
|
|
2982
|
+
const byName = groups.get(p.subCategory2) ?? /* @__PURE__ */ new Map();
|
|
2983
|
+
byName.set(p.commonName, [...byName.get(p.commonName) ?? [], p]);
|
|
2984
|
+
groups.set(p.subCategory2, byName);
|
|
2985
|
+
}
|
|
2986
|
+
return jsonRes(
|
|
2987
|
+
200,
|
|
2988
|
+
[...groups].map(([subCategory2, byName]) => ({
|
|
2989
|
+
subCategory2_item: subCategory2,
|
|
2990
|
+
commonNames: [...byName].map(([commonName, products]) => ({
|
|
2991
|
+
commonName,
|
|
2992
|
+
products: products.map(productSummary)
|
|
2993
|
+
}))
|
|
2994
|
+
}))
|
|
2995
|
+
);
|
|
2996
|
+
}
|
|
2997
|
+
productDetails(context) {
|
|
2998
|
+
const product = this.product(context.params.productId ?? "");
|
|
2999
|
+
const body = productDetails(product);
|
|
3000
|
+
if (faultEffect(context.request, "response_drift") !== void 0) {
|
|
3001
|
+
return jsonRes(200, { ...body, unitPrice: String(body.unitPrice) });
|
|
3002
|
+
}
|
|
3003
|
+
return jsonRes(200, body);
|
|
3004
|
+
}
|
|
3005
|
+
discounts(context) {
|
|
3006
|
+
const body = record(context);
|
|
3007
|
+
this.clinic(String(body.clinicId));
|
|
3008
|
+
const rows = body.productIds.map((id) => this.state.products.get(id)).filter((p) => p !== void 0).map((p) => ({
|
|
3009
|
+
id: p.id,
|
|
3010
|
+
productId: p.productId,
|
|
3011
|
+
discountedPrice: round2(p.unitPrice * (1 - p.discountedPercentage / 100)),
|
|
3012
|
+
unitPrice: p.unitPrice,
|
|
3013
|
+
discountedPercentage: p.discountedPercentage,
|
|
3014
|
+
controlledSubstance: p.controlledSubstance
|
|
3015
|
+
}));
|
|
3016
|
+
return jsonRes(200, rows);
|
|
3017
|
+
}
|
|
3018
|
+
daySupply(context) {
|
|
3019
|
+
const body = record(context);
|
|
3020
|
+
const product = this.product(String(body.productId));
|
|
3021
|
+
const quantity = Number(body.quantity);
|
|
3022
|
+
const perUnit = /ea$/i.test(product.productSize);
|
|
3023
|
+
const daySupply = perUnit ? Math.max(1, Math.round(quantity)) : 30;
|
|
3024
|
+
return jsonRes(200, {
|
|
3025
|
+
daySupply,
|
|
3026
|
+
daySupplyReason: perUnit ? "Calculated from quantity (1 per day)" : "Default 30-day supply"
|
|
3027
|
+
});
|
|
3028
|
+
}
|
|
3029
|
+
shippingRate(context) {
|
|
3030
|
+
const body = record(context);
|
|
3031
|
+
this.clinic(String(body.clinicId));
|
|
3032
|
+
this.location(String(body.clinicLocationId));
|
|
3033
|
+
this.patient(String(body.patientId));
|
|
3034
|
+
const products = body.productIds.map((id) => this.product(id));
|
|
3035
|
+
const code = String(body.shippingState).toUpperCase();
|
|
3036
|
+
const state = SHIPPING_STATES.find((s) => STATE_CODES[s.name] === code);
|
|
3037
|
+
if (!state) return error(400, `VPI does not ship to ${code}`);
|
|
3038
|
+
if (products.some((p) => p.productType === "S") && !state.sterile) {
|
|
3039
|
+
return error(400, `VPI does not ship sterile products to ${state.name}`);
|
|
3040
|
+
}
|
|
3041
|
+
const cold = products.some((p) => p.coldShipped === "1");
|
|
3042
|
+
const rush = body.isRushOrder === true;
|
|
3043
|
+
return jsonRes(200, {
|
|
3044
|
+
shippingMethod: cold ? "FedEx Priority Overnight" : "UPS Ground",
|
|
3045
|
+
rushOrderCost: rush ? 35 : 0,
|
|
3046
|
+
rushOrderMethod: rush ? "FedEx Standard Overnight" : "",
|
|
3047
|
+
isSignatureRequired: products.some((p) => p.productType === "S")
|
|
3048
|
+
});
|
|
3049
|
+
}
|
|
3050
|
+
duplicateCheck(context) {
|
|
3051
|
+
const body = record(context);
|
|
3052
|
+
const patients = body.patientIds;
|
|
3053
|
+
const products = body.productIds;
|
|
3054
|
+
const duplicate = faultEffect(context.request, "duplicate_prescription") !== void 0 || this.state.prescriptions.list().some(
|
|
3055
|
+
({ value: rx }) => isActive(rx.list) && patients.includes(rx.patientId) && rx.productIds.some((id) => products.includes(id))
|
|
3056
|
+
);
|
|
3057
|
+
return jsonRes(200, {
|
|
3058
|
+
isDuplicate: duplicate,
|
|
3059
|
+
isProviderSignatureNeeded: this.state.current().isProviderSignatureNeeded
|
|
3060
|
+
});
|
|
3061
|
+
}
|
|
3062
|
+
savePrescription(context) {
|
|
3063
|
+
const body = record(context);
|
|
3064
|
+
const location = this.location(String(body.clinicLocationId));
|
|
3065
|
+
if (location.clinicId !== body.clinicId) notFound("Clinic location");
|
|
3066
|
+
const provider = this.state.providers.get(String(body.providerId));
|
|
3067
|
+
if (!provider || provider.clinicLocationId !== location.id) notFound("Provider");
|
|
3068
|
+
const patientId = body.patientIds[0];
|
|
3069
|
+
const patient = this.patient(patientId);
|
|
3070
|
+
if (patient.clinicId !== location.clinicId) notFound("Patient");
|
|
3071
|
+
const lines = body.products;
|
|
3072
|
+
for (const line of lines) {
|
|
3073
|
+
const product = this.product(line.id);
|
|
3074
|
+
if (product.productId !== line.productId) {
|
|
3075
|
+
return error(400, `Product ${line.id} does not match product code ${line.productId}`);
|
|
3076
|
+
}
|
|
3077
|
+
if (product.controlledSubstance === "1") {
|
|
3078
|
+
return error(400, "Controlled substances cannot be prescribed through this endpoint");
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
const now = this.iso();
|
|
3082
|
+
const created = {
|
|
3083
|
+
prescriptionId: this.state.nextPrescriptionId(),
|
|
3084
|
+
clinicId: location.clinicId,
|
|
3085
|
+
clinicLocationId: location.id,
|
|
3086
|
+
patientId,
|
|
3087
|
+
providerId: provider?.id ?? "",
|
|
3088
|
+
productIds: lines.map((line) => line.id),
|
|
3089
|
+
prescriptionStatus: DRAFT_STATUS,
|
|
3090
|
+
list: "incomplete",
|
|
3091
|
+
trackingNumber: null,
|
|
3092
|
+
createdAt: now,
|
|
3093
|
+
updatedAt: now
|
|
3094
|
+
};
|
|
3095
|
+
this.state.prescriptions.insert(created.prescriptionId, created);
|
|
3096
|
+
const ids = { prescriptionId: created.prescriptionId, patientId };
|
|
3097
|
+
if (faultEffect(context.request, "save_ambiguous_409") !== void 0) {
|
|
3098
|
+
return annotateResponse(error(409, "Request conflicted with a concurrent save"), { ids });
|
|
3099
|
+
}
|
|
3100
|
+
return annotateResponse(
|
|
3101
|
+
jsonRes(200, {
|
|
3102
|
+
message: "Prescription saved successfully",
|
|
3103
|
+
prescriptionId: created.prescriptionId,
|
|
3104
|
+
isRefillRequest: false,
|
|
3105
|
+
refillFromPrescriptionId: null
|
|
3106
|
+
}),
|
|
3107
|
+
{ ids }
|
|
3108
|
+
);
|
|
3109
|
+
}
|
|
3110
|
+
roster(context) {
|
|
3111
|
+
const body = record(context);
|
|
3112
|
+
this.clinic(String(body.clinicId));
|
|
3113
|
+
const limit = Number(body.limit);
|
|
3114
|
+
const page = Number(body.currentPage);
|
|
3115
|
+
const all = this.state.patients.list({ order: "oldest", where: (p) => p.clinicId === body.clinicId }).map((row) => row.value);
|
|
3116
|
+
const rows = all.slice((page - 1) * limit, page * limit);
|
|
3117
|
+
return jsonRes(200, {
|
|
3118
|
+
pagination: {
|
|
3119
|
+
hasNextPage: page * limit < all.length,
|
|
3120
|
+
currentPage: page,
|
|
3121
|
+
limit,
|
|
3122
|
+
totalCount: all.length
|
|
3123
|
+
},
|
|
3124
|
+
patients: rows.map(patientBody)
|
|
3125
|
+
});
|
|
3126
|
+
}
|
|
3127
|
+
prescriptionPage(context, list) {
|
|
3128
|
+
const body = record(context);
|
|
3129
|
+
const location = this.location(String(body.clinicLocationId));
|
|
3130
|
+
const limit = Number(body.limit);
|
|
3131
|
+
const page = Number(body.currentPage);
|
|
3132
|
+
const rows = this.state.list(list, location).slice((page - 1) * limit, page * limit);
|
|
3133
|
+
const envelope = this.state.current().statusEnvelope;
|
|
3134
|
+
const useId = envelope === "vendor" && list === "archived";
|
|
3135
|
+
const shaped = rows.map((rx) => ({
|
|
3136
|
+
...useId ? { id: rx.prescriptionId } : { prescriptionId: rx.prescriptionId },
|
|
3137
|
+
prescriptionStatus: rx.prescriptionStatus,
|
|
3138
|
+
trackingNumber: rx.trackingNumber,
|
|
3139
|
+
patientId: rx.patientId,
|
|
3140
|
+
createdAt: rx.createdAt
|
|
3141
|
+
}));
|
|
3142
|
+
const kind = envelope !== "vendor" ? envelope : list === "submitted" ? "message.prescriptions" : list === "archived" ? "message" : "array";
|
|
3143
|
+
const payload = kind === "array" ? shaped : kind === "prescriptions" ? { prescriptions: shaped } : kind === "message" ? { message: shaped } : { message: { prescriptions: shaped } };
|
|
3144
|
+
return jsonRes(200, payload);
|
|
3145
|
+
}
|
|
3146
|
+
/** Move a prescription to a VPI status (and its list); completion adds a tracking number. */
|
|
3147
|
+
transition(id, input) {
|
|
3148
|
+
const rx = this.state.prescriptions.get(id);
|
|
3149
|
+
if (!rx) return void 0;
|
|
3150
|
+
const resolved = resolveStatus(input.to);
|
|
3151
|
+
const next = {
|
|
3152
|
+
...rx,
|
|
3153
|
+
prescriptionStatus: resolved.status,
|
|
3154
|
+
list: input.list ?? resolved.list,
|
|
3155
|
+
trackingNumber: input.trackingNumber ?? rx.trackingNumber ?? (isCompleted(resolved.status) ? `1Z${opaqueToken(id, 16).toUpperCase()}` : null),
|
|
3156
|
+
updatedAt: this.iso()
|
|
3157
|
+
};
|
|
3158
|
+
this.state.prescriptions.update(id, next);
|
|
3159
|
+
return next;
|
|
3160
|
+
}
|
|
3161
|
+
/** Seed a clinic patient (VPI patient creation is not part of our client's contract). */
|
|
3162
|
+
addPatient(input) {
|
|
3163
|
+
const patient = {
|
|
3164
|
+
id: input.id ?? this.state.nextPatientId(),
|
|
3165
|
+
clinicId: input.clinicId ?? this.state.locations.list({ order: "oldest" })[0]?.value.clinicId ?? "",
|
|
3166
|
+
firstName: input.firstName,
|
|
3167
|
+
lastName: input.lastName,
|
|
3168
|
+
dateOfBirth: input.dateOfBirth,
|
|
3169
|
+
email: input.email ?? null,
|
|
3170
|
+
phoneNumber: input.phoneNumber ?? null,
|
|
3171
|
+
cellPhone: input.cellPhone ?? null,
|
|
3172
|
+
addresses: (input.addresses ?? []).map((a) => ({
|
|
3173
|
+
id: a.id ?? this.state.nextAddressId(),
|
|
3174
|
+
addressLine1: a.addressLine1,
|
|
3175
|
+
addressLine2: a.addressLine2 ?? null,
|
|
3176
|
+
city: a.city,
|
|
3177
|
+
state: a.state,
|
|
3178
|
+
zipcode: a.zipcode
|
|
3179
|
+
}))
|
|
3180
|
+
};
|
|
3181
|
+
this.state.patients.insert(patient.id, patient);
|
|
3182
|
+
return patient;
|
|
3183
|
+
}
|
|
3184
|
+
prescriptions() {
|
|
3185
|
+
return this.state.prescriptions.list({ order: "oldest" }).map((row) => row.value);
|
|
3186
|
+
}
|
|
3187
|
+
};
|
|
3188
|
+
|
|
3189
|
+
export {
|
|
3190
|
+
DEFAULT_USER_ID,
|
|
3191
|
+
DEFAULT_CLINIC_ID,
|
|
3192
|
+
DEFAULT_CLINIC_LOCATION_ID,
|
|
3193
|
+
DEFAULT_PROVIDER_ID,
|
|
3194
|
+
DEFAULT_PATIENT_ID,
|
|
3195
|
+
DEFAULT_PRODUCTS,
|
|
3196
|
+
DEFAULT_CLINIC_LOCATION,
|
|
3197
|
+
DEFAULT_PROVIDERS,
|
|
3198
|
+
DEFAULT_PATIENTS,
|
|
3199
|
+
SHIPPING_STATES,
|
|
3200
|
+
document,
|
|
3201
|
+
operationIds,
|
|
3202
|
+
supportedOperationIds,
|
|
3203
|
+
VPI_PRESETS,
|
|
3204
|
+
createRuntime2 as createRuntime,
|
|
3205
|
+
VPI_NAMESPACE,
|
|
3206
|
+
issueJwt,
|
|
3207
|
+
tokenCredential,
|
|
3208
|
+
VpiAPI
|
|
3209
|
+
};
|
|
3210
|
+
//# sourceMappingURL=chunk-32KSYN2C.js.map
|