@crvouga/mockingbird-service-resend 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 +159 -0
- package/dist/chunk-A4NJUMTM.js +369 -0
- package/dist/chunk-A4NJUMTM.js.map +7 -0
- package/dist/chunk-MAW2TLUJ.js +3233 -0
- package/dist/chunk-MAW2TLUJ.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +1040 -0
- package/dist/index.js +25 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1372 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +93 -0
|
@@ -0,0 +1,3233 @@
|
|
|
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 record = value;
|
|
768
|
+
const keys = Object.keys(record);
|
|
769
|
+
for (const name of s.required ?? [])
|
|
770
|
+
if (!(name in record))
|
|
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, record[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, record[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/idempotency.js
|
|
976
|
+
var inFlight = /* @__PURE__ */ new Map();
|
|
977
|
+
var IdempotencyStore = class {
|
|
978
|
+
namespace;
|
|
979
|
+
responses;
|
|
980
|
+
constructor(sqlite, namespace, name = "idempotency") {
|
|
981
|
+
this.namespace = namespace;
|
|
982
|
+
this.responses = new Collection(sqlite, namespace, name);
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* Run `handler` once per `key`. `fingerprint` identifies the request's parameters (e.g.
|
|
986
|
+
* the method, path and canonical body). Only `replayable` responses are stored (default:
|
|
987
|
+
* every status below 500, as Stripe does), so a transient failure can be retried.
|
|
988
|
+
*/
|
|
989
|
+
async run(key, fingerprint, errors, handler, replayable = (status) => status < 500) {
|
|
990
|
+
const slot = `${this.namespace}\0${key}`;
|
|
991
|
+
const stored = this.responses.get(key);
|
|
992
|
+
if (stored) {
|
|
993
|
+
if (stored.fingerprint !== fingerprint)
|
|
994
|
+
return errors.mismatch();
|
|
995
|
+
return new Response(stored.body, {
|
|
996
|
+
status: stored.status,
|
|
997
|
+
headers: [...stored.headers, ["idempotent-replayed", "true"]]
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
if (inFlight.has(slot))
|
|
1001
|
+
return errors.conflict();
|
|
1002
|
+
let release = () => {
|
|
1003
|
+
};
|
|
1004
|
+
inFlight.set(slot, new Promise((resolve) => {
|
|
1005
|
+
release = resolve;
|
|
1006
|
+
}));
|
|
1007
|
+
try {
|
|
1008
|
+
const response = await handler();
|
|
1009
|
+
if (!replayable(response.status))
|
|
1010
|
+
return response;
|
|
1011
|
+
const body = await response.clone().text();
|
|
1012
|
+
this.responses.insert(key, {
|
|
1013
|
+
fingerprint,
|
|
1014
|
+
status: response.status,
|
|
1015
|
+
headers: [...response.headers],
|
|
1016
|
+
body
|
|
1017
|
+
});
|
|
1018
|
+
return response;
|
|
1019
|
+
} finally {
|
|
1020
|
+
inFlight.delete(slot);
|
|
1021
|
+
release();
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
};
|
|
1025
|
+
var requestFingerprint = (method, path, body) => `${method.toUpperCase()} ${path} ${stableStringify(body)}`;
|
|
1026
|
+
var stableStringify = (value) => {
|
|
1027
|
+
if (Array.isArray(value))
|
|
1028
|
+
return `[${value.map(stableStringify).join(",")}]`;
|
|
1029
|
+
if (value && typeof value === "object") {
|
|
1030
|
+
return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
|
|
1031
|
+
}
|
|
1032
|
+
return JSON.stringify(value) ?? "undefined";
|
|
1033
|
+
};
|
|
1034
|
+
|
|
1035
|
+
// ../core/dist/ids.js
|
|
1036
|
+
var ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
1037
|
+
var mix = (input) => {
|
|
1038
|
+
let hash = 2166136261;
|
|
1039
|
+
for (let i = 0; i < input.length; i++) {
|
|
1040
|
+
hash ^= input.charCodeAt(i);
|
|
1041
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
1042
|
+
}
|
|
1043
|
+
hash ^= hash >>> 16;
|
|
1044
|
+
hash = Math.imul(hash, 2246822507) >>> 0;
|
|
1045
|
+
hash ^= hash >>> 13;
|
|
1046
|
+
return hash >>> 0;
|
|
1047
|
+
};
|
|
1048
|
+
var opaqueToken = (input, length) => {
|
|
1049
|
+
let out = "";
|
|
1050
|
+
let round = 0;
|
|
1051
|
+
while (out.length < length) {
|
|
1052
|
+
let hash = mix(`${input}:${round++}`);
|
|
1053
|
+
for (let i = 0; i < 5 && out.length < length; i++) {
|
|
1054
|
+
out += ALPHABET.charAt(hash % ALPHABET.length);
|
|
1055
|
+
hash = Math.floor(hash / ALPHABET.length);
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
return out;
|
|
1059
|
+
};
|
|
1060
|
+
var IdSequence = class {
|
|
1061
|
+
sqlite;
|
|
1062
|
+
namespace;
|
|
1063
|
+
salt;
|
|
1064
|
+
constructor(sqlite, namespace, salt = "mockingbird") {
|
|
1065
|
+
this.sqlite = sqlite;
|
|
1066
|
+
this.namespace = namespace;
|
|
1067
|
+
this.salt = salt;
|
|
1068
|
+
}
|
|
1069
|
+
next(prefix, length = 14) {
|
|
1070
|
+
return this.sqlite.transaction(() => {
|
|
1071
|
+
const row = this.sqlite.prepare("SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'").get(this.namespace, prefix);
|
|
1072
|
+
const value = (row?.value ?? 0) + 1;
|
|
1073
|
+
this.sqlite.prepare(`INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)
|
|
1074
|
+
ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`).run(this.namespace, prefix, value);
|
|
1075
|
+
return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`;
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
|
|
1080
|
+
// ../core/dist/journal.js
|
|
1081
|
+
var DEFAULT_JOURNAL_SIZE = 1e3;
|
|
1082
|
+
var createJournal = (size = DEFAULT_JOURNAL_SIZE) => {
|
|
1083
|
+
const capacity = Math.max(0, Math.floor(size));
|
|
1084
|
+
const rings = /* @__PURE__ */ new Map();
|
|
1085
|
+
let sequence = 0;
|
|
1086
|
+
const order = /* @__PURE__ */ new WeakMap();
|
|
1087
|
+
const inOrder = (ring) => ring.entries.length < capacity ? ring.entries : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)];
|
|
1088
|
+
return {
|
|
1089
|
+
size: capacity,
|
|
1090
|
+
record(entry) {
|
|
1091
|
+
if (capacity === 0)
|
|
1092
|
+
return;
|
|
1093
|
+
order.set(entry, sequence++);
|
|
1094
|
+
let ring = rings.get(entry.namespace);
|
|
1095
|
+
if (!ring) {
|
|
1096
|
+
ring = { entries: [], next: 0 };
|
|
1097
|
+
rings.set(entry.namespace, ring);
|
|
1098
|
+
}
|
|
1099
|
+
if (ring.entries.length < capacity)
|
|
1100
|
+
ring.entries.push(entry);
|
|
1101
|
+
else {
|
|
1102
|
+
ring.entries[ring.next] = entry;
|
|
1103
|
+
ring.next = (ring.next + 1) % capacity;
|
|
1104
|
+
}
|
|
1105
|
+
},
|
|
1106
|
+
list(query = {}) {
|
|
1107
|
+
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));
|
|
1108
|
+
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));
|
|
1109
|
+
return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
|
|
1110
|
+
},
|
|
1111
|
+
clear(namespace) {
|
|
1112
|
+
if (namespace === void 0)
|
|
1113
|
+
rings.clear();
|
|
1114
|
+
else
|
|
1115
|
+
rings.delete(namespace);
|
|
1116
|
+
}
|
|
1117
|
+
};
|
|
1118
|
+
};
|
|
1119
|
+
var notes = /* @__PURE__ */ new WeakMap();
|
|
1120
|
+
var annotateResponse = (response, extra) => {
|
|
1121
|
+
const existing = notes.get(response);
|
|
1122
|
+
notes.set(response, {
|
|
1123
|
+
...existing,
|
|
1124
|
+
...extra,
|
|
1125
|
+
...existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}
|
|
1126
|
+
});
|
|
1127
|
+
return response;
|
|
1128
|
+
};
|
|
1129
|
+
var responseNotes = (response) => notes.get(response);
|
|
1130
|
+
|
|
1131
|
+
// ../core/dist/metrics.js
|
|
1132
|
+
var createMetrics = () => {
|
|
1133
|
+
let requests = 0;
|
|
1134
|
+
let faults = 0;
|
|
1135
|
+
let totalDurationMs = 0;
|
|
1136
|
+
const byOperation = /* @__PURE__ */ new Map();
|
|
1137
|
+
const unmatched = /* @__PURE__ */ new Map();
|
|
1138
|
+
return {
|
|
1139
|
+
record(entry) {
|
|
1140
|
+
requests++;
|
|
1141
|
+
totalDurationMs += entry.durationMs;
|
|
1142
|
+
if (entry.faultId !== void 0)
|
|
1143
|
+
faults++;
|
|
1144
|
+
const key = `${entry.operationId ?? "(unmatched)"} ${entry.status}`;
|
|
1145
|
+
byOperation.set(key, (byOperation.get(key) ?? 0) + 1);
|
|
1146
|
+
if (entry.unmatched) {
|
|
1147
|
+
const route = `${entry.method} ${entry.path}`;
|
|
1148
|
+
unmatched.set(route, (unmatched.get(route) ?? 0) + 1);
|
|
1149
|
+
}
|
|
1150
|
+
},
|
|
1151
|
+
report: () => ({
|
|
1152
|
+
requests,
|
|
1153
|
+
byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),
|
|
1154
|
+
unmatched: [...unmatched].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([route, count]) => {
|
|
1155
|
+
const space = route.indexOf(" ");
|
|
1156
|
+
return { method: route.slice(0, space), path: route.slice(space + 1), count };
|
|
1157
|
+
}),
|
|
1158
|
+
faults,
|
|
1159
|
+
totalDurationMs
|
|
1160
|
+
}),
|
|
1161
|
+
reset() {
|
|
1162
|
+
requests = 0;
|
|
1163
|
+
faults = 0;
|
|
1164
|
+
totalDurationMs = 0;
|
|
1165
|
+
byOperation.clear();
|
|
1166
|
+
unmatched.clear();
|
|
1167
|
+
}
|
|
1168
|
+
};
|
|
1169
|
+
};
|
|
1170
|
+
|
|
1171
|
+
// ../core/dist/outbox.js
|
|
1172
|
+
var OutboxStore = class {
|
|
1173
|
+
items;
|
|
1174
|
+
constructor(sqlite, namespace, name = "outbox") {
|
|
1175
|
+
this.items = new Collection(sqlite, namespace, name);
|
|
1176
|
+
}
|
|
1177
|
+
record(item) {
|
|
1178
|
+
this.items.insert(item.id, item);
|
|
1179
|
+
return item;
|
|
1180
|
+
}
|
|
1181
|
+
get(id) {
|
|
1182
|
+
return this.items.get(id);
|
|
1183
|
+
}
|
|
1184
|
+
update(id, item) {
|
|
1185
|
+
this.items.update(id, item);
|
|
1186
|
+
}
|
|
1187
|
+
/** Oldest first, so a suite reads messages in the order they were sent. */
|
|
1188
|
+
list(query = {}) {
|
|
1189
|
+
const to = query.to?.toLowerCase();
|
|
1190
|
+
const matched = this.items.list({ order: "oldest" }).map((row) => row.value).filter((item) => {
|
|
1191
|
+
if (to !== void 0) {
|
|
1192
|
+
const recipients = Array.isArray(item.to) ? item.to : [item.to];
|
|
1193
|
+
if (!recipients.some((r) => r.toLowerCase() === to))
|
|
1194
|
+
return false;
|
|
1195
|
+
}
|
|
1196
|
+
if (query.since !== void 0 && Date.parse(item.createdAt) < query.since)
|
|
1197
|
+
return false;
|
|
1198
|
+
if (query.where && !query.where(item))
|
|
1199
|
+
return false;
|
|
1200
|
+
return true;
|
|
1201
|
+
});
|
|
1202
|
+
return query.limit !== void 0 ? matched.slice(-Math.max(0, query.limit)) : matched;
|
|
1203
|
+
}
|
|
1204
|
+
};
|
|
1205
|
+
var json2 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1206
|
+
var parseSince = (value) => {
|
|
1207
|
+
if (value === null)
|
|
1208
|
+
return void 0;
|
|
1209
|
+
const parsed = /^\d+$/.test(value) ? Number(value) : Date.parse(value);
|
|
1210
|
+
return Number.isNaN(parsed) ? null : parsed;
|
|
1211
|
+
};
|
|
1212
|
+
var outboxAdminRoutes = (runtime, pick, filter) => ({
|
|
1213
|
+
"GET /outbox": ({ url, namespace }) => {
|
|
1214
|
+
const since = parseSince(url.searchParams.get("since"));
|
|
1215
|
+
if (since === null) {
|
|
1216
|
+
return json2(400, {
|
|
1217
|
+
error: { type: "mockingbird_admin", message: "since: expected epoch ms or ISO-8601" }
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
const limit = url.searchParams.get("limit");
|
|
1221
|
+
const where = filter?.(url.searchParams);
|
|
1222
|
+
const to = url.searchParams.get("to");
|
|
1223
|
+
return json2(200, {
|
|
1224
|
+
messages: pick(runtime.instance(namespace)).list({
|
|
1225
|
+
...to !== null ? { to } : {},
|
|
1226
|
+
...since !== void 0 ? { since } : {},
|
|
1227
|
+
...where ? { where } : {},
|
|
1228
|
+
...limit !== null && /^\d+$/.test(limit) ? { limit: Number(limit) } : {}
|
|
1229
|
+
})
|
|
1230
|
+
});
|
|
1231
|
+
},
|
|
1232
|
+
"GET /outbox/:id": ({ params, namespace }) => {
|
|
1233
|
+
const item = pick(runtime.instance(namespace)).get(params.id);
|
|
1234
|
+
return item ? json2(200, item) : json2(404, { error: { type: "mockingbird_admin", message: `no message ${params.id}` } });
|
|
1235
|
+
}
|
|
1236
|
+
});
|
|
1237
|
+
var extractLinks = (html) => {
|
|
1238
|
+
const links = [];
|
|
1239
|
+
for (const match of html.matchAll(/href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)) {
|
|
1240
|
+
const raw = match[1] ?? match[2] ?? match[3] ?? "";
|
|
1241
|
+
const decoded = raw.replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">");
|
|
1242
|
+
if (decoded && !links.includes(decoded))
|
|
1243
|
+
links.push(decoded);
|
|
1244
|
+
}
|
|
1245
|
+
return links;
|
|
1246
|
+
};
|
|
1247
|
+
|
|
1248
|
+
// ../../core/dist/timeline.js
|
|
1249
|
+
var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1250
|
+
var Timeline = class {
|
|
1251
|
+
maxCheckpoints;
|
|
1252
|
+
now;
|
|
1253
|
+
makeId;
|
|
1254
|
+
nodes = /* @__PURE__ */ new Map();
|
|
1255
|
+
heads = /* @__PURE__ */ new Map();
|
|
1256
|
+
/** Unreferenced nodes in the exact order they became collectible. */
|
|
1257
|
+
evictable = /* @__PURE__ */ new Set();
|
|
1258
|
+
/** Branch heads plus explicit retainers. Absent means zero. */
|
|
1259
|
+
references = /* @__PURE__ */ new Map();
|
|
1260
|
+
explicitPins = /* @__PURE__ */ new Map();
|
|
1261
|
+
sequence = 0;
|
|
1262
|
+
constructor(options = {}) {
|
|
1263
|
+
const max = options.maxCheckpoints ?? 1e3;
|
|
1264
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1265
|
+
throw new RangeError("maxCheckpoints must be a positive integer");
|
|
1266
|
+
this.maxCheckpoints = max;
|
|
1267
|
+
this.now = options.now ?? (() => this.sequence);
|
|
1268
|
+
this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
|
|
1269
|
+
}
|
|
1270
|
+
/** Capture a new immutable value and move `branch` to it. */
|
|
1271
|
+
commit(value, options = {}) {
|
|
1272
|
+
const branch = options.branch ?? "main";
|
|
1273
|
+
this.assertBranch(branch);
|
|
1274
|
+
const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
|
|
1275
|
+
if (parent !== null && !this.nodes.has(parent))
|
|
1276
|
+
throw new RangeError(`no checkpoint ${parent}`);
|
|
1277
|
+
const id = this.makeId(++this.sequence);
|
|
1278
|
+
if (this.nodes.has(id))
|
|
1279
|
+
throw new RangeError(`duplicate checkpoint id ${id}`);
|
|
1280
|
+
const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
|
|
1281
|
+
this.nodes.set(id, checkpoint);
|
|
1282
|
+
this.moveHead(branch, id);
|
|
1283
|
+
this.collect(this.maxCheckpoints);
|
|
1284
|
+
return checkpoint;
|
|
1285
|
+
}
|
|
1286
|
+
/** Create a branch pointer without copying its checkpoint value. */
|
|
1287
|
+
fork(branch, options = {}) {
|
|
1288
|
+
this.assertBranch(branch);
|
|
1289
|
+
if (this.heads.has(branch))
|
|
1290
|
+
throw new RangeError(`branch already exists: ${branch}`);
|
|
1291
|
+
const from = options.from ?? this.heads.get("main");
|
|
1292
|
+
if (from === void 0)
|
|
1293
|
+
return void 0;
|
|
1294
|
+
const checkpoint = this.get(from);
|
|
1295
|
+
this.moveHead(branch, checkpoint.id);
|
|
1296
|
+
return checkpoint;
|
|
1297
|
+
}
|
|
1298
|
+
/** Move a branch pointer to an existing checkpoint. */
|
|
1299
|
+
checkout(branch, id) {
|
|
1300
|
+
this.assertBranch(branch);
|
|
1301
|
+
const checkpoint = this.get(id);
|
|
1302
|
+
this.moveHead(branch, checkpoint.id);
|
|
1303
|
+
return checkpoint;
|
|
1304
|
+
}
|
|
1305
|
+
get(id) {
|
|
1306
|
+
const checkpoint = this.nodes.get(id);
|
|
1307
|
+
if (!checkpoint)
|
|
1308
|
+
throw new RangeError(`no checkpoint ${id}`);
|
|
1309
|
+
return checkpoint;
|
|
1310
|
+
}
|
|
1311
|
+
head(branch = "main") {
|
|
1312
|
+
const id = this.heads.get(branch);
|
|
1313
|
+
return id === void 0 ? void 0 : this.get(id);
|
|
1314
|
+
}
|
|
1315
|
+
hasBranch(branch) {
|
|
1316
|
+
return this.heads.has(branch);
|
|
1317
|
+
}
|
|
1318
|
+
branches() {
|
|
1319
|
+
return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
|
|
1320
|
+
}
|
|
1321
|
+
checkpoints() {
|
|
1322
|
+
return [...this.nodes.values()];
|
|
1323
|
+
}
|
|
1324
|
+
/** Number of retained checkpoints without allocating an array. */
|
|
1325
|
+
get size() {
|
|
1326
|
+
return this.nodes.size;
|
|
1327
|
+
}
|
|
1328
|
+
/** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
|
|
1329
|
+
retain(id) {
|
|
1330
|
+
const checkpoint = this.get(id);
|
|
1331
|
+
this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
|
|
1332
|
+
this.addReference(id);
|
|
1333
|
+
return checkpoint;
|
|
1334
|
+
}
|
|
1335
|
+
/** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
|
|
1336
|
+
release(id) {
|
|
1337
|
+
if (!this.nodes.has(id))
|
|
1338
|
+
return false;
|
|
1339
|
+
const pins = this.explicitPins.get(id) ?? 0;
|
|
1340
|
+
if (pins === 0)
|
|
1341
|
+
return false;
|
|
1342
|
+
if (pins === 1)
|
|
1343
|
+
this.explicitPins.delete(id);
|
|
1344
|
+
else
|
|
1345
|
+
this.explicitPins.set(id, pins - 1);
|
|
1346
|
+
this.removeReference(id);
|
|
1347
|
+
this.collect(this.maxCheckpoints);
|
|
1348
|
+
return true;
|
|
1349
|
+
}
|
|
1350
|
+
deleteBranch(branch) {
|
|
1351
|
+
if (branch === "main")
|
|
1352
|
+
throw new RangeError("cannot delete main branch");
|
|
1353
|
+
const previous = this.heads.get(branch);
|
|
1354
|
+
const deleted = this.heads.delete(branch);
|
|
1355
|
+
if (previous !== void 0)
|
|
1356
|
+
this.removeReference(previous);
|
|
1357
|
+
this.collect(this.maxCheckpoints);
|
|
1358
|
+
return deleted;
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
|
|
1362
|
+
* commits never scan pinned nodes or the retained history. Parents are metadata rather than a
|
|
1363
|
+
* storage dependency, so a retained node remains usable after pruning.
|
|
1364
|
+
*/
|
|
1365
|
+
gc(max = this.maxCheckpoints) {
|
|
1366
|
+
if (!Number.isSafeInteger(max) || max < 1)
|
|
1367
|
+
throw new RangeError("max must be a positive integer");
|
|
1368
|
+
const removed = [];
|
|
1369
|
+
this.collect(max, removed);
|
|
1370
|
+
return removed;
|
|
1371
|
+
}
|
|
1372
|
+
collect(max, removed) {
|
|
1373
|
+
while (this.nodes.size > max && this.evictable.size > 0) {
|
|
1374
|
+
const id = this.evictable.values().next().value;
|
|
1375
|
+
this.evictable.delete(id);
|
|
1376
|
+
this.nodes.delete(id);
|
|
1377
|
+
removed?.push(id);
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
moveHead(branch, id) {
|
|
1381
|
+
const previous = this.heads.get(branch);
|
|
1382
|
+
if (previous === id)
|
|
1383
|
+
return;
|
|
1384
|
+
if (previous !== void 0)
|
|
1385
|
+
this.removeReference(previous);
|
|
1386
|
+
this.heads.set(branch, id);
|
|
1387
|
+
this.addReference(id);
|
|
1388
|
+
}
|
|
1389
|
+
addReference(id) {
|
|
1390
|
+
this.references.set(id, (this.references.get(id) ?? 0) + 1);
|
|
1391
|
+
this.evictable.delete(id);
|
|
1392
|
+
}
|
|
1393
|
+
removeReference(id) {
|
|
1394
|
+
const next = (this.references.get(id) ?? 0) - 1;
|
|
1395
|
+
if (next > 0)
|
|
1396
|
+
this.references.set(id, next);
|
|
1397
|
+
else {
|
|
1398
|
+
this.references.delete(id);
|
|
1399
|
+
if (this.nodes.has(id))
|
|
1400
|
+
this.evictable.add(id);
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
assertBranch(branch) {
|
|
1404
|
+
if (!BRANCH_PATTERN.test(branch))
|
|
1405
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
|
|
1406
|
+
}
|
|
1407
|
+
};
|
|
1408
|
+
|
|
1409
|
+
// ../../sqlite/dist/default.js
|
|
1410
|
+
import { Database } from "@crvouga/mockingbird-service-sqlite";
|
|
1411
|
+
var createDefaultSqlite = () => new Database();
|
|
1412
|
+
var resolveSqlite = (sqlite) => sqlite ?? createDefaultSqlite();
|
|
1413
|
+
|
|
1414
|
+
// ../../sqlite/dist/migrate.js
|
|
1415
|
+
var ensureMigrationsTable = (sqlite) => {
|
|
1416
|
+
sqlite.exec(`
|
|
1417
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
1418
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
1419
|
+
applied_at INTEGER NOT NULL
|
|
1420
|
+
)
|
|
1421
|
+
`);
|
|
1422
|
+
};
|
|
1423
|
+
var migrate = (sqlite, migrations) => {
|
|
1424
|
+
ensureMigrationsTable(sqlite);
|
|
1425
|
+
const applied = new Set(sqlite.prepare("SELECT id FROM schema_migrations").all().map((row) => row.id));
|
|
1426
|
+
const pending = migrations.filter((migration) => !applied.has(migration.id));
|
|
1427
|
+
if (pending.length === 0)
|
|
1428
|
+
return;
|
|
1429
|
+
const insert = sqlite.prepare("INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)");
|
|
1430
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1431
|
+
sqlite.transaction(() => {
|
|
1432
|
+
for (const migration of pending) {
|
|
1433
|
+
sqlite.exec(migration.sql);
|
|
1434
|
+
insert.run(migration.id, now);
|
|
1435
|
+
}
|
|
1436
|
+
});
|
|
1437
|
+
};
|
|
1438
|
+
|
|
1439
|
+
// ../../sqlite/dist/schema.js
|
|
1440
|
+
var CORE_MIGRATIONS = [
|
|
1441
|
+
{
|
|
1442
|
+
id: "20260322_core_records_sequences",
|
|
1443
|
+
sql: `
|
|
1444
|
+
CREATE TABLE IF NOT EXISTS mockingbird_records (
|
|
1445
|
+
namespace TEXT NOT NULL,
|
|
1446
|
+
collection TEXT NOT NULL,
|
|
1447
|
+
id TEXT NOT NULL,
|
|
1448
|
+
seq INTEGER NOT NULL,
|
|
1449
|
+
value TEXT NOT NULL,
|
|
1450
|
+
PRIMARY KEY (namespace, collection, id)
|
|
1451
|
+
);
|
|
1452
|
+
CREATE INDEX IF NOT EXISTS mockingbird_records_seq
|
|
1453
|
+
ON mockingbird_records (namespace, collection, seq);
|
|
1454
|
+
CREATE TABLE IF NOT EXISTS mockingbird_sequences (
|
|
1455
|
+
namespace TEXT NOT NULL,
|
|
1456
|
+
name TEXT NOT NULL,
|
|
1457
|
+
kind TEXT NOT NULL,
|
|
1458
|
+
value INTEGER NOT NULL,
|
|
1459
|
+
PRIMARY KEY (namespace, name, kind)
|
|
1460
|
+
);
|
|
1461
|
+
`
|
|
1462
|
+
}
|
|
1463
|
+
];
|
|
1464
|
+
var migrateCore = (sqlite) => {
|
|
1465
|
+
migrate(sqlite, CORE_MIGRATIONS);
|
|
1466
|
+
};
|
|
1467
|
+
var clearNamespace = (sqlite, namespace) => {
|
|
1468
|
+
sqlite.transaction(() => {
|
|
1469
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1470
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1471
|
+
});
|
|
1472
|
+
};
|
|
1473
|
+
|
|
1474
|
+
// ../../openapi/metadata/dist/types.js
|
|
1475
|
+
var EXTENSION_KEYS = {
|
|
1476
|
+
operation: "x-mockingbird",
|
|
1477
|
+
resource: "x-mockingbird-resource",
|
|
1478
|
+
resourceRef: "x-mockingbird-resource-ref",
|
|
1479
|
+
volatile: "x-mockingbird-volatile",
|
|
1480
|
+
scope: "x-mockingbird-scope",
|
|
1481
|
+
unsupported: "x-mockingbird-unsupported",
|
|
1482
|
+
parityHeader: "x-mockingbird-parity-header"
|
|
1483
|
+
};
|
|
1484
|
+
|
|
1485
|
+
// ../../openapi/metadata/dist/read.js
|
|
1486
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1487
|
+
var extensionOf = (holder, key) => holder[key];
|
|
1488
|
+
var operationMetadata = (operation) => {
|
|
1489
|
+
const raw = extensionOf(operation, EXTENSION_KEYS.operation);
|
|
1490
|
+
const ext = isRecord2(raw) ? raw : {};
|
|
1491
|
+
const supported = ext.supported ?? true;
|
|
1492
|
+
const parity = ext.parity ?? {};
|
|
1493
|
+
return {
|
|
1494
|
+
supported,
|
|
1495
|
+
reason: typeof ext.reason === "string" ? ext.reason : void 0,
|
|
1496
|
+
parity: {
|
|
1497
|
+
enabled: supported && (parity.enabled ?? true),
|
|
1498
|
+
safe: parity.safe ?? true,
|
|
1499
|
+
reason: typeof parity.reason === "string" ? parity.reason : void 0
|
|
1500
|
+
}
|
|
1501
|
+
};
|
|
1502
|
+
};
|
|
1503
|
+
|
|
1504
|
+
// ../core/dist/service.js
|
|
1505
|
+
import { Hono } from "hono";
|
|
1506
|
+
var defineOperations = (handlers) => handlers;
|
|
1507
|
+
var OperationRegistryError = class extends Error {
|
|
1508
|
+
problems;
|
|
1509
|
+
constructor(problems) {
|
|
1510
|
+
super(`operation registry is inconsistent:
|
|
1511
|
+
${problems.map((p) => ` - ${p}`).join("\n")}`);
|
|
1512
|
+
this.problems = problems;
|
|
1513
|
+
this.name = "OperationRegistryError";
|
|
1514
|
+
}
|
|
1515
|
+
};
|
|
1516
|
+
var verifyOperations = (document2, handlers) => {
|
|
1517
|
+
const problems = [];
|
|
1518
|
+
const operations = listOperations(document2);
|
|
1519
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1520
|
+
for (const operation of operations) {
|
|
1521
|
+
if (seen.has(operation.operationId))
|
|
1522
|
+
problems.push(`duplicate operationId ${operation.operationId}`);
|
|
1523
|
+
seen.add(operation.operationId);
|
|
1524
|
+
const supported = operationMetadata(operation.operation).supported;
|
|
1525
|
+
const handler = handlers[operation.operationId];
|
|
1526
|
+
if (supported && !handler)
|
|
1527
|
+
problems.push(`supported operation ${operation.operationId} has no handler`);
|
|
1528
|
+
if (!supported && handler)
|
|
1529
|
+
problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`);
|
|
1530
|
+
}
|
|
1531
|
+
for (const id of Object.keys(handlers)) {
|
|
1532
|
+
if (!seen.has(id))
|
|
1533
|
+
problems.push(`handler ${id} has no OpenAPI operation`);
|
|
1534
|
+
}
|
|
1535
|
+
return problems;
|
|
1536
|
+
};
|
|
1537
|
+
var honoPath = (template) => template.replace(/\{([^}]+)\}/g, ":$1");
|
|
1538
|
+
var routeOrder = (a, b) => {
|
|
1539
|
+
const sa = a.path.split("/");
|
|
1540
|
+
const sb = b.path.split("/");
|
|
1541
|
+
for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
|
|
1542
|
+
const x = sa[i] ?? "";
|
|
1543
|
+
const y = sb[i] ?? "";
|
|
1544
|
+
const px = x.startsWith("{");
|
|
1545
|
+
const py = y.startsWith("{");
|
|
1546
|
+
if (px !== py)
|
|
1547
|
+
return px ? 1 : -1;
|
|
1548
|
+
if (x !== y)
|
|
1549
|
+
return x < y ? -1 : 1;
|
|
1550
|
+
}
|
|
1551
|
+
return 0;
|
|
1552
|
+
};
|
|
1553
|
+
var queryOf = (url) => decodeFormPairs(url.searchParams.entries());
|
|
1554
|
+
var bootSqlite = (sqlite) => {
|
|
1555
|
+
const client = resolveSqlite(sqlite);
|
|
1556
|
+
migrateCore(client);
|
|
1557
|
+
return client;
|
|
1558
|
+
};
|
|
1559
|
+
var createService = (options) => {
|
|
1560
|
+
const problems = verifyOperations(options.document, options.handlers);
|
|
1561
|
+
if (problems.length > 0)
|
|
1562
|
+
throw new OperationRegistryError(problems);
|
|
1563
|
+
migrateCore(options.sqlite);
|
|
1564
|
+
const now = options.now ?? (() => Date.now());
|
|
1565
|
+
const app = new Hono();
|
|
1566
|
+
app.notFound((c) => options.notFound(c.req.raw));
|
|
1567
|
+
app.onError((error2, c) => options.onError(error2, c.req.raw));
|
|
1568
|
+
const operations = [...listOperations(options.document)].sort(routeOrder);
|
|
1569
|
+
for (const operation of operations) {
|
|
1570
|
+
const metadata = operationMetadata(operation.operation);
|
|
1571
|
+
const handler = options.handlers[operation.operationId];
|
|
1572
|
+
const route = async (c) => {
|
|
1573
|
+
const request = c.req.raw;
|
|
1574
|
+
if (!metadata.supported || !handler) {
|
|
1575
|
+
return options.unsupported ? options.unsupported(request, operation) : options.notFound(request);
|
|
1576
|
+
}
|
|
1577
|
+
const url = new URL(request.url);
|
|
1578
|
+
const context = {
|
|
1579
|
+
request,
|
|
1580
|
+
url,
|
|
1581
|
+
params: c.req.param(),
|
|
1582
|
+
query: queryOf(url),
|
|
1583
|
+
body: await readBody(request),
|
|
1584
|
+
sqlite: options.sqlite,
|
|
1585
|
+
namespace: options.namespace,
|
|
1586
|
+
operation,
|
|
1587
|
+
document: options.document,
|
|
1588
|
+
now
|
|
1589
|
+
};
|
|
1590
|
+
const short = await options.before?.(context);
|
|
1591
|
+
if (short)
|
|
1592
|
+
return short;
|
|
1593
|
+
return handler(context);
|
|
1594
|
+
};
|
|
1595
|
+
app.on(operation.method.toUpperCase(), honoPath(operation.path), route);
|
|
1596
|
+
}
|
|
1597
|
+
return {
|
|
1598
|
+
app,
|
|
1599
|
+
sqlite: options.sqlite,
|
|
1600
|
+
namespace: options.namespace,
|
|
1601
|
+
fetch: async (request) => app.fetch(request),
|
|
1602
|
+
reset: async () => {
|
|
1603
|
+
clearNamespace(options.sqlite, options.namespace);
|
|
1604
|
+
}
|
|
1605
|
+
};
|
|
1606
|
+
};
|
|
1607
|
+
|
|
1608
|
+
// ../core/dist/snapshot.js
|
|
1609
|
+
var snapshotNamespace = (sqlite, namespace) => ({
|
|
1610
|
+
namespace,
|
|
1611
|
+
records: sqlite.prepare("SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq").all(namespace),
|
|
1612
|
+
sequences: sqlite.prepare("SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind").all(namespace)
|
|
1613
|
+
});
|
|
1614
|
+
var restoreNamespace = (sqlite, namespace, snapshot) => {
|
|
1615
|
+
sqlite.transaction(() => {
|
|
1616
|
+
sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ?").run(namespace);
|
|
1617
|
+
sqlite.prepare("DELETE FROM mockingbird_sequences WHERE namespace = ?").run(namespace);
|
|
1618
|
+
const record = sqlite.prepare("INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)");
|
|
1619
|
+
for (const row of snapshot.records) {
|
|
1620
|
+
record.run(namespace, row.collection, row.id, row.seq, row.value);
|
|
1621
|
+
}
|
|
1622
|
+
const sequence = sqlite.prepare("INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)");
|
|
1623
|
+
for (const row of snapshot.sequences) {
|
|
1624
|
+
sequence.run(namespace, row.name, row.kind, row.value);
|
|
1625
|
+
}
|
|
1626
|
+
});
|
|
1627
|
+
};
|
|
1628
|
+
|
|
1629
|
+
// ../core/dist/version.js
|
|
1630
|
+
var PACKAGE_VERSION = true ? "0.1.0" : UNRELEASED_VERSION;
|
|
1631
|
+
|
|
1632
|
+
// ../core/dist/signing.js
|
|
1633
|
+
var encoder = new TextEncoder();
|
|
1634
|
+
var toBase64 = (bytes) => {
|
|
1635
|
+
let binary = "";
|
|
1636
|
+
for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {
|
|
1637
|
+
binary += String.fromCharCode(byte);
|
|
1638
|
+
}
|
|
1639
|
+
return btoa(binary);
|
|
1640
|
+
};
|
|
1641
|
+
var fromBase64 = (value) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
|
|
1642
|
+
var toHex = (bytes) => [...bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1643
|
+
var keyBytes = (key) => typeof key === "string" ? encoder.encode(key) : key;
|
|
1644
|
+
var hmac = async (algorithm, key, message, encoding = "hex") => {
|
|
1645
|
+
const imported = await crypto.subtle.importKey("raw", keyBytes(key), { name: "HMAC", hash: algorithm }, false, ["sign"]);
|
|
1646
|
+
const signed = await crypto.subtle.sign("HMAC", imported, typeof message === "string" ? encoder.encode(message) : message);
|
|
1647
|
+
return encoding === "hex" ? toHex(signed) : toBase64(signed);
|
|
1648
|
+
};
|
|
1649
|
+
var svixSecretBytes = (secret) => {
|
|
1650
|
+
const raw = secret.replace(/^f?whsec_/, "");
|
|
1651
|
+
try {
|
|
1652
|
+
return fromBase64(raw);
|
|
1653
|
+
} catch {
|
|
1654
|
+
throw new TypeError("webhook secret must be whsec_<base64> (as Svix issues it)");
|
|
1655
|
+
}
|
|
1656
|
+
};
|
|
1657
|
+
var signSvix = async (secret, messageId, timestampSeconds, body) => `v1,${await hmac("SHA-256", svixSecretBytes(secret), `${messageId}.${timestampSeconds}.${body}`, "base64")}`;
|
|
1658
|
+
var signTimestamped = async (secret, timestampSeconds, body) => `t=${timestampSeconds},v1=${await hmac("SHA-256", secret, `${timestampSeconds}.${body}`, "hex")}`;
|
|
1659
|
+
var signTwilio = async (authToken, url, params) => {
|
|
1660
|
+
const payload = url + Object.keys(params).sort().map((key) => `${key}${params[key]}`).join("");
|
|
1661
|
+
return hmac("SHA-1", authToken, payload, "base64");
|
|
1662
|
+
};
|
|
1663
|
+
|
|
1664
|
+
// ../core/dist/webhooks.js
|
|
1665
|
+
var signers = {
|
|
1666
|
+
/** No signature. */
|
|
1667
|
+
none: () => () => ({}),
|
|
1668
|
+
/** Svix (`svix-id`, `svix-timestamp`, `svix-signature: v1,<b64>`): Junction, Flex, Resend. */
|
|
1669
|
+
svix: (options = {}) => async ({ messageId, body, timestampSeconds, secret }) => {
|
|
1670
|
+
if (!secret)
|
|
1671
|
+
return {};
|
|
1672
|
+
const prefix = options.prefix ?? "svix";
|
|
1673
|
+
return {
|
|
1674
|
+
[`${prefix}-id`]: messageId,
|
|
1675
|
+
[`${prefix}-timestamp`]: String(timestampSeconds),
|
|
1676
|
+
[`${prefix}-signature`]: await signSvix(secret, messageId, timestampSeconds, body)
|
|
1677
|
+
};
|
|
1678
|
+
},
|
|
1679
|
+
/** `<header>: t=<unix>,v1=<hex HMAC-SHA256(secret, "t.body")>`: Stripe, Persona, Fullscript. */
|
|
1680
|
+
timestamped: (header = "Stripe-Signature") => async ({ body, timestampSeconds, secret }) => secret ? { [header]: await signTimestamped(secret, timestampSeconds, body) } : {},
|
|
1681
|
+
/** `X-Twilio-Signature` over the public URL plus the sorted form parameters. */
|
|
1682
|
+
twilio: () => async ({ signUrl, form, secret }) => secret ? { "X-Twilio-Signature": await signTwilio(secret, signUrl, form ?? {}) } : {},
|
|
1683
|
+
/** The secret itself in a header (optionally templated): RxVortex, Pharmetika, AHA `Token <s>`. */
|
|
1684
|
+
header: (header, format = (s) => s) => ({ secret }) => secret ? { [header]: format(secret) } : {},
|
|
1685
|
+
/** Anything else: the service computes the headers itself. */
|
|
1686
|
+
custom: (sign) => sign
|
|
1687
|
+
};
|
|
1688
|
+
var DEFAULT_DELAYS = [0, 5e3, 3e5, 18e5, 72e5];
|
|
1689
|
+
var unref = (timer) => {
|
|
1690
|
+
;
|
|
1691
|
+
timer.unref?.();
|
|
1692
|
+
};
|
|
1693
|
+
var randomId = (prefix) => `${prefix}${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`;
|
|
1694
|
+
var matchesEndpoint = (endpoint, message) => {
|
|
1695
|
+
const events = endpoint.events ?? ["*"];
|
|
1696
|
+
if (!events.includes("*") && !events.includes(message.type))
|
|
1697
|
+
return false;
|
|
1698
|
+
for (const [key, value] of Object.entries(endpoint.tags ?? {})) {
|
|
1699
|
+
if (message.tags[key] !== value)
|
|
1700
|
+
return false;
|
|
1701
|
+
}
|
|
1702
|
+
return true;
|
|
1703
|
+
};
|
|
1704
|
+
var createWebhookHub = (options) => {
|
|
1705
|
+
const delays = options.retryDelaysMs ?? DEFAULT_DELAYS;
|
|
1706
|
+
const timeoutMs = options.timeoutMs ?? 15e3;
|
|
1707
|
+
const delivered = options.delivered ?? ((status) => status >= 200 && status < 300);
|
|
1708
|
+
const send = options.fetch ?? ((request) => fetch(request));
|
|
1709
|
+
const keep = options.keep ?? 500;
|
|
1710
|
+
const now = options.now ?? Date.now;
|
|
1711
|
+
const id = options.id ?? randomId;
|
|
1712
|
+
const scheduleTimer = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
|
|
1713
|
+
const cancel = options.cancel ?? ((handle) => clearTimeout(handle));
|
|
1714
|
+
const global = (options.endpoints ?? []).map((e, i) => ({ ...e, id: e.id ?? `we_global_${i}` }));
|
|
1715
|
+
const own = /* @__PURE__ */ new Map();
|
|
1716
|
+
const messages = [];
|
|
1717
|
+
const deliveries = /* @__PURE__ */ new Map();
|
|
1718
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1719
|
+
const payloads = /* @__PURE__ */ new Map();
|
|
1720
|
+
const faults = /* @__PURE__ */ new Map();
|
|
1721
|
+
const held = /* @__PURE__ */ new Map();
|
|
1722
|
+
const inFlight2 = /* @__PURE__ */ new Set();
|
|
1723
|
+
const track = (work) => {
|
|
1724
|
+
inFlight2.add(work);
|
|
1725
|
+
void work.finally(() => inFlight2.delete(work));
|
|
1726
|
+
};
|
|
1727
|
+
const attempt = async (delivery) => {
|
|
1728
|
+
const entry = payloads.get(delivery.id);
|
|
1729
|
+
if (!entry)
|
|
1730
|
+
return false;
|
|
1731
|
+
const { message, endpoint } = entry;
|
|
1732
|
+
const timestampSeconds = Math.floor(now() / 1e3);
|
|
1733
|
+
const started = now();
|
|
1734
|
+
const record = {
|
|
1735
|
+
attempt: delivery.attempts.length + 1,
|
|
1736
|
+
at: new Date(started).toISOString(),
|
|
1737
|
+
status: null,
|
|
1738
|
+
error: null,
|
|
1739
|
+
durationMs: 0,
|
|
1740
|
+
responseBody: null
|
|
1741
|
+
};
|
|
1742
|
+
const controller = new AbortController();
|
|
1743
|
+
const timer = scheduleTimer(() => controller.abort(), timeoutMs);
|
|
1744
|
+
try {
|
|
1745
|
+
const signed = await options.signer({
|
|
1746
|
+
messageId: message.id,
|
|
1747
|
+
body: message.body,
|
|
1748
|
+
timestampSeconds,
|
|
1749
|
+
url: endpoint.url,
|
|
1750
|
+
secret: endpoint.secret,
|
|
1751
|
+
signUrl: endpoint.signUrl ?? endpoint.url,
|
|
1752
|
+
form: message.contentType.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(message.body)) : void 0,
|
|
1753
|
+
type: message.type,
|
|
1754
|
+
tags: message.tags
|
|
1755
|
+
});
|
|
1756
|
+
const response = await send(new Request(endpoint.url, {
|
|
1757
|
+
method: "POST",
|
|
1758
|
+
headers: {
|
|
1759
|
+
"content-type": message.contentType,
|
|
1760
|
+
...endpoint.headers,
|
|
1761
|
+
...message.headers,
|
|
1762
|
+
...signed
|
|
1763
|
+
},
|
|
1764
|
+
body: message.body,
|
|
1765
|
+
signal: controller.signal
|
|
1766
|
+
}));
|
|
1767
|
+
record.status = response.status;
|
|
1768
|
+
record.responseBody = await response.text();
|
|
1769
|
+
} catch (error2) {
|
|
1770
|
+
record.error = controller.signal.aborted ? `timed out after ${timeoutMs}ms` : error2 instanceof Error ? error2.message : String(error2);
|
|
1771
|
+
} finally {
|
|
1772
|
+
cancel(timer);
|
|
1773
|
+
record.durationMs = now() - started;
|
|
1774
|
+
delivery.attempts.push(record);
|
|
1775
|
+
}
|
|
1776
|
+
return record.status !== null && delivered(record.status);
|
|
1777
|
+
};
|
|
1778
|
+
const schedule = (delivery) => {
|
|
1779
|
+
const index = delivery.attempts.length;
|
|
1780
|
+
if (index >= delays.length) {
|
|
1781
|
+
delivery.state = "failed";
|
|
1782
|
+
pending.delete(delivery.id);
|
|
1783
|
+
return;
|
|
1784
|
+
}
|
|
1785
|
+
const run = () => {
|
|
1786
|
+
pending.delete(delivery.id);
|
|
1787
|
+
track(attempt(delivery).then((ok) => {
|
|
1788
|
+
if (ok)
|
|
1789
|
+
delivery.state = "delivered";
|
|
1790
|
+
else
|
|
1791
|
+
schedule(delivery);
|
|
1792
|
+
}));
|
|
1793
|
+
};
|
|
1794
|
+
const delay = delays[index] ?? 0;
|
|
1795
|
+
if (delay <= 0) {
|
|
1796
|
+
pending.set(delivery.id, void 0);
|
|
1797
|
+
run();
|
|
1798
|
+
return;
|
|
1799
|
+
}
|
|
1800
|
+
const timer = scheduleTimer(run, delay);
|
|
1801
|
+
unref(timer);
|
|
1802
|
+
pending.set(delivery.id, timer);
|
|
1803
|
+
};
|
|
1804
|
+
const endpointsFor = (namespace) => [...own.get(namespace) ?? [], ...global];
|
|
1805
|
+
const fanOut = (message, state = "pending") => {
|
|
1806
|
+
for (const endpoint of endpointsFor(message.namespace)) {
|
|
1807
|
+
if (!matchesEndpoint(endpoint, message))
|
|
1808
|
+
continue;
|
|
1809
|
+
const delivery = {
|
|
1810
|
+
id: id("dlv_"),
|
|
1811
|
+
messageId: message.id,
|
|
1812
|
+
namespace: message.namespace,
|
|
1813
|
+
type: message.type,
|
|
1814
|
+
endpointId: endpoint.id ?? "we_unknown",
|
|
1815
|
+
url: endpoint.url,
|
|
1816
|
+
state,
|
|
1817
|
+
attempts: []
|
|
1818
|
+
};
|
|
1819
|
+
deliveries.set(delivery.id, delivery);
|
|
1820
|
+
payloads.set(delivery.id, { message, endpoint });
|
|
1821
|
+
if (state === "pending")
|
|
1822
|
+
schedule(delivery);
|
|
1823
|
+
}
|
|
1824
|
+
};
|
|
1825
|
+
const takeFault = (namespace) => {
|
|
1826
|
+
const queue = faults.get(namespace);
|
|
1827
|
+
const head = queue?.[0];
|
|
1828
|
+
if (!queue || !head)
|
|
1829
|
+
return void 0;
|
|
1830
|
+
head.remaining--;
|
|
1831
|
+
if (head.remaining <= 0)
|
|
1832
|
+
queue.shift();
|
|
1833
|
+
return head.mode;
|
|
1834
|
+
};
|
|
1835
|
+
const releaseHeld = (namespace) => {
|
|
1836
|
+
const waiting = held.get(namespace);
|
|
1837
|
+
if (!waiting)
|
|
1838
|
+
return;
|
|
1839
|
+
held.delete(namespace);
|
|
1840
|
+
for (const message of waiting)
|
|
1841
|
+
fanOut(message);
|
|
1842
|
+
};
|
|
1843
|
+
const hub = {
|
|
1844
|
+
publish(input) {
|
|
1845
|
+
const contentType = input.contentType ?? (input.form ? "application/x-www-form-urlencoded" : "application/json");
|
|
1846
|
+
const body = typeof input.body === "string" ? input.body : input.form ? new URLSearchParams(input.form).toString() : JSON.stringify(input.body);
|
|
1847
|
+
const message = {
|
|
1848
|
+
id: input.id ?? id("msg_"),
|
|
1849
|
+
namespace: input.namespace,
|
|
1850
|
+
type: input.type,
|
|
1851
|
+
body,
|
|
1852
|
+
contentType,
|
|
1853
|
+
tags: input.tags ?? {},
|
|
1854
|
+
headers: input.headers ?? {},
|
|
1855
|
+
publishedAt: new Date(now()).toISOString()
|
|
1856
|
+
};
|
|
1857
|
+
messages.push(message);
|
|
1858
|
+
const ofNamespace = messages.filter((m) => m.namespace === message.namespace);
|
|
1859
|
+
const oldest = ofNamespace[0];
|
|
1860
|
+
if (ofNamespace.length > keep && oldest)
|
|
1861
|
+
messages.splice(messages.indexOf(oldest), 1);
|
|
1862
|
+
options.onMessage?.(message);
|
|
1863
|
+
const fault = takeFault(message.namespace);
|
|
1864
|
+
if (fault === "drop") {
|
|
1865
|
+
fanOut(message, "dropped");
|
|
1866
|
+
return message;
|
|
1867
|
+
}
|
|
1868
|
+
if (fault === "reorder") {
|
|
1869
|
+
held.set(message.namespace, [...held.get(message.namespace) ?? [], message]);
|
|
1870
|
+
return message;
|
|
1871
|
+
}
|
|
1872
|
+
fanOut(message);
|
|
1873
|
+
if (fault === "duplicate")
|
|
1874
|
+
fanOut(message);
|
|
1875
|
+
releaseHeld(message.namespace);
|
|
1876
|
+
return message;
|
|
1877
|
+
},
|
|
1878
|
+
setEndpoints(namespace, endpoints) {
|
|
1879
|
+
const withIds = endpoints.map((e, i) => ({ ...e, id: e.id ?? `we_${namespace}_${i}` }));
|
|
1880
|
+
own.set(namespace, withIds);
|
|
1881
|
+
return withIds;
|
|
1882
|
+
},
|
|
1883
|
+
endpoints: endpointsFor,
|
|
1884
|
+
messages: (namespace) => namespace === void 0 ? [...messages] : messages.filter((m) => m.namespace === namespace),
|
|
1885
|
+
deliveries: (namespace) => [...deliveries.values()].filter((d) => namespace === void 0 || d.namespace === namespace),
|
|
1886
|
+
async replay(id2) {
|
|
1887
|
+
const delivery = deliveries.get(id2);
|
|
1888
|
+
if (!delivery)
|
|
1889
|
+
return void 0;
|
|
1890
|
+
const ok = await attempt(delivery);
|
|
1891
|
+
if (ok)
|
|
1892
|
+
delivery.state = "delivered";
|
|
1893
|
+
return delivery;
|
|
1894
|
+
},
|
|
1895
|
+
async flush() {
|
|
1896
|
+
for (const namespace of [...held.keys()])
|
|
1897
|
+
releaseHeld(namespace);
|
|
1898
|
+
const waiting = [...pending.entries()];
|
|
1899
|
+
for (const [id2, timer] of waiting) {
|
|
1900
|
+
if (timer === void 0)
|
|
1901
|
+
continue;
|
|
1902
|
+
cancel(timer);
|
|
1903
|
+
pending.delete(id2);
|
|
1904
|
+
const delivery = deliveries.get(id2);
|
|
1905
|
+
if (!delivery)
|
|
1906
|
+
continue;
|
|
1907
|
+
track(attempt(delivery).then((ok) => {
|
|
1908
|
+
if (ok)
|
|
1909
|
+
delivery.state = "delivered";
|
|
1910
|
+
else
|
|
1911
|
+
schedule(delivery);
|
|
1912
|
+
}));
|
|
1913
|
+
}
|
|
1914
|
+
await hub.idle();
|
|
1915
|
+
},
|
|
1916
|
+
async idle() {
|
|
1917
|
+
while (inFlight2.size > 0)
|
|
1918
|
+
await Promise.allSettled([...inFlight2]);
|
|
1919
|
+
},
|
|
1920
|
+
fault(namespace, fault) {
|
|
1921
|
+
const queue = faults.get(namespace) ?? [];
|
|
1922
|
+
queue.push({ mode: fault.mode, remaining: Math.max(1, fault.count ?? 1) });
|
|
1923
|
+
faults.set(namespace, queue);
|
|
1924
|
+
},
|
|
1925
|
+
clear(namespace) {
|
|
1926
|
+
for (const [id2, delivery] of deliveries) {
|
|
1927
|
+
if (namespace !== void 0 && delivery.namespace !== namespace)
|
|
1928
|
+
continue;
|
|
1929
|
+
const timer = pending.get(id2);
|
|
1930
|
+
if (timer !== void 0)
|
|
1931
|
+
cancel(timer);
|
|
1932
|
+
pending.delete(id2);
|
|
1933
|
+
deliveries.delete(id2);
|
|
1934
|
+
payloads.delete(id2);
|
|
1935
|
+
}
|
|
1936
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1937
|
+
if (namespace === void 0 || messages[i]?.namespace === namespace)
|
|
1938
|
+
messages.splice(i, 1);
|
|
1939
|
+
}
|
|
1940
|
+
if (namespace === void 0) {
|
|
1941
|
+
held.clear();
|
|
1942
|
+
faults.clear();
|
|
1943
|
+
own.clear();
|
|
1944
|
+
} else {
|
|
1945
|
+
held.delete(namespace);
|
|
1946
|
+
faults.delete(namespace);
|
|
1947
|
+
own.delete(namespace);
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
};
|
|
1951
|
+
return hub;
|
|
1952
|
+
};
|
|
1953
|
+
var json3 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
1954
|
+
var adminError2 = (status, message) => json3(status, { error: { type: "mockingbird_admin", message } });
|
|
1955
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1956
|
+
var parseEndpoint = (value) => {
|
|
1957
|
+
if (!isRecord3(value) || typeof value.url !== "string")
|
|
1958
|
+
return "each endpoint needs a url";
|
|
1959
|
+
try {
|
|
1960
|
+
new URL(value.url);
|
|
1961
|
+
} catch {
|
|
1962
|
+
return `not a URL: ${value.url}`;
|
|
1963
|
+
}
|
|
1964
|
+
const endpoint = { url: value.url };
|
|
1965
|
+
if (typeof value.id === "string")
|
|
1966
|
+
endpoint.id = value.id;
|
|
1967
|
+
if (typeof value.secret === "string")
|
|
1968
|
+
endpoint.secret = value.secret;
|
|
1969
|
+
if (typeof value.signUrl === "string")
|
|
1970
|
+
endpoint.signUrl = value.signUrl;
|
|
1971
|
+
const events = value.events ?? value.enabledEvents;
|
|
1972
|
+
if (Array.isArray(events))
|
|
1973
|
+
endpoint.events = events.map(String);
|
|
1974
|
+
if (isRecord3(value.tags)) {
|
|
1975
|
+
endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]));
|
|
1976
|
+
}
|
|
1977
|
+
if (typeof value.account === "string")
|
|
1978
|
+
endpoint.tags = { ...endpoint.tags, account: value.account };
|
|
1979
|
+
if (isRecord3(value.headers)) {
|
|
1980
|
+
endpoint.headers = Object.fromEntries(Object.entries(value.headers).map(([k, v]) => [k, String(v)]));
|
|
1981
|
+
}
|
|
1982
|
+
return endpoint;
|
|
1983
|
+
};
|
|
1984
|
+
var webhookAdminRoutes = (hub) => ({
|
|
1985
|
+
"GET /webhooks": ({ url, namespace }) => json3(200, {
|
|
1986
|
+
deliveries: hub.deliveries(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((d) => {
|
|
1987
|
+
const type = url.searchParams.get("type");
|
|
1988
|
+
return type === null || d.type === type;
|
|
1989
|
+
})
|
|
1990
|
+
}),
|
|
1991
|
+
"GET /webhooks/events": ({ url, namespace }) => {
|
|
1992
|
+
const type = url.searchParams.get("type");
|
|
1993
|
+
return json3(200, {
|
|
1994
|
+
events: hub.messages(url.searchParams.get("all") === "1" ? void 0 : namespace).filter((m) => type === null || m.type === type).map((m) => ({ ...m, payload: parsePayload(m) }))
|
|
1995
|
+
});
|
|
1996
|
+
},
|
|
1997
|
+
"POST /webhooks/:id/replay": async ({ params }) => {
|
|
1998
|
+
const replayed = await hub.replay(params.id);
|
|
1999
|
+
return replayed ? json3(200, replayed) : adminError2(404, `no delivery ${params.id}`);
|
|
2000
|
+
},
|
|
2001
|
+
"POST /webhooks/flush": async () => {
|
|
2002
|
+
await hub.flush();
|
|
2003
|
+
return json3(200, { status: "ok" });
|
|
2004
|
+
},
|
|
2005
|
+
"POST /webhooks/faults": ({ body, namespace }) => {
|
|
2006
|
+
if (!isRecord3(body) || !["duplicate", "reorder", "drop"].includes(String(body.mode))) {
|
|
2007
|
+
return adminError2(400, "mode must be duplicate, reorder or drop");
|
|
2008
|
+
}
|
|
2009
|
+
const fault = { mode: body.mode };
|
|
2010
|
+
if (typeof body.count === "number")
|
|
2011
|
+
fault.count = body.count;
|
|
2012
|
+
hub.fault(namespace, fault);
|
|
2013
|
+
return json3(201, { namespace, ...fault });
|
|
2014
|
+
},
|
|
2015
|
+
"GET /webhook-endpoints": ({ namespace }) => json3(200, {
|
|
2016
|
+
endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({
|
|
2017
|
+
...rest,
|
|
2018
|
+
secret: secret ? "(set)" : null
|
|
2019
|
+
}))
|
|
2020
|
+
}),
|
|
2021
|
+
"PUT /webhook-endpoints": ({ body, namespace }) => {
|
|
2022
|
+
const list2 = Array.isArray(body) ? body : isRecord3(body) ? body.endpoints : void 0;
|
|
2023
|
+
if (!Array.isArray(list2))
|
|
2024
|
+
return adminError2(400, "expected [{url, secret?, events?}]");
|
|
2025
|
+
const parsed = [];
|
|
2026
|
+
for (const each of list2) {
|
|
2027
|
+
const endpoint = parseEndpoint(each);
|
|
2028
|
+
if (typeof endpoint === "string")
|
|
2029
|
+
return adminError2(400, endpoint);
|
|
2030
|
+
parsed.push(endpoint);
|
|
2031
|
+
}
|
|
2032
|
+
const set = hub.setEndpoints(namespace, parsed);
|
|
2033
|
+
return json3(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? "(set)" : null })) });
|
|
2034
|
+
},
|
|
2035
|
+
"DELETE /webhook-endpoints": ({ namespace }) => {
|
|
2036
|
+
hub.setEndpoints(namespace, []);
|
|
2037
|
+
return json3(200, { status: "ok" });
|
|
2038
|
+
}
|
|
2039
|
+
});
|
|
2040
|
+
var parsePayload = (message) => {
|
|
2041
|
+
if (message.contentType.startsWith("application/json")) {
|
|
2042
|
+
try {
|
|
2043
|
+
return JSON.parse(message.body);
|
|
2044
|
+
} catch {
|
|
2045
|
+
return message.body;
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
2048
|
+
if (message.contentType.startsWith("application/x-www-form-urlencoded")) {
|
|
2049
|
+
return Object.fromEntries(new URLSearchParams(message.body));
|
|
2050
|
+
}
|
|
2051
|
+
return message.body;
|
|
2052
|
+
};
|
|
2053
|
+
|
|
2054
|
+
// ../core/dist/runtime.js
|
|
2055
|
+
var MOCKINGBIRD_HEADER = "x-mockingbird";
|
|
2056
|
+
var BRANCH_HEADER = "x-mockingbird-branch";
|
|
2057
|
+
var AT_HEADER = "x-mockingbird-at";
|
|
2058
|
+
var CHECKPOINT_HEADER = "x-mockingbird-checkpoint";
|
|
2059
|
+
var DEFAULT_NAMESPACE = "default";
|
|
2060
|
+
var NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
2061
|
+
var PATH_PREFIX = /^\/ns\/([^/]+)(\/.*)?$/;
|
|
2062
|
+
var BRANCH_PATTERN2 = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
2063
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
2064
|
+
var effects = /* @__PURE__ */ new WeakMap();
|
|
2065
|
+
var reuseSorted = (fresh, previous, compare, equal) => {
|
|
2066
|
+
if (!previous || previous.length === 0)
|
|
2067
|
+
return fresh.map((row) => Object.freeze(row));
|
|
2068
|
+
const result = new Array(fresh.length);
|
|
2069
|
+
let unchanged = fresh.length === previous.length;
|
|
2070
|
+
let oldIndex = 0;
|
|
2071
|
+
for (let index = 0; index < fresh.length; index++) {
|
|
2072
|
+
const row = fresh[index];
|
|
2073
|
+
while (oldIndex < previous.length && compare(previous[oldIndex], row) < 0) {
|
|
2074
|
+
oldIndex++;
|
|
2075
|
+
}
|
|
2076
|
+
const old = previous[oldIndex];
|
|
2077
|
+
result[index] = old !== void 0 && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row);
|
|
2078
|
+
if (result[index] !== previous[index])
|
|
2079
|
+
unchanged = false;
|
|
2080
|
+
}
|
|
2081
|
+
return unchanged ? previous : result;
|
|
2082
|
+
};
|
|
2083
|
+
var DroppedConnectionError = class extends TypeError {
|
|
2084
|
+
code = "MOCKINGBIRD_DROP";
|
|
2085
|
+
constructor() {
|
|
2086
|
+
super("fetch failed: connection dropped by Mockingbird fault");
|
|
2087
|
+
this.name = "TypeError";
|
|
2088
|
+
}
|
|
2089
|
+
};
|
|
2090
|
+
var operationMatcher = (document2) => {
|
|
2091
|
+
const matchers = listOperations(document2).map((operation) => ({
|
|
2092
|
+
operationId: operation.operationId,
|
|
2093
|
+
method: operation.method.toUpperCase(),
|
|
2094
|
+
pattern: new RegExp(`^${operation.path.split("/").map((segment) => segment.startsWith("{") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/")}/?$`),
|
|
2095
|
+
params: (operation.path.match(/\{/g) ?? []).length
|
|
2096
|
+
})).sort((a, b) => a.params - b.params);
|
|
2097
|
+
return (request, path) => matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId;
|
|
2098
|
+
};
|
|
2099
|
+
var createRuntime = (options) => {
|
|
2100
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
2101
|
+
const clock = options.clock ?? createClock();
|
|
2102
|
+
const rng = createRng(options.seed ?? 0);
|
|
2103
|
+
const wallNow = options.io?.wallNow ?? Date.now;
|
|
2104
|
+
const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
|
|
2105
|
+
const sleep = options.io?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
2106
|
+
const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep);
|
|
2107
|
+
const metrics = createMetrics();
|
|
2108
|
+
const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE);
|
|
2109
|
+
const version = options.version ?? PACKAGE_VERSION;
|
|
2110
|
+
const instances = /* @__PURE__ */ new Map();
|
|
2111
|
+
const publicNamespaces = /* @__PURE__ */ new Set();
|
|
2112
|
+
const branchRngs = /* @__PURE__ */ new Map();
|
|
2113
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
2114
|
+
const branchStorage = /* @__PURE__ */ new Map();
|
|
2115
|
+
const captured = /* @__PURE__ */ new Map();
|
|
2116
|
+
const credentials = createCredentialRegistry();
|
|
2117
|
+
const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
|
|
2118
|
+
const storageNamespace = (name) => name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`;
|
|
2119
|
+
const instanceFor = (key, publicNamespace = key, isolatedRng) => {
|
|
2120
|
+
const existing = instances.get(key);
|
|
2121
|
+
if (existing)
|
|
2122
|
+
return existing;
|
|
2123
|
+
if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {
|
|
2124
|
+
throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`);
|
|
2125
|
+
}
|
|
2126
|
+
const created = options.create({
|
|
2127
|
+
namespace: storageNamespace(key),
|
|
2128
|
+
publicNamespace,
|
|
2129
|
+
sqlite,
|
|
2130
|
+
clock,
|
|
2131
|
+
rng: isolatedRng ?? rng
|
|
2132
|
+
});
|
|
2133
|
+
instances.set(key, created);
|
|
2134
|
+
publicNamespaces.add(publicNamespace);
|
|
2135
|
+
if (isolatedRng)
|
|
2136
|
+
branchRngs.set(key, isolatedRng);
|
|
2137
|
+
return created;
|
|
2138
|
+
};
|
|
2139
|
+
const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
|
|
2140
|
+
const capture = (storage) => {
|
|
2141
|
+
const fresh = snapshotNamespace(sqlite, storageNamespace(storage));
|
|
2142
|
+
const previous = captured.get(storage);
|
|
2143
|
+
const snapshot2 = {
|
|
2144
|
+
namespace: fresh.namespace,
|
|
2145
|
+
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),
|
|
2146
|
+
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)
|
|
2147
|
+
};
|
|
2148
|
+
Object.freeze(snapshot2.records);
|
|
2149
|
+
Object.freeze(snapshot2.sequences);
|
|
2150
|
+
Object.freeze(snapshot2);
|
|
2151
|
+
captured.set(storage, snapshot2);
|
|
2152
|
+
return Object.freeze({
|
|
2153
|
+
snapshot: snapshot2,
|
|
2154
|
+
clock: Object.freeze(clock.state()),
|
|
2155
|
+
rngState: (branchRngs.get(storage) ?? rng).state()
|
|
2156
|
+
});
|
|
2157
|
+
};
|
|
2158
|
+
const timeline = (name = DEFAULT_NAMESPACE) => {
|
|
2159
|
+
let found = timelines.get(name);
|
|
2160
|
+
if (found)
|
|
2161
|
+
return found;
|
|
2162
|
+
instance(name);
|
|
2163
|
+
found = new Timeline({
|
|
2164
|
+
now: clock.now,
|
|
2165
|
+
...options.maxCheckpoints !== void 0 ? { maxCheckpoints: options.maxCheckpoints } : {}
|
|
2166
|
+
});
|
|
2167
|
+
found.commit(capture(name));
|
|
2168
|
+
timelines.set(name, found);
|
|
2169
|
+
return found;
|
|
2170
|
+
};
|
|
2171
|
+
const physicalBranch = (namespace, branch2) => {
|
|
2172
|
+
if (branch2 === "main")
|
|
2173
|
+
return namespace;
|
|
2174
|
+
const mapKey = `${namespace}\0${branch2}`;
|
|
2175
|
+
const existing = branchStorage.get(mapKey);
|
|
2176
|
+
if (existing)
|
|
2177
|
+
return existing;
|
|
2178
|
+
const key = `branch_${seedFrom(`${options.name}\0${namespace}\0${branch2}`).toString(36)}`;
|
|
2179
|
+
branchStorage.set(mapKey, key);
|
|
2180
|
+
return key;
|
|
2181
|
+
};
|
|
2182
|
+
const ensureBranch = (namespace, branch2, at) => {
|
|
2183
|
+
if (!BRANCH_PATTERN2.test(branch2))
|
|
2184
|
+
throw new RangeError(`branch must match ${BRANCH_PATTERN2}`);
|
|
2185
|
+
const history = timeline(namespace);
|
|
2186
|
+
if (branch2 === "main") {
|
|
2187
|
+
if (at !== void 0) {
|
|
2188
|
+
const point = history.checkout("main", at);
|
|
2189
|
+
restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot);
|
|
2190
|
+
captured.set(namespace, point.value.snapshot);
|
|
2191
|
+
rng.setState(point.value.rngState);
|
|
2192
|
+
clock.set(point.value.clock.now);
|
|
2193
|
+
if (point.value.clock.frozen)
|
|
2194
|
+
clock.freeze();
|
|
2195
|
+
else
|
|
2196
|
+
clock.unfreeze();
|
|
2197
|
+
}
|
|
2198
|
+
return namespace;
|
|
2199
|
+
}
|
|
2200
|
+
const storage = physicalBranch(namespace, branch2);
|
|
2201
|
+
if (!history.hasBranch(branch2)) {
|
|
2202
|
+
if (at === void 0)
|
|
2203
|
+
history.commit(capture(namespace));
|
|
2204
|
+
const point = history.fork(branch2, at === void 0 ? {} : { from: at });
|
|
2205
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
2206
|
+
if (point)
|
|
2207
|
+
branchRng.setState(point.value.rngState);
|
|
2208
|
+
instanceFor(storage, namespace, branchRng);
|
|
2209
|
+
if (point)
|
|
2210
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2211
|
+
if (point)
|
|
2212
|
+
captured.set(storage, point.value.snapshot);
|
|
2213
|
+
} else if (at !== void 0 && history.head(branch2)?.id !== at) {
|
|
2214
|
+
const point = history.checkout(branch2, at);
|
|
2215
|
+
if (!instances.has(storage)) {
|
|
2216
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
2217
|
+
branchRng.setState(point.value.rngState);
|
|
2218
|
+
instanceFor(storage, namespace, branchRng);
|
|
2219
|
+
}
|
|
2220
|
+
branchRngs.get(storage)?.setState(point.value.rngState);
|
|
2221
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2222
|
+
captured.set(storage, point.value.snapshot);
|
|
2223
|
+
} else {
|
|
2224
|
+
if (!instances.has(storage)) {
|
|
2225
|
+
const point = history.head(branch2);
|
|
2226
|
+
const branchRng = createRng(options.seed ?? 0);
|
|
2227
|
+
if (point)
|
|
2228
|
+
branchRng.setState(point.value.rngState);
|
|
2229
|
+
instanceFor(storage, namespace, branchRng);
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
return storage;
|
|
2233
|
+
};
|
|
2234
|
+
const checkpoint = (namespace = DEFAULT_NAMESPACE, branch2 = "main") => {
|
|
2235
|
+
const storage = ensureBranch(namespace, branch2);
|
|
2236
|
+
return timeline(namespace).commit(capture(storage), { branch: branch2 });
|
|
2237
|
+
};
|
|
2238
|
+
const branch = (name, branchOptions = {}) => {
|
|
2239
|
+
const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
2240
|
+
ensureBranch(namespace, name, branchOptions.at);
|
|
2241
|
+
const head = timeline(namespace).head(name);
|
|
2242
|
+
if (!head)
|
|
2243
|
+
throw new RangeError(`branch ${name} has no checkpoint`);
|
|
2244
|
+
return head;
|
|
2245
|
+
};
|
|
2246
|
+
const checkout = (checkpointId, checkoutOptions = {}) => {
|
|
2247
|
+
const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE;
|
|
2248
|
+
const branchName = checkoutOptions.branch ?? "main";
|
|
2249
|
+
const history = timeline(namespace);
|
|
2250
|
+
const point = history.checkout(branchName, checkpointId);
|
|
2251
|
+
const storage = ensureBranch(namespace, branchName);
|
|
2252
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2253
|
+
captured.set(storage, point.value.snapshot);
|
|
2254
|
+
clock.set(point.value.clock.now);
|
|
2255
|
+
if (point.value.clock.frozen)
|
|
2256
|
+
clock.freeze();
|
|
2257
|
+
else
|
|
2258
|
+
clock.unfreeze();
|
|
2259
|
+
(branchRngs.get(storage) ?? rng).setState(point.value.rngState);
|
|
2260
|
+
};
|
|
2261
|
+
const reset = async (name = DEFAULT_NAMESPACE) => {
|
|
2262
|
+
if (name === "*") {
|
|
2263
|
+
options.webhooks?.clear();
|
|
2264
|
+
for (const each of instances.values())
|
|
2265
|
+
await each.reset();
|
|
2266
|
+
timelines.clear();
|
|
2267
|
+
branchStorage.clear();
|
|
2268
|
+
branchRngs.clear();
|
|
2269
|
+
captured.clear();
|
|
2270
|
+
return;
|
|
2271
|
+
}
|
|
2272
|
+
options.webhooks?.clear(name);
|
|
2273
|
+
const target = instances.get(name);
|
|
2274
|
+
if (target)
|
|
2275
|
+
await target.reset();
|
|
2276
|
+
else
|
|
2277
|
+
clearNamespace(sqlite, storageNamespace(name));
|
|
2278
|
+
for (const [mapping, storage] of branchStorage) {
|
|
2279
|
+
if (!mapping.startsWith(`${name}\0`))
|
|
2280
|
+
continue;
|
|
2281
|
+
const branchInstance = instances.get(storage);
|
|
2282
|
+
if (branchInstance)
|
|
2283
|
+
await branchInstance.reset();
|
|
2284
|
+
else
|
|
2285
|
+
clearNamespace(sqlite, storageNamespace(storage));
|
|
2286
|
+
branchStorage.delete(mapping);
|
|
2287
|
+
branchRngs.delete(storage);
|
|
2288
|
+
captured.delete(storage);
|
|
2289
|
+
}
|
|
2290
|
+
timelines.delete(name);
|
|
2291
|
+
captured.delete(name);
|
|
2292
|
+
};
|
|
2293
|
+
const snapshot = (name = DEFAULT_NAMESPACE) => {
|
|
2294
|
+
return checkpoint(name, "main").value.snapshot;
|
|
2295
|
+
};
|
|
2296
|
+
const restore = (from, name = DEFAULT_NAMESPACE) => {
|
|
2297
|
+
instance(name);
|
|
2298
|
+
restoreNamespace(sqlite, storageNamespace(name), from);
|
|
2299
|
+
captured.set(name, from);
|
|
2300
|
+
const history = timelines.get(name);
|
|
2301
|
+
if (history)
|
|
2302
|
+
history.commit(capture(name), { branch: "main" });
|
|
2303
|
+
else
|
|
2304
|
+
timeline(name);
|
|
2305
|
+
};
|
|
2306
|
+
const runtime = {
|
|
2307
|
+
name: options.name,
|
|
2308
|
+
sqlite,
|
|
2309
|
+
clock,
|
|
2310
|
+
faults,
|
|
2311
|
+
metrics,
|
|
2312
|
+
journal,
|
|
2313
|
+
rng,
|
|
2314
|
+
credentials,
|
|
2315
|
+
webhooks: options.webhooks,
|
|
2316
|
+
applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {
|
|
2317
|
+
const preset = options.presets?.[name];
|
|
2318
|
+
if (!preset)
|
|
2319
|
+
throw new RangeError(`no fault preset ${JSON.stringify(name)}`);
|
|
2320
|
+
const added = (preset.rules ?? []).map((rule, index) => faults.add({
|
|
2321
|
+
namespace,
|
|
2322
|
+
...rule,
|
|
2323
|
+
...overrides,
|
|
2324
|
+
preset: name,
|
|
2325
|
+
id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : ""}`
|
|
2326
|
+
}));
|
|
2327
|
+
if (preset.webhook && options.webhooks) {
|
|
2328
|
+
options.webhooks.fault(namespace, {
|
|
2329
|
+
...preset.webhook,
|
|
2330
|
+
...overrides.count !== void 0 ? { count: overrides.count } : {}
|
|
2331
|
+
});
|
|
2332
|
+
}
|
|
2333
|
+
return added;
|
|
2334
|
+
},
|
|
2335
|
+
instance,
|
|
2336
|
+
namespaces: () => [...publicNamespaces].sort(),
|
|
2337
|
+
reset,
|
|
2338
|
+
snapshot,
|
|
2339
|
+
restore,
|
|
2340
|
+
checkpoint,
|
|
2341
|
+
branch,
|
|
2342
|
+
checkout,
|
|
2343
|
+
timeline,
|
|
2344
|
+
fetch: async (incoming) => {
|
|
2345
|
+
let request = incoming;
|
|
2346
|
+
const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname);
|
|
2347
|
+
if (prefixed) {
|
|
2348
|
+
const url2 = new URL(request.url);
|
|
2349
|
+
url2.pathname = prefixed[2] ?? "/";
|
|
2350
|
+
const headers = new Headers(request.headers);
|
|
2351
|
+
if (!headers.has(NAMESPACE_HEADER)) {
|
|
2352
|
+
headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
|
|
2353
|
+
}
|
|
2354
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD";
|
|
2355
|
+
request = new Request(url2, {
|
|
2356
|
+
method: request.method,
|
|
2357
|
+
headers,
|
|
2358
|
+
...hasBody ? { body: await request.arrayBuffer() } : {},
|
|
2359
|
+
signal: request.signal
|
|
2360
|
+
});
|
|
2361
|
+
}
|
|
2362
|
+
let namespace = control.namespaceOf(request);
|
|
2363
|
+
if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {
|
|
2364
|
+
const credential = options.credential(request);
|
|
2365
|
+
const mapped = credential !== void 0 ? credentials.get(credential) : void 0;
|
|
2366
|
+
if (mapped !== void 0)
|
|
2367
|
+
namespace = mapped;
|
|
2368
|
+
}
|
|
2369
|
+
const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
|
|
2370
|
+
const at = request.headers.get(AT_HEADER) ?? void 0;
|
|
2371
|
+
const stamp = (response2) => {
|
|
2372
|
+
const value = NAMESPACE_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
|
|
2373
|
+
try {
|
|
2374
|
+
response2.headers.set(MOCKINGBIRD_HEADER, value);
|
|
2375
|
+
return response2;
|
|
2376
|
+
} catch {
|
|
2377
|
+
const copy = new Response(response2.body, response2);
|
|
2378
|
+
copy.headers.set(MOCKINGBIRD_HEADER, value);
|
|
2379
|
+
return copy;
|
|
2380
|
+
}
|
|
2381
|
+
};
|
|
2382
|
+
const handled = await control.handle(request);
|
|
2383
|
+
if (handled)
|
|
2384
|
+
return stamp(handled);
|
|
2385
|
+
const started = monotonicNow();
|
|
2386
|
+
const url = new URL(request.url);
|
|
2387
|
+
const operationId = operationIdFor(request, url.pathname);
|
|
2388
|
+
const log = (status, faultId, response2) => {
|
|
2389
|
+
const noted = response2 ? responseNotes(response2) : void 0;
|
|
2390
|
+
const entry = {
|
|
2391
|
+
service: options.name,
|
|
2392
|
+
namespace,
|
|
2393
|
+
operationId,
|
|
2394
|
+
method: request.method,
|
|
2395
|
+
path: url.pathname,
|
|
2396
|
+
status,
|
|
2397
|
+
durationMs: Math.round((monotonicNow() - started) * 100) / 100,
|
|
2398
|
+
unmatched: options.document !== void 0 && operationId === void 0,
|
|
2399
|
+
...faultId !== void 0 ? { faultId } : {},
|
|
2400
|
+
...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
|
|
2401
|
+
...noted?.adopted ? { adopted: true } : {}
|
|
2402
|
+
};
|
|
2403
|
+
metrics.record(entry);
|
|
2404
|
+
journal.record({ ...entry, at: new Date(clock.now()).toISOString() });
|
|
2405
|
+
options.onLog?.(entry);
|
|
2406
|
+
};
|
|
2407
|
+
if (!NAMESPACE_PATTERN.test(namespace)) {
|
|
2408
|
+
log(400);
|
|
2409
|
+
return stamp(new Response(JSON.stringify({
|
|
2410
|
+
error: {
|
|
2411
|
+
type: "mockingbird_admin",
|
|
2412
|
+
message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`
|
|
2413
|
+
}
|
|
2414
|
+
}), { status: 400, headers: { "content-type": "application/json" } }));
|
|
2415
|
+
}
|
|
2416
|
+
if (!BRANCH_PATTERN2.test(selectedBranch)) {
|
|
2417
|
+
log(400);
|
|
2418
|
+
return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN2}`));
|
|
2419
|
+
}
|
|
2420
|
+
let storage;
|
|
2421
|
+
try {
|
|
2422
|
+
if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
|
|
2423
|
+
const point = timeline(namespace).get(at);
|
|
2424
|
+
storage = physicalBranch(namespace, `at_${at}`);
|
|
2425
|
+
let viewRng = branchRngs.get(storage);
|
|
2426
|
+
if (!viewRng) {
|
|
2427
|
+
viewRng = createRng(options.seed ?? 0);
|
|
2428
|
+
instanceFor(storage, namespace, viewRng);
|
|
2429
|
+
}
|
|
2430
|
+
viewRng.setState(point.value.rngState);
|
|
2431
|
+
restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot);
|
|
2432
|
+
captured.set(storage, point.value.snapshot);
|
|
2433
|
+
} else {
|
|
2434
|
+
storage = ensureBranch(namespace, selectedBranch, at);
|
|
2435
|
+
}
|
|
2436
|
+
} catch (error2) {
|
|
2437
|
+
log(409);
|
|
2438
|
+
return stamp(adminFail(409, error2 instanceof Error ? error2.message : String(error2)));
|
|
2439
|
+
}
|
|
2440
|
+
const hits = await faults.take({
|
|
2441
|
+
operationId,
|
|
2442
|
+
method: request.method,
|
|
2443
|
+
path: url.pathname,
|
|
2444
|
+
namespace
|
|
2445
|
+
});
|
|
2446
|
+
const final = hits.find((hit) => hit.drop || hit.response);
|
|
2447
|
+
if (final?.drop) {
|
|
2448
|
+
log(0, final.id);
|
|
2449
|
+
throw new DroppedConnectionError();
|
|
2450
|
+
}
|
|
2451
|
+
if (final?.response) {
|
|
2452
|
+
log(final.response.status, final.id);
|
|
2453
|
+
return stamp(final.response);
|
|
2454
|
+
}
|
|
2455
|
+
const fired = hits.filter((hit) => hit.effect !== void 0);
|
|
2456
|
+
if (fired.length > 0)
|
|
2457
|
+
effects.set(request, fired.map((hit) => hit.effect));
|
|
2458
|
+
let response = await instanceFor(storage, namespace).fetch(request);
|
|
2459
|
+
if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {
|
|
2460
|
+
const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
|
|
2461
|
+
response = mutableResponse(response);
|
|
2462
|
+
response.headers.set(CHECKPOINT_HEADER, point.id);
|
|
2463
|
+
}
|
|
2464
|
+
if (selectedBranch !== "main") {
|
|
2465
|
+
response = mutableResponse(response);
|
|
2466
|
+
response.headers.set(BRANCH_HEADER, selectedBranch);
|
|
2467
|
+
}
|
|
2468
|
+
if (at !== void 0) {
|
|
2469
|
+
response = mutableResponse(response);
|
|
2470
|
+
response.headers.set(AT_HEADER, at);
|
|
2471
|
+
}
|
|
2472
|
+
log(response.status, fired[0]?.id, response);
|
|
2473
|
+
return stamp(response);
|
|
2474
|
+
}
|
|
2475
|
+
};
|
|
2476
|
+
const control = createControlPlane({
|
|
2477
|
+
name: options.name,
|
|
2478
|
+
startedAt: wallNow(),
|
|
2479
|
+
wallNow,
|
|
2480
|
+
clock,
|
|
2481
|
+
faults,
|
|
2482
|
+
metrics,
|
|
2483
|
+
journal,
|
|
2484
|
+
defaultNamespace: DEFAULT_NAMESPACE,
|
|
2485
|
+
namespaces: runtime.namespaces,
|
|
2486
|
+
reset,
|
|
2487
|
+
timeTravel: {
|
|
2488
|
+
checkpoint: (name, branchName) => {
|
|
2489
|
+
const point = checkpoint(name, branchName);
|
|
2490
|
+
return {
|
|
2491
|
+
id: point.id,
|
|
2492
|
+
branch: point.branch,
|
|
2493
|
+
parent: point.parent,
|
|
2494
|
+
at: point.at,
|
|
2495
|
+
records: point.value.snapshot.records.length
|
|
2496
|
+
};
|
|
2497
|
+
},
|
|
2498
|
+
branch: (branchName, branchOptions) => {
|
|
2499
|
+
const point = branch(branchName, branchOptions);
|
|
2500
|
+
return { id: point.id, branch: point.branch, parent: point.parent, at: point.at };
|
|
2501
|
+
},
|
|
2502
|
+
checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),
|
|
2503
|
+
retain: (name, checkpointId) => {
|
|
2504
|
+
timeline(name).retain(checkpointId);
|
|
2505
|
+
},
|
|
2506
|
+
release: (name, checkpointId) => timeline(name).release(checkpointId),
|
|
2507
|
+
inspect: (name) => {
|
|
2508
|
+
const history = timeline(name);
|
|
2509
|
+
return {
|
|
2510
|
+
branches: history.branches(),
|
|
2511
|
+
checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({
|
|
2512
|
+
id,
|
|
2513
|
+
branch: branchName,
|
|
2514
|
+
parent,
|
|
2515
|
+
at
|
|
2516
|
+
}))
|
|
2517
|
+
};
|
|
2518
|
+
}
|
|
2519
|
+
},
|
|
2520
|
+
describe: options.describe ?? (() => ({})),
|
|
2521
|
+
...options.presets ? {
|
|
2522
|
+
applyPreset: (name, namespace, overrides) => runtime.applyPreset(name, namespace, overrides)
|
|
2523
|
+
} : {},
|
|
2524
|
+
routes: {
|
|
2525
|
+
...credentialRoutes(credentials),
|
|
2526
|
+
...options.presets ? presetRoutes(options.presets, runtime) : {},
|
|
2527
|
+
...options.webhooks ? webhookAdminRoutes(options.webhooks) : {},
|
|
2528
|
+
...options.admin?.(runtime) ?? {}
|
|
2529
|
+
},
|
|
2530
|
+
adminKey: options.adminKey
|
|
2531
|
+
});
|
|
2532
|
+
return runtime;
|
|
2533
|
+
};
|
|
2534
|
+
var mutableResponse = (response) => {
|
|
2535
|
+
try {
|
|
2536
|
+
response.headers.set("x-mockingbird-mutable-probe", "1");
|
|
2537
|
+
response.headers.delete("x-mockingbird-mutable-probe");
|
|
2538
|
+
return response;
|
|
2539
|
+
} catch {
|
|
2540
|
+
return new Response(response.body, response);
|
|
2541
|
+
}
|
|
2542
|
+
};
|
|
2543
|
+
var adminJson = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2544
|
+
var adminFail = (status, message) => adminJson(status, { error: { type: "mockingbird_admin", message } });
|
|
2545
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2546
|
+
var credentialRoutes = (registry) => ({
|
|
2547
|
+
"GET /credentials": () => adminJson(200, {
|
|
2548
|
+
credentials: registry.entries().map(({ credential, namespace }) => ({
|
|
2549
|
+
credential: maskCredential(credential),
|
|
2550
|
+
namespace
|
|
2551
|
+
}))
|
|
2552
|
+
}),
|
|
2553
|
+
"PUT /credentials": ({ body, namespace }) => {
|
|
2554
|
+
const pairs = [];
|
|
2555
|
+
const list2 = Array.isArray(body) ? body : isObject(body) ? body.credentials : void 0;
|
|
2556
|
+
if (Array.isArray(list2)) {
|
|
2557
|
+
for (const each of list2) {
|
|
2558
|
+
if (typeof each === "string")
|
|
2559
|
+
pairs.push([each, namespace]);
|
|
2560
|
+
else if (isObject(each) && typeof each.credential === "string") {
|
|
2561
|
+
pairs.push([
|
|
2562
|
+
each.credential,
|
|
2563
|
+
typeof each.namespace === "string" ? each.namespace : namespace
|
|
2564
|
+
]);
|
|
2565
|
+
} else
|
|
2566
|
+
return adminFail(400, "each entry is a credential string or {credential, namespace}");
|
|
2567
|
+
}
|
|
2568
|
+
} else if (isObject(list2)) {
|
|
2569
|
+
for (const [credential, target] of Object.entries(list2)) {
|
|
2570
|
+
if (typeof target !== "string")
|
|
2571
|
+
return adminFail(400, `namespace for ${credential} must be a string`);
|
|
2572
|
+
pairs.push([credential, target]);
|
|
2573
|
+
}
|
|
2574
|
+
} else if (isObject(body) && typeof body.credential === "string") {
|
|
2575
|
+
pairs.push([body.credential, typeof body.namespace === "string" ? body.namespace : namespace]);
|
|
2576
|
+
} else {
|
|
2577
|
+
return adminFail(400, 'expected {"credentials": {"<credential>": "<namespace>"}}');
|
|
2578
|
+
}
|
|
2579
|
+
for (const [credential, target] of pairs) {
|
|
2580
|
+
if (!NAMESPACE_PATTERN.test(target))
|
|
2581
|
+
return adminFail(400, `bad namespace ${JSON.stringify(target)}`);
|
|
2582
|
+
registry.set(credential, target);
|
|
2583
|
+
}
|
|
2584
|
+
return adminJson(200, { mapped: pairs.length });
|
|
2585
|
+
},
|
|
2586
|
+
"DELETE /credentials": ({ url }) => {
|
|
2587
|
+
const credential = url.searchParams.get("credential");
|
|
2588
|
+
if (credential === null)
|
|
2589
|
+
registry.clear();
|
|
2590
|
+
else
|
|
2591
|
+
registry.remove(credential);
|
|
2592
|
+
return adminJson(200, { status: "ok" });
|
|
2593
|
+
}
|
|
2594
|
+
});
|
|
2595
|
+
var presetRoutes = (presets, runtime) => ({
|
|
2596
|
+
"GET /faults/presets": () => adminJson(200, {
|
|
2597
|
+
presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset }))
|
|
2598
|
+
}),
|
|
2599
|
+
"POST /faults/presets/:name": ({ params, body, namespace }) => {
|
|
2600
|
+
const name = params.name;
|
|
2601
|
+
if (!presets[name])
|
|
2602
|
+
return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`);
|
|
2603
|
+
const overrides = isObject(body) ? body : {};
|
|
2604
|
+
return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) });
|
|
2605
|
+
}
|
|
2606
|
+
});
|
|
2607
|
+
|
|
2608
|
+
// ../core/dist/validation.js
|
|
2609
|
+
var bodyIssues = (context, contentType = "application/json") => {
|
|
2610
|
+
const requestBody = context.operation.operation.requestBody;
|
|
2611
|
+
if (!requestBody)
|
|
2612
|
+
return [];
|
|
2613
|
+
const resolved = deref(context.document, requestBody);
|
|
2614
|
+
const schema = resolved.content?.[contentType]?.schema;
|
|
2615
|
+
if (!schema)
|
|
2616
|
+
return [];
|
|
2617
|
+
const value = context.body.kind === "json" || context.body.kind === "form" ? context.body.value : void 0;
|
|
2618
|
+
if (context.body.kind === "invalid") {
|
|
2619
|
+
return [{ path: "", message: `request body is not valid ${context.body.mediaType}` }];
|
|
2620
|
+
}
|
|
2621
|
+
if (value === void 0) {
|
|
2622
|
+
return resolved.required ? [{ path: "", message: "request body is required" }] : [];
|
|
2623
|
+
}
|
|
2624
|
+
return validateValue(context.document, resolveSchema(context.document, schema), value).map((issue) => ({ path: issue.path.join("."), message: issue.message }));
|
|
2625
|
+
};
|
|
2626
|
+
|
|
2627
|
+
// src/generated/openapi.ts
|
|
2628
|
+
var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Resend API (Mockingbird subset)","description":"Stateful mock subset of the Resend email API: send (with \`Idempotency-Key\`), retrieve a sent\\nemail, and the received-email (inbound) endpoints our care-chat hydration reads, including\\nthe attachment download URL. Trimmed from Resend's published API reference to what\\n\`resend@4.8.0\` and our backend call.\\n","version":"1","x-mockingbird-upstream":{"note":"Trimmed from https://resend.com/docs/api-reference (emails/send-email, emails/retrieve-email, receiving/retrieve-received-email, receiving/list-attachments); request/response shapes cross-checked against resend@4.8.0 (dist/index.mjs) and our consumer (send-emails.service.ts, notification-dispatcher email.ts, resend-inbound-email.client.ts)."}},"servers":[{"url":"https://api.resend.com"}],"security":[{"bearerAuth":[]}],"paths":{"/emails":{"post":{"operationId":"SendEmail","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"parameters":[{"name":"Idempotency-Key","in":"header","description":"Replays the first response for the same key and payload (1\u2013256 characters).","schema":{"type":"string","pattern":"^[!-~]{1,256}$"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendEmailBody"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"type":"object","required":["id"],"properties":{"id":{"type":"string","x-mockingbird-resource":{"type":"email","identity":true},"x-mockingbird-volatile":{"kind":"id"}}}}}}},"400":{"description":"Invalid idempotency key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"Missing API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"Idempotency key reused with another payload, or still in flight","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/emails/{email_id}":{"parameters":[{"name":"email_id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"email","missing":"00000000-0000-4000-8000-000000000000"}}}],"get":{"operationId":"GetEmail","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The sent email","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Email"}}}},"401":{"description":"Missing API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown email","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/emails/receiving/{email_id}":{"parameters":[{"$ref":"#/components/parameters/ReceivedEmailId"}],"get":{"operationId":"GetReceivedEmail","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The received email, with its content","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReceivedEmail"}}}},"401":{"description":"Missing API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown email","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/emails/receiving/{email_id}/attachments":{"parameters":[{"$ref":"#/components/parameters/ReceivedEmailId"}],"get":{"operationId":"ListReceivedEmailAttachments","x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Attachment metadata with short-lived download URLs","content":{"application/json":{"schema":{"type":"object","required":["object","data"],"properties":{"object":{"type":"string","enum":["list"]},"has_more":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/ReceivedAttachment"}}}}}}},"401":{"description":"Missing API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"Unknown email","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/downloads/inbound/{attachment_id}":{"get":{"operationId":"DownloadReceivedAttachment","description":"The \`download_url\` of a received attachment: unauthenticated (it stands in for Resend's signed CDN URL), the raw bytes with their content type and length.","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"attachment_id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"received_attachment","missing":"00000000-0000-4000-8000-000000000000"}}}],"responses":{"200":{"description":"The attachment bytes","content":{"application/octet-stream":{"schema":{"type":"string","format":"binary"}}}},"404":{"description":"Unknown attachment","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer","description":"\`Authorization: Bearer re_\u2026\`"}},"parameters":{"ReceivedEmailId":{"name":"email_id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"received_email","missing":"00000000-0000-4000-8000-000000000000"}}}},"schemas":{"Address":{"type":"string","description":"\`email@example.com\` or \`Name <email@example.com>\`","pattern":"^([^<>@]* <[A-Za-z0-9._+-]+@[A-Za-z0-9-]+(\\\\.[A-Za-z0-9-]+)+>|[A-Za-z0-9._+-]+@[A-Za-z0-9-]+(\\\\.[A-Za-z0-9-]+)+)$","maxLength":120},"Recipients":{"oneOf":[{"$ref":"#/components/schemas/Address"},{"type":"array","minItems":1,"maxItems":50,"items":{"$ref":"#/components/schemas/Address"}}]},"SendEmailBody":{"type":"object","required":["from","to","subject"],"properties":{"from":{"$ref":"#/components/schemas/Address"},"to":{"$ref":"#/components/schemas/Recipients"},"subject":{"type":"string","minLength":1,"maxLength":200},"html":{"type":"string","maxLength":5000},"text":{"type":"string","maxLength":5000},"cc":{"$ref":"#/components/schemas/Recipients"},"bcc":{"$ref":"#/components/schemas/Recipients"},"reply_to":{"$ref":"#/components/schemas/Recipients"},"scheduled_at":{"type":"string","maxLength":60},"headers":{"type":"object","additionalProperties":{"type":"string","maxLength":500}},"tags":{"type":"array","maxItems":10,"items":{"type":"object","required":["name","value"],"properties":{"name":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,256}$"},"value":{"type":"string","pattern":"^[A-Za-z0-9_-]{1,256}$"}}}},"attachments":{"type":"array","maxItems":5,"items":{"type":"object","properties":{"filename":{"type":"string","minLength":1,"maxLength":100},"content":{"description":"Base64 bytes (or a JSON-serialised Node Buffer).","oneOf":[{"type":"string","maxLength":10000},{"type":"object","required":["type","data"],"properties":{"type":{"type":"string","enum":["Buffer"]},"data":{"type":"array","maxItems":10000,"items":{"type":"integer","minimum":0,"maximum":255}}}}]},"path":{"type":"string","maxLength":500},"content_type":{"type":"string","maxLength":100},"inline_content_id":{"type":"string","maxLength":100}}}}}},"Email":{"type":"object","required":["object","id","to","from","created_at","subject","html","text","bcc","cc","reply_to","last_event"],"properties":{"object":{"type":"string","enum":["email"]},"id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}},"to":{"type":"array","items":{"type":"string"}},"from":{"type":"string"},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"subject":{"type":"string"},"html":{"type":["string","null"]},"text":{"type":["string","null"]},"bcc":{"type":["array","null"],"items":{"type":"string"}},"cc":{"type":["array","null"],"items":{"type":"string"}},"reply_to":{"type":["array","null"],"items":{"type":"string"}},"last_event":{"type":"string","enum":["delivered","scheduled"]},"scheduled_at":{"type":["string","null"]},"tags":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"value":{"type":"string"}}}}}},"ReceivedAttachment":{"type":"object","required":["id","filename","content_type","size","download_url"],"properties":{"id":{"type":"string","x-mockingbird-resource":{"type":"received_attachment","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"filename":{"type":"string"},"content_type":{"type":"string"},"content_disposition":{"type":["string","null"]},"content_id":{"type":["string","null"]},"size":{"type":"integer"},"download_url":{"type":"string","x-mockingbird-volatile":{"kind":"url"}},"expires_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}}}},"ReceivedEmail":{"type":"object","required":["object","id","to","from","created_at","subject","html","text","message_id","attachments"],"properties":{"object":{"type":"string","enum":["email"]},"id":{"type":"string","x-mockingbird-resource":{"type":"received_email","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"to":{"type":"array","items":{"type":"string"}},"from":{"type":"string"},"cc":{"type":"array","items":{"type":"string"}},"bcc":{"type":"array","items":{"type":"string"}},"reply_to":{"type":"array","items":{"type":"string"}},"created_at":{"type":"string","x-mockingbird-volatile":{"kind":"timestamp"}},"subject":{"type":["string","null"]},"html":{"type":["string","null"]},"text":{"type":["string","null"]},"headers":{"type":"object","additionalProperties":{"type":"string"}},"message_id":{"type":["string","null"]},"attachments":{"type":"array","items":{"type":"object","required":["id","filename","content_type"],"properties":{"id":{"type":"string"},"filename":{"type":"string"},"content_type":{"type":"string"},"content_disposition":{"type":["string","null"]},"content_id":{"type":["string","null"]}}}}}},"Error":{"type":"object","description":"Resend's error body; the SDK returns it verbatim as \`error\`.","required":["statusCode","name","message"],"properties":{"statusCode":{"type":"integer"},"name":{"type":"string"},"message":{"type":"string"}}}}}}`);
|
|
2629
|
+
var operationIds = ["SendEmail", "GetEmail", "GetReceivedEmail", "ListReceivedEmailAttachments", "DownloadReceivedAttachment"];
|
|
2630
|
+
var supportedOperationIds = ["SendEmail", "GetEmail", "GetReceivedEmail", "ListReceivedEmailAttachments", "DownloadReceivedAttachment"];
|
|
2631
|
+
|
|
2632
|
+
// src/state.ts
|
|
2633
|
+
var ResendState = class {
|
|
2634
|
+
outbox;
|
|
2635
|
+
received;
|
|
2636
|
+
/** Attachment id → received email id, for the unauthenticated download URL. */
|
|
2637
|
+
attachmentIndex;
|
|
2638
|
+
idempotency;
|
|
2639
|
+
ids;
|
|
2640
|
+
constructor(sqlite, namespace) {
|
|
2641
|
+
this.outbox = new OutboxStore(sqlite, namespace, "outbox");
|
|
2642
|
+
this.received = new Collection(sqlite, namespace, "received");
|
|
2643
|
+
this.attachmentIndex = new Collection(sqlite, namespace, "attachment_index");
|
|
2644
|
+
this.idempotency = new IdempotencyStore(sqlite, namespace);
|
|
2645
|
+
this.ids = new IdSequence(sqlite, namespace, "resend");
|
|
2646
|
+
}
|
|
2647
|
+
/** A UUID-shaped id, deterministic for a given history (Resend ids are UUIDs). */
|
|
2648
|
+
nextId(kind) {
|
|
2649
|
+
const token = this.ids.next(`${kind}_`, 32).slice(kind.length + 1);
|
|
2650
|
+
const hex = [...token].map((c) => (c.charCodeAt(0) % 16).toString(16)).join("");
|
|
2651
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
|
|
2652
|
+
}
|
|
2653
|
+
};
|
|
2654
|
+
|
|
2655
|
+
// src/runtime.ts
|
|
2656
|
+
var RESEND_PRESETS = {
|
|
2657
|
+
send_422: {
|
|
2658
|
+
description: "Send answers 422 validation_error (the SDK returns it as error; sendEmail throws)",
|
|
2659
|
+
rules: [
|
|
2660
|
+
{
|
|
2661
|
+
operationId: "SendEmail",
|
|
2662
|
+
status: 422,
|
|
2663
|
+
body: {
|
|
2664
|
+
statusCode: 422,
|
|
2665
|
+
name: "validation_error",
|
|
2666
|
+
message: "Invalid `to` field. The email address needs to follow the `email@example.com` or `Name <email@example.com>` format."
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
]
|
|
2670
|
+
},
|
|
2671
|
+
send_429: {
|
|
2672
|
+
description: "Send answers 429 rate_limit_exceeded, with Resend's rate-limit headers",
|
|
2673
|
+
rules: [
|
|
2674
|
+
{
|
|
2675
|
+
operationId: "SendEmail",
|
|
2676
|
+
status: 429,
|
|
2677
|
+
headers: {
|
|
2678
|
+
"retry-after": "1",
|
|
2679
|
+
"ratelimit-limit": "2",
|
|
2680
|
+
"ratelimit-remaining": "0",
|
|
2681
|
+
"ratelimit-reset": "1"
|
|
2682
|
+
},
|
|
2683
|
+
body: {
|
|
2684
|
+
statusCode: 429,
|
|
2685
|
+
name: "rate_limit_exceeded",
|
|
2686
|
+
message: "Too many requests. You can only make 2 requests per second. See rate limit response headers for more information. Or contact support to increase rate limit."
|
|
2687
|
+
}
|
|
2688
|
+
}
|
|
2689
|
+
]
|
|
2690
|
+
},
|
|
2691
|
+
send_500: {
|
|
2692
|
+
description: "Send answers a JSON 500 internal_server_error",
|
|
2693
|
+
rules: [
|
|
2694
|
+
{
|
|
2695
|
+
operationId: "SendEmail",
|
|
2696
|
+
status: 500,
|
|
2697
|
+
body: {
|
|
2698
|
+
statusCode: 500,
|
|
2699
|
+
name: "internal_server_error",
|
|
2700
|
+
message: "An unexpected error occurred."
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
]
|
|
2704
|
+
},
|
|
2705
|
+
non_json_500: {
|
|
2706
|
+
description: "Send answers a 500 HTML page (the SDK reports application_error)",
|
|
2707
|
+
rules: [
|
|
2708
|
+
{
|
|
2709
|
+
operationId: "SendEmail",
|
|
2710
|
+
status: 500,
|
|
2711
|
+
headers: { "content-type": "text/html; charset=utf-8" },
|
|
2712
|
+
body: "<html><head><title>500 Internal Server Error</title></head><body><h1>Internal Server Error</h1></body></html>"
|
|
2713
|
+
}
|
|
2714
|
+
]
|
|
2715
|
+
},
|
|
2716
|
+
network_drop: {
|
|
2717
|
+
description: "Send drops the connection before answering (the SDK reports 'Unable to fetch data')",
|
|
2718
|
+
rules: [{ operationId: "SendEmail", drop: true }]
|
|
2719
|
+
},
|
|
2720
|
+
receiving_500: {
|
|
2721
|
+
description: "The received-email endpoints answer 500 (our hydration throws 'could not be retrieved')",
|
|
2722
|
+
rules: [
|
|
2723
|
+
{
|
|
2724
|
+
pathPrefix: "/emails/receiving",
|
|
2725
|
+
status: 500,
|
|
2726
|
+
body: {
|
|
2727
|
+
statusCode: 500,
|
|
2728
|
+
name: "internal_server_error",
|
|
2729
|
+
message: "An unexpected error occurred."
|
|
2730
|
+
}
|
|
2731
|
+
}
|
|
2732
|
+
]
|
|
2733
|
+
},
|
|
2734
|
+
webhook_duplicate: {
|
|
2735
|
+
description: "The next email.received webhook is delivered twice",
|
|
2736
|
+
webhook: { mode: "duplicate" }
|
|
2737
|
+
},
|
|
2738
|
+
webhook_reorder: {
|
|
2739
|
+
description: "The next two email.received webhooks arrive swapped",
|
|
2740
|
+
webhook: { mode: "reorder" }
|
|
2741
|
+
},
|
|
2742
|
+
webhook_drop: {
|
|
2743
|
+
description: "The next email.received webhook is never delivered",
|
|
2744
|
+
webhook: { mode: "drop" }
|
|
2745
|
+
}
|
|
2746
|
+
};
|
|
2747
|
+
var forwardToInbox = async (target, email, namespace) => {
|
|
2748
|
+
const send = target.fetch ?? ((request) => fetch(request));
|
|
2749
|
+
const response = await send(
|
|
2750
|
+
new Request(`${target.url.replace(/\/$/, "")}/__admin/ingest`, {
|
|
2751
|
+
method: "POST",
|
|
2752
|
+
headers: {
|
|
2753
|
+
"content-type": "application/json",
|
|
2754
|
+
"x-mockingbird-namespace": namespace,
|
|
2755
|
+
...target.adminKey ? { "x-mockingbird-admin-key": target.adminKey } : {}
|
|
2756
|
+
},
|
|
2757
|
+
body: JSON.stringify({
|
|
2758
|
+
from: email.from,
|
|
2759
|
+
to: email.toHeader,
|
|
2760
|
+
cc: email.cc,
|
|
2761
|
+
bcc: email.bcc,
|
|
2762
|
+
subject: email.subject,
|
|
2763
|
+
html: email.html,
|
|
2764
|
+
text: email.text,
|
|
2765
|
+
headers: email.headers
|
|
2766
|
+
}),
|
|
2767
|
+
signal: AbortSignal.timeout(target.timeoutMs ?? 2e3)
|
|
2768
|
+
})
|
|
2769
|
+
);
|
|
2770
|
+
await response.body?.cancel();
|
|
2771
|
+
return response.ok;
|
|
2772
|
+
};
|
|
2773
|
+
var json4 = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
2774
|
+
var adminError3 = (status, message) => json4(status, { error: { type: "mockingbird_admin", message } });
|
|
2775
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2776
|
+
var isAddressList = (value) => typeof value === "string" || Array.isArray(value) && value.every((v) => typeof v === "string");
|
|
2777
|
+
var inboundInput = (body) => {
|
|
2778
|
+
if (!isRecord4(body)) return "expected a JSON object";
|
|
2779
|
+
if (typeof body.from !== "string" || body.from === "") return "from: the sender address";
|
|
2780
|
+
if (!isAddressList(body.to) || Array.isArray(body.to) && body.to.length === 0) {
|
|
2781
|
+
return "to: a recipient address or a non-empty list of them";
|
|
2782
|
+
}
|
|
2783
|
+
for (const key of ["cc", "bcc", "replyTo"]) {
|
|
2784
|
+
if (body[key] !== void 0 && !isAddressList(body[key])) return `${key}: an address or a list`;
|
|
2785
|
+
}
|
|
2786
|
+
for (const key of ["subject", "text", "html", "messageId"]) {
|
|
2787
|
+
if (body[key] !== void 0 && body[key] !== null && typeof body[key] !== "string") {
|
|
2788
|
+
return `${key}: a string`;
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
2791
|
+
if (body.headers !== void 0 && !isRecord4(body.headers)) return "headers: {name: value}";
|
|
2792
|
+
if (body.attachments !== void 0) {
|
|
2793
|
+
if (!Array.isArray(body.attachments) || body.attachments.some(
|
|
2794
|
+
(a) => !isRecord4(a) || typeof a.filename !== "string" || typeof a.content !== "string"
|
|
2795
|
+
)) {
|
|
2796
|
+
return "attachments: [{filename, content (base64), contentType?, contentId?}]";
|
|
2797
|
+
}
|
|
2798
|
+
}
|
|
2799
|
+
return body;
|
|
2800
|
+
};
|
|
2801
|
+
var adminRoutes = (hub) => (runtime) => ({
|
|
2802
|
+
...outboxAdminRoutes(
|
|
2803
|
+
runtime,
|
|
2804
|
+
(api) => api.state.outbox,
|
|
2805
|
+
(params) => {
|
|
2806
|
+
const tag = params.get("tag");
|
|
2807
|
+
if (tag === null) return void 0;
|
|
2808
|
+
const colon = tag.indexOf(":");
|
|
2809
|
+
const name = colon < 0 ? tag : tag.slice(0, colon);
|
|
2810
|
+
const value = colon < 0 ? void 0 : tag.slice(colon + 1);
|
|
2811
|
+
return (item) => (item.tags ?? []).some(
|
|
2812
|
+
(t) => t.name === name && (value === void 0 || t.value === value)
|
|
2813
|
+
);
|
|
2814
|
+
}
|
|
2815
|
+
),
|
|
2816
|
+
"GET /outbox/:id/links": ({ params, namespace }) => {
|
|
2817
|
+
const email = runtime.instance(namespace).state.outbox.get(params.id);
|
|
2818
|
+
if (!email) return adminError3(404, `no email ${params.id}`);
|
|
2819
|
+
const links = email.html ? extractLinks(email.html) : [...(email.text ?? "").matchAll(/\bhttps?:\/\/[^\s<>"')\]]+/g)].map((m) => m[0]);
|
|
2820
|
+
return json4(200, { id: email.id, links });
|
|
2821
|
+
},
|
|
2822
|
+
"POST /inbound": ({ body, namespace, url }) => {
|
|
2823
|
+
const input = inboundInput(body);
|
|
2824
|
+
if (typeof input === "string") return adminError3(400, input);
|
|
2825
|
+
const { email, event } = runtime.instance(namespace).receive(input, url.origin);
|
|
2826
|
+
const message = hub.publish({
|
|
2827
|
+
namespace,
|
|
2828
|
+
type: event.type,
|
|
2829
|
+
body: event,
|
|
2830
|
+
id: `msg_${email.id.replace(/-/g, "")}`
|
|
2831
|
+
});
|
|
2832
|
+
return json4(201, { id: email.id, webhook: message.id, event });
|
|
2833
|
+
},
|
|
2834
|
+
"GET /inbound": ({ namespace }) => json4(200, { emails: runtime.instance(namespace).inbound() })
|
|
2835
|
+
});
|
|
2836
|
+
var createRuntime2 = (options = {}) => {
|
|
2837
|
+
const { retryDelaysMs, fetch: send, ...endpoint } = options.webhooks ?? { url: "" };
|
|
2838
|
+
const hub = createWebhookHub({
|
|
2839
|
+
signer: signers.svix(),
|
|
2840
|
+
...retryDelaysMs ? { retryDelaysMs } : {},
|
|
2841
|
+
...send ? { fetch: send } : {},
|
|
2842
|
+
endpoints: options.webhooks ? [endpoint] : []
|
|
2843
|
+
});
|
|
2844
|
+
const stats = { forwarded: 0, failed: 0, lastError: null };
|
|
2845
|
+
const target = options.forwardToInbox;
|
|
2846
|
+
const runtime = createRuntime({
|
|
2847
|
+
name: RESEND_NAMESPACE,
|
|
2848
|
+
document,
|
|
2849
|
+
...options.sqlite ? { sqlite: options.sqlite } : {},
|
|
2850
|
+
...options.clock ? { clock: options.clock } : {},
|
|
2851
|
+
...options.seed !== void 0 ? { seed: options.seed } : {},
|
|
2852
|
+
...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
|
|
2853
|
+
...options.onLog ? { onLog: options.onLog } : {},
|
|
2854
|
+
credential: bearerToken,
|
|
2855
|
+
presets: RESEND_PRESETS,
|
|
2856
|
+
webhooks: hub,
|
|
2857
|
+
create: ({ sqlite, namespace, publicNamespace, clock }) => new ResendAPI({
|
|
2858
|
+
sqlite,
|
|
2859
|
+
namespace,
|
|
2860
|
+
publicNamespace,
|
|
2861
|
+
now: clock.now,
|
|
2862
|
+
...target ? {
|
|
2863
|
+
onSent: async (email) => {
|
|
2864
|
+
try {
|
|
2865
|
+
if (await forwardToInbox(target, email, publicNamespace)) stats.forwarded++;
|
|
2866
|
+
else {
|
|
2867
|
+
stats.failed++;
|
|
2868
|
+
stats.lastError = "the inbox refused the message";
|
|
2869
|
+
}
|
|
2870
|
+
} catch (error2) {
|
|
2871
|
+
stats.failed++;
|
|
2872
|
+
stats.lastError = error2 instanceof Error ? error2.message : String(error2);
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
2875
|
+
} : {}
|
|
2876
|
+
}),
|
|
2877
|
+
describe: () => ({
|
|
2878
|
+
webhooks: hub.endpoints("default").length > 0 ? "on" : "off",
|
|
2879
|
+
forwardToInbox: target ? target.url : "off"
|
|
2880
|
+
}),
|
|
2881
|
+
admin: (base) => ({
|
|
2882
|
+
...adminRoutes(hub)(base),
|
|
2883
|
+
"GET /forwarding": () => json4(200, { target: target?.url ?? null, ...stats })
|
|
2884
|
+
})
|
|
2885
|
+
});
|
|
2886
|
+
return Object.assign(runtime, { webhooks: hub, forwarding: () => ({ ...stats }) });
|
|
2887
|
+
};
|
|
2888
|
+
|
|
2889
|
+
// src/index.ts
|
|
2890
|
+
var RESEND_NAMESPACE = "resend";
|
|
2891
|
+
var DOWNLOAD_URL_TTL_MS = 36e5;
|
|
2892
|
+
var error = (statusCode, name, message) => jsonRes(statusCode, { statusCode, name, message });
|
|
2893
|
+
var notFound = (what = "Email") => error(404, "not_found", `${what} not found`);
|
|
2894
|
+
var ADDRESS_FIELDS = /* @__PURE__ */ new Set(["from", "to", "cc", "bcc", "reply_to"]);
|
|
2895
|
+
var validationResponse = (issue) => {
|
|
2896
|
+
const missing = /^missing required property (.+)$/.exec(issue.message);
|
|
2897
|
+
if (missing && issue.path === "") {
|
|
2898
|
+
return error(422, "missing_required_field", `Missing \`${missing[1]}\` field.`);
|
|
2899
|
+
}
|
|
2900
|
+
const field = issue.path.split(".")[0] || "body";
|
|
2901
|
+
if (ADDRESS_FIELDS.has(field)) {
|
|
2902
|
+
return error(
|
|
2903
|
+
422,
|
|
2904
|
+
"validation_error",
|
|
2905
|
+
`Invalid \`${field}\` field. The email address needs to follow the \`email@example.com\` or \`Name <email@example.com>\` format.`
|
|
2906
|
+
);
|
|
2907
|
+
}
|
|
2908
|
+
if (field === "tags") {
|
|
2909
|
+
return error(
|
|
2910
|
+
422,
|
|
2911
|
+
"validation_error",
|
|
2912
|
+
"Invalid `tags` field. Tag names and values must only contain ASCII letters (a\u2013z, A\u2013Z), numbers (0\u20139), underscores (_), or dashes (-), and can be at most 256 characters."
|
|
2913
|
+
);
|
|
2914
|
+
}
|
|
2915
|
+
return error(422, "validation_error", `Invalid \`${field}\` field.`);
|
|
2916
|
+
};
|
|
2917
|
+
var list = (value) => value === void 0 || value === null ? [] : Array.isArray(value) ? value.map(String) : [String(value)];
|
|
2918
|
+
var bareAddress = (value) => (/<([^<>]+)>\s*$/.exec(value)?.[1] ?? value).trim().toLowerCase();
|
|
2919
|
+
var attachmentBytes = (content) => {
|
|
2920
|
+
if (typeof content === "string") {
|
|
2921
|
+
try {
|
|
2922
|
+
return fromBase64(content);
|
|
2923
|
+
} catch {
|
|
2924
|
+
return new TextEncoder().encode(content);
|
|
2925
|
+
}
|
|
2926
|
+
}
|
|
2927
|
+
if (typeof content === "object" && content !== null) {
|
|
2928
|
+
const data = content.data ?? content;
|
|
2929
|
+
if (Array.isArray(data)) return Uint8Array.from(data.map(Number));
|
|
2930
|
+
}
|
|
2931
|
+
return new Uint8Array();
|
|
2932
|
+
};
|
|
2933
|
+
var ResendAPI = class {
|
|
2934
|
+
app;
|
|
2935
|
+
sqlite;
|
|
2936
|
+
state;
|
|
2937
|
+
service;
|
|
2938
|
+
now;
|
|
2939
|
+
publicNamespace;
|
|
2940
|
+
onSent;
|
|
2941
|
+
constructor(options = {}) {
|
|
2942
|
+
const sqlite = bootSqlite(options.sqlite);
|
|
2943
|
+
const namespace = options.namespace ?? RESEND_NAMESPACE;
|
|
2944
|
+
this.now = options.now ?? (() => Date.now());
|
|
2945
|
+
this.publicNamespace = options.publicNamespace;
|
|
2946
|
+
this.onSent = options.onSent;
|
|
2947
|
+
this.state = new ResendState(sqlite, namespace);
|
|
2948
|
+
const handlers = defineOperations({
|
|
2949
|
+
SendEmail: (context) => this.send(context),
|
|
2950
|
+
GetEmail: (context) => this.getEmail(context),
|
|
2951
|
+
GetReceivedEmail: (context) => this.getReceived(context),
|
|
2952
|
+
ListReceivedEmailAttachments: (context) => this.listAttachments(context),
|
|
2953
|
+
DownloadReceivedAttachment: (context) => this.download(context)
|
|
2954
|
+
});
|
|
2955
|
+
this.service = createService({
|
|
2956
|
+
document,
|
|
2957
|
+
handlers,
|
|
2958
|
+
sqlite,
|
|
2959
|
+
namespace,
|
|
2960
|
+
now: this.now,
|
|
2961
|
+
notFound: () => error(404, "not_found", "The requested endpoint does not exist."),
|
|
2962
|
+
onError: (thrown) => {
|
|
2963
|
+
if (thrown instanceof HttpError) return thrown.toResponse();
|
|
2964
|
+
throw thrown;
|
|
2965
|
+
},
|
|
2966
|
+
before: (context) => {
|
|
2967
|
+
if (context.operation.operationId === "DownloadReceivedAttachment") return void 0;
|
|
2968
|
+
if (!bearerToken(context.request)) {
|
|
2969
|
+
return error(
|
|
2970
|
+
401,
|
|
2971
|
+
"missing_api_key",
|
|
2972
|
+
"Missing API key in the authorization header. Include the following header 'Authorization: Bearer YOUR_API_KEY' in the request."
|
|
2973
|
+
);
|
|
2974
|
+
}
|
|
2975
|
+
return void 0;
|
|
2976
|
+
}
|
|
2977
|
+
});
|
|
2978
|
+
this.app = this.service.app;
|
|
2979
|
+
this.sqlite = this.service.sqlite;
|
|
2980
|
+
}
|
|
2981
|
+
fetch(request) {
|
|
2982
|
+
return this.service.fetch(request);
|
|
2983
|
+
}
|
|
2984
|
+
async reset() {
|
|
2985
|
+
await this.service.reset();
|
|
2986
|
+
}
|
|
2987
|
+
/** Every sent email, oldest first. */
|
|
2988
|
+
sent() {
|
|
2989
|
+
return this.state.outbox.list();
|
|
2990
|
+
}
|
|
2991
|
+
iso(offsetMs = 0) {
|
|
2992
|
+
return new Date(this.now() + offsetMs).toISOString();
|
|
2993
|
+
}
|
|
2994
|
+
send(context) {
|
|
2995
|
+
const key = context.request.headers.get("idempotency-key");
|
|
2996
|
+
if (key !== null && (key.length < 1 || key.length > 256)) {
|
|
2997
|
+
return error(
|
|
2998
|
+
400,
|
|
2999
|
+
"invalid_idempotency_key",
|
|
3000
|
+
"Idempotency key must be between 1-256 characters."
|
|
3001
|
+
);
|
|
3002
|
+
}
|
|
3003
|
+
if (context.body.kind !== "json" || typeof context.body.value !== "object" || context.body.value === null || Array.isArray(context.body.value)) {
|
|
3004
|
+
return error(422, "validation_error", "The request body must be a JSON object.");
|
|
3005
|
+
}
|
|
3006
|
+
const body = context.body.value;
|
|
3007
|
+
if (key === null) return this.create(context, body, null);
|
|
3008
|
+
return this.state.idempotency.run(
|
|
3009
|
+
key,
|
|
3010
|
+
requestFingerprint("POST", "/emails", body),
|
|
3011
|
+
{
|
|
3012
|
+
mismatch: () => error(
|
|
3013
|
+
409,
|
|
3014
|
+
"invalid_idempotent_request",
|
|
3015
|
+
"Same idempotency key used with a different request payload."
|
|
3016
|
+
),
|
|
3017
|
+
conflict: () => error(
|
|
3018
|
+
409,
|
|
3019
|
+
"concurrent_idempotent_requests",
|
|
3020
|
+
"Same idempotency key used while original request is still in progress."
|
|
3021
|
+
)
|
|
3022
|
+
},
|
|
3023
|
+
() => this.create(context, body, key),
|
|
3024
|
+
(status) => status === 200
|
|
3025
|
+
);
|
|
3026
|
+
}
|
|
3027
|
+
async create(context, body, idempotencyKey) {
|
|
3028
|
+
const [issue] = bodyIssues(context);
|
|
3029
|
+
if (issue) return validationResponse(issue);
|
|
3030
|
+
const html = typeof body.html === "string" ? body.html : null;
|
|
3031
|
+
const text = typeof body.text === "string" ? body.text : null;
|
|
3032
|
+
if (html === null && text === null) {
|
|
3033
|
+
return error(422, "missing_required_field", "Missing `html` or `text` field.");
|
|
3034
|
+
}
|
|
3035
|
+
const toHeader = list(body.to);
|
|
3036
|
+
const email = {
|
|
3037
|
+
id: this.state.nextId("email"),
|
|
3038
|
+
from: String(body.from),
|
|
3039
|
+
to: toHeader.map(bareAddress),
|
|
3040
|
+
toHeader,
|
|
3041
|
+
cc: list(body.cc).map(bareAddress),
|
|
3042
|
+
bcc: list(body.bcc).map(bareAddress),
|
|
3043
|
+
replyTo: list(body.reply_to),
|
|
3044
|
+
subject: String(body.subject),
|
|
3045
|
+
html,
|
|
3046
|
+
text,
|
|
3047
|
+
tags: Array.isArray(body.tags) ? body.tags : [],
|
|
3048
|
+
headers: body.headers ?? {},
|
|
3049
|
+
attachments: (Array.isArray(body.attachments) ? body.attachments : []).map((raw) => {
|
|
3050
|
+
const attachment = raw;
|
|
3051
|
+
return {
|
|
3052
|
+
filename: String(attachment.filename ?? "attachment"),
|
|
3053
|
+
contentType: typeof attachment.content_type === "string" ? attachment.content_type : null,
|
|
3054
|
+
size: attachmentBytes(attachment.content).length
|
|
3055
|
+
};
|
|
3056
|
+
}),
|
|
3057
|
+
idempotencyKey,
|
|
3058
|
+
scheduledAt: typeof body.scheduled_at === "string" ? body.scheduled_at : null,
|
|
3059
|
+
createdAt: this.iso()
|
|
3060
|
+
};
|
|
3061
|
+
this.state.outbox.record(email);
|
|
3062
|
+
await this.onSent?.(email);
|
|
3063
|
+
return annotateResponse(jsonRes(200, { id: email.id }), { ids: { emailId: email.id } });
|
|
3064
|
+
}
|
|
3065
|
+
getEmail(context) {
|
|
3066
|
+
const email = this.state.outbox.get(context.params.email_id ?? "");
|
|
3067
|
+
if (!email) return notFound();
|
|
3068
|
+
return annotateResponse(
|
|
3069
|
+
jsonRes(200, {
|
|
3070
|
+
object: "email",
|
|
3071
|
+
id: email.id,
|
|
3072
|
+
to: email.toHeader,
|
|
3073
|
+
from: email.from,
|
|
3074
|
+
created_at: email.createdAt,
|
|
3075
|
+
subject: email.subject,
|
|
3076
|
+
html: email.html,
|
|
3077
|
+
text: email.text,
|
|
3078
|
+
bcc: email.bcc.length > 0 ? email.bcc : null,
|
|
3079
|
+
cc: email.cc.length > 0 ? email.cc : null,
|
|
3080
|
+
reply_to: email.replyTo.length > 0 ? email.replyTo : null,
|
|
3081
|
+
last_event: email.scheduledAt ? "scheduled" : "delivered",
|
|
3082
|
+
scheduled_at: email.scheduledAt,
|
|
3083
|
+
tags: email.tags
|
|
3084
|
+
}),
|
|
3085
|
+
{ ids: { emailId: email.id } }
|
|
3086
|
+
);
|
|
3087
|
+
}
|
|
3088
|
+
/** Store an inbound email and build the `email.received` event for it. */
|
|
3089
|
+
receive(input, origin) {
|
|
3090
|
+
const id = this.state.nextId("received");
|
|
3091
|
+
const attachments = (input.attachments ?? []).map((attachment) => {
|
|
3092
|
+
const bytes = attachmentBytes(attachment.content);
|
|
3093
|
+
return {
|
|
3094
|
+
id: this.state.nextId("attachment"),
|
|
3095
|
+
filename: attachment.filename,
|
|
3096
|
+
content_type: attachment.contentType ?? "application/octet-stream",
|
|
3097
|
+
content_disposition: attachment.contentDisposition ?? "attachment",
|
|
3098
|
+
content_id: attachment.contentId ?? null,
|
|
3099
|
+
size: bytes.length,
|
|
3100
|
+
content: toBase64(bytes)
|
|
3101
|
+
};
|
|
3102
|
+
});
|
|
3103
|
+
const email = {
|
|
3104
|
+
id,
|
|
3105
|
+
from: input.from,
|
|
3106
|
+
to: list(input.to),
|
|
3107
|
+
cc: list(input.cc),
|
|
3108
|
+
bcc: list(input.bcc),
|
|
3109
|
+
replyTo: list(input.replyTo),
|
|
3110
|
+
subject: input.subject ?? null,
|
|
3111
|
+
html: input.html ?? null,
|
|
3112
|
+
text: input.text ?? null,
|
|
3113
|
+
headers: input.headers ?? {},
|
|
3114
|
+
messageId: input.messageId ?? `<${id}@inbound.resend.mock>`,
|
|
3115
|
+
attachments,
|
|
3116
|
+
createdAt: this.iso()
|
|
3117
|
+
};
|
|
3118
|
+
this.state.received.insert(id, email);
|
|
3119
|
+
for (const attachment of attachments) {
|
|
3120
|
+
this.state.attachmentIndex.insert(attachment.id, { emailId: id });
|
|
3121
|
+
}
|
|
3122
|
+
const event = {
|
|
3123
|
+
type: "email.received",
|
|
3124
|
+
created_at: email.createdAt,
|
|
3125
|
+
data: {
|
|
3126
|
+
email_id: id,
|
|
3127
|
+
created_at: email.createdAt,
|
|
3128
|
+
from: email.from,
|
|
3129
|
+
to: email.to,
|
|
3130
|
+
cc: email.cc,
|
|
3131
|
+
bcc: email.bcc,
|
|
3132
|
+
subject: email.subject,
|
|
3133
|
+
message_id: email.messageId,
|
|
3134
|
+
attachments: attachments.map((attachment) => ({
|
|
3135
|
+
...this.attachmentMeta(attachment),
|
|
3136
|
+
...input.inline ? { size: attachment.size, download_url: this.downloadUrl(origin, attachment.id) } : {}
|
|
3137
|
+
})),
|
|
3138
|
+
...input.inline ? {
|
|
3139
|
+
text: email.text,
|
|
3140
|
+
html: email.html,
|
|
3141
|
+
headers: Object.entries(email.headers).map(([name, value]) => ({ name, value }))
|
|
3142
|
+
} : {}
|
|
3143
|
+
}
|
|
3144
|
+
};
|
|
3145
|
+
return { email, event };
|
|
3146
|
+
}
|
|
3147
|
+
/** Every received email, oldest first. */
|
|
3148
|
+
inbound() {
|
|
3149
|
+
return this.state.received.list({ order: "oldest" }).map((row) => row.value);
|
|
3150
|
+
}
|
|
3151
|
+
attachmentMeta(attachment) {
|
|
3152
|
+
return {
|
|
3153
|
+
id: attachment.id,
|
|
3154
|
+
filename: attachment.filename,
|
|
3155
|
+
content_type: attachment.content_type,
|
|
3156
|
+
content_disposition: attachment.content_disposition,
|
|
3157
|
+
content_id: attachment.content_id
|
|
3158
|
+
};
|
|
3159
|
+
}
|
|
3160
|
+
downloadUrl(origin, attachmentId) {
|
|
3161
|
+
const prefix = this.publicNamespace && this.publicNamespace !== "default" ? `/ns/${encodeURIComponent(this.publicNamespace)}` : "";
|
|
3162
|
+
return `${origin}${prefix}/downloads/inbound/${attachmentId}`;
|
|
3163
|
+
}
|
|
3164
|
+
getReceived(context) {
|
|
3165
|
+
const email = this.state.received.get(context.params.email_id ?? "");
|
|
3166
|
+
if (!email) return notFound();
|
|
3167
|
+
return annotateResponse(
|
|
3168
|
+
jsonRes(200, {
|
|
3169
|
+
object: "email",
|
|
3170
|
+
id: email.id,
|
|
3171
|
+
to: email.to,
|
|
3172
|
+
from: email.from,
|
|
3173
|
+
cc: email.cc,
|
|
3174
|
+
bcc: email.bcc,
|
|
3175
|
+
reply_to: email.replyTo,
|
|
3176
|
+
created_at: email.createdAt,
|
|
3177
|
+
subject: email.subject,
|
|
3178
|
+
html: email.html,
|
|
3179
|
+
text: email.text,
|
|
3180
|
+
headers: email.headers,
|
|
3181
|
+
message_id: email.messageId,
|
|
3182
|
+
attachments: email.attachments.map((a) => this.attachmentMeta(a))
|
|
3183
|
+
}),
|
|
3184
|
+
{ ids: { receivedEmailId: email.id } }
|
|
3185
|
+
);
|
|
3186
|
+
}
|
|
3187
|
+
listAttachments(context) {
|
|
3188
|
+
const email = this.state.received.get(context.params.email_id ?? "");
|
|
3189
|
+
if (!email) return notFound();
|
|
3190
|
+
return annotateResponse(
|
|
3191
|
+
jsonRes(200, {
|
|
3192
|
+
object: "list",
|
|
3193
|
+
has_more: false,
|
|
3194
|
+
data: email.attachments.map((attachment) => ({
|
|
3195
|
+
...this.attachmentMeta(attachment),
|
|
3196
|
+
size: attachment.size,
|
|
3197
|
+
download_url: this.downloadUrl(context.url.origin, attachment.id),
|
|
3198
|
+
expires_at: this.iso(DOWNLOAD_URL_TTL_MS)
|
|
3199
|
+
}))
|
|
3200
|
+
}),
|
|
3201
|
+
{ ids: { receivedEmailId: email.id } }
|
|
3202
|
+
);
|
|
3203
|
+
}
|
|
3204
|
+
download(context) {
|
|
3205
|
+
const id = context.params.attachment_id ?? "";
|
|
3206
|
+
const owner = this.state.attachmentIndex.get(id);
|
|
3207
|
+
const attachment = owner ? this.state.received.get(owner.emailId)?.attachments.find((a) => a.id === id) : void 0;
|
|
3208
|
+
if (!attachment) return notFound("Attachment");
|
|
3209
|
+
const bytes = fromBase64(attachment.content);
|
|
3210
|
+
return new Response(bytes, {
|
|
3211
|
+
status: 200,
|
|
3212
|
+
headers: {
|
|
3213
|
+
"content-type": attachment.content_type,
|
|
3214
|
+
"content-length": String(bytes.length),
|
|
3215
|
+
"content-disposition": `attachment; filename="${attachment.filename.replace(/"/g, "")}"`
|
|
3216
|
+
}
|
|
3217
|
+
});
|
|
3218
|
+
}
|
|
3219
|
+
};
|
|
3220
|
+
|
|
3221
|
+
export {
|
|
3222
|
+
document,
|
|
3223
|
+
operationIds,
|
|
3224
|
+
supportedOperationIds,
|
|
3225
|
+
RESEND_PRESETS,
|
|
3226
|
+
forwardToInbox,
|
|
3227
|
+
createRuntime2 as createRuntime,
|
|
3228
|
+
RESEND_NAMESPACE,
|
|
3229
|
+
DOWNLOAD_URL_TTL_MS,
|
|
3230
|
+
bareAddress,
|
|
3231
|
+
ResendAPI
|
|
3232
|
+
};
|
|
3233
|
+
//# sourceMappingURL=chunk-MAW2TLUJ.js.map
|